repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
saradbowman/osf.io | admin/registration_providers/views.py | 16869 | import json
from django.http import HttpResponse
from django.core import serializers
from django.core.management import call_command
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect
from django.views.generic import View, CreateView, ListView, DetailView, UpdateView, DeleteView, TemplateView
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.forms.models import model_to_dict
from django.http import JsonResponse
from admin.registration_providers.forms import RegistrationProviderForm, RegistrationProviderCustomTaxonomyForm
from admin.base import settings
from admin.base.forms import ImportFileForm
from osf.models import RegistrationProvider, NodeLicense
class CreateRegistrationProvider(PermissionRequiredMixin, CreateView):
raise_exception = True
permission_required = 'osf.change_registrationprovider'
template_name = 'registration_providers/create.html'
model = RegistrationProvider
form_class = RegistrationProviderForm
success_url = reverse_lazy('registration_providers:list')
def form_valid(self, form):
self.object = form.save(commit=False)
self.object._creator = self.request.user
self.object.save()
return super(CreateRegistrationProvider, self).form_valid(form)
def get_context_data(self, *args, **kwargs):
kwargs['import_form'] = ImportFileForm()
kwargs['show_taxonomies'] = True
kwargs['tinymce_apikey'] = settings.TINYMCE_APIKEY
return super(CreateRegistrationProvider, self).get_context_data(*args, **kwargs)
class RegistrationProviderList(PermissionRequiredMixin, ListView):
paginate_by = 25
template_name = 'registration_providers/list.html'
ordering = 'name'
permission_required = 'osf.view_registrationprovider'
raise_exception = True
model = RegistrationProvider
def get_queryset(self):
return RegistrationProvider.objects.all().order_by(self.ordering)
def get_context_data(self, **kwargs):
query_set = kwargs.pop('object_list', self.object_list)
page_size = self.get_paginate_by(query_set)
paginator, page, query_set, is_paginated = self.paginate_queryset(
query_set, page_size)
return {
'registration_providers': query_set,
'page': page,
}
class RegistrationProviderDetail(PermissionRequiredMixin, View):
permission_required = 'osf.change_registrationprovider'
raise_exception = True
def get(self, request, *args, **kwargs):
view = RegistrationProviderDisplay.as_view()
return view(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
view = RegistrationProviderChangeForm.as_view()
return view(request, *args, **kwargs)
class RegistrationProviderDisplay(PermissionRequiredMixin, DetailView):
model = RegistrationProvider
template_name = 'registration_providers/detail.html'
permission_required = 'osf.view_registrationprovider'
raise_exception = True
def get_object(self, queryset=None):
return RegistrationProvider.objects.get(id=self.kwargs.get('registration_provider_id'))
def get_context_data(self, *args, **kwargs):
registration_provider = self.get_object()
registration_provider_attributes = model_to_dict(registration_provider)
registration_provider_attributes['default_license'] = registration_provider.default_license.name if registration_provider.default_license else None
# compile html list of licenses_acceptable so we can render them as a list
licenses_acceptable = list(registration_provider.licenses_acceptable.values_list('name', flat=True))
licenses_html = '<ul>'
for license in licenses_acceptable:
licenses_html += '<li>{}</li>'.format(license)
licenses_html += '</ul>'
registration_provider_attributes['licenses_acceptable'] = licenses_html
# compile html list of subjects
subject_ids = registration_provider.all_subjects.values_list('id', flat=True)
kwargs['registration_provider'] = registration_provider_attributes
kwargs['subject_ids'] = list(subject_ids)
subject_html = '<ul class="subjects-list">'
for parent in registration_provider.top_level_subjects:
if parent.id in subject_ids:
mapped_text = ''
if parent.bepress_subject and parent.text != parent.bepress_subject.text:
mapped_text = ' (mapped from {})'.format(parent.bepress_subject.text)
hash_id = abs(hash(parent.text))
subject_html = subject_html + '<li data-id={}>{}'.format(hash_id, parent.text) + mapped_text + '</li>'
child_html = '<ul class="three-cols" data-id={}>'.format(hash_id)
for child in parent.children.all():
grandchild_html = ''
if child.id in subject_ids:
child_mapped_text = ''
if child.bepress_subject and child.text != child.bepress_subject.text:
child_mapped_text = ' (mapped from {})'.format(child.bepress_subject.text)
child_html = child_html + '<li>{}'.format(child.text) + child_mapped_text + '</li>'
grandchild_html = '<ul>'
for grandchild in child.children.all():
if grandchild.id in subject_ids:
grandchild_mapped_text = ''
if grandchild.bepress_subject and grandchild.text != grandchild.bepress_subject.text:
grandchild_mapped_text = ' (mapped from {})'.format(grandchild.bepress_subject.text)
grandchild_html = grandchild_html + '<li>{}'.format(grandchild.text) + grandchild_mapped_text + '</li>'
grandchild_html += '</ul>'
child_html += grandchild_html
child_html += '</ul>'
subject_html += child_html
subject_html += '</ul>'
registration_provider_attributes['subjects'] = subject_html
fields = model_to_dict(registration_provider)
kwargs['show_taxonomies'] = False if registration_provider.subjects.exists() else True
kwargs['form'] = RegistrationProviderForm(initial=fields)
kwargs['import_form'] = ImportFileForm()
kwargs['taxonomy_form'] = RegistrationProviderCustomTaxonomyForm()
# set api key for tinymce
kwargs['tinymce_apikey'] = settings.TINYMCE_APIKEY
return kwargs
class RegistrationProviderChangeForm(PermissionRequiredMixin, UpdateView):
permission_required = 'osf.change_registrationprovider'
raise_exception = True
model = RegistrationProvider
form_class = RegistrationProviderForm
def form_invalid(self, form):
super(RegistrationProviderChangeForm, self).form_invalid(form)
err_message = ''
for item in form.errors.values():
err_message = err_message + item + '\n'
return HttpResponse(err_message, status=409)
def get_context_data(self, *args, **kwargs):
kwargs['import_form'] = ImportFileForm()
return super(RegistrationProviderChangeForm, self).get_context_data(*args, **kwargs)
def get_object(self, queryset=None):
provider_id = self.kwargs.get('registration_provider_id')
return RegistrationProvider.objects.get(id=provider_id)
def get_success_url(self, *args, **kwargs):
return reverse_lazy('registration_providers:detail',
kwargs={'registration_provider_id': self.kwargs.get('registration_provider_id')})
class DeleteRegistrationProvider(PermissionRequiredMixin, DeleteView):
permission_required = 'osf.delete_registrationprovider'
raise_exception = True
template_name = 'registration_providers/confirm_delete.html'
success_url = reverse_lazy('registration_providers:list')
def delete(self, request, *args, **kwargs):
provider = RegistrationProvider.objects.get(id=self.kwargs['registration_provider_id'])
if provider.registrations.count() > 0:
return redirect('registration_providers:cannot_delete', registration_provider_id=provider.pk)
return super(DeleteRegistrationProvider, self).delete(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
provider = RegistrationProvider.objects.get(id=self.kwargs['registration_provider_id'])
if provider.registrations.count() > 0:
return redirect('registration_providers:cannot_delete', registration_provider_id=provider.pk)
return super(DeleteRegistrationProvider, self).get(request, *args, **kwargs)
def get_object(self, queryset=None):
return RegistrationProvider.objects.get(id=self.kwargs['registration_provider_id'])
def get_context_data(self, *args, **kwargs):
registration_provider = self.get_object()
kwargs['provider_name'] = registration_provider.name
kwargs['has_collected_submissions'] = registration_provider.primary_collection.collectionsubmission_set.exists()
kwargs['collected_submissions_count'] = registration_provider.primary_collection.collectionsubmission_set.count()
kwargs['provider_id'] = registration_provider.id
return super(DeleteRegistrationProvider, self).get_context_data(*args, **kwargs)
class CannotDeleteProvider(TemplateView):
template_name = 'registration_providers/cannot_delete.html'
def get_context_data(self, **kwargs):
context = super(CannotDeleteProvider, self).get_context_data(**kwargs)
context['provider'] = RegistrationProvider.objects.get(id=self.kwargs['registration_provider_id'])
return context
class ExportRegistrationProvider(PermissionRequiredMixin, View):
permission_required = 'osf.change_registrationprovider'
raise_exception = True
def get(self, request, *args, **kwargs):
registration_provider = RegistrationProvider.objects.get(id=self.kwargs['registration_provider_id'])
data = serializers.serialize('json', [registration_provider])
cleaned_data = json.loads(data)[0]
cleaned_fields = cleaned_data['fields']
cleaned_fields.pop('primary_collection', None)
cleaned_fields['licenses_acceptable'] = [node_license.license_id for node_license in registration_provider.licenses_acceptable.all()]
cleaned_fields['default_license'] = registration_provider.default_license.license_id if registration_provider.default_license else ''
cleaned_fields['subjects'] = self.serialize_subjects(registration_provider)
cleaned_data['fields'] = cleaned_fields
filename = '{}_export.json'.format(registration_provider.name)
response = HttpResponse(json.dumps(cleaned_data), content_type='text/json')
response['Content-Disposition'] = 'attachment; filename={}'.format(filename)
return response
def serialize_subjects(self, provider):
if provider._id != 'osf' and provider.subjects.count():
result = {}
result['include'] = []
result['exclude'] = []
result['custom'] = {
subject.text: {
'parent': subject.parent.text if subject.parent else '',
'bepress': subject.bepress_subject.text
}
for subject in provider.subjects.all()
}
return result
class ImportRegistrationProvider(PermissionRequiredMixin, View):
permission_required = 'osf.change_registrationprovider'
raise_exception = True
def post(self, request, *args, **kwargs):
form = ImportFileForm(request.POST, request.FILES)
if form.is_valid():
file_str = self.parse_file(request.FILES['file'])
file_json = json.loads(file_str)
cleaned_result = file_json['fields']
registration_provider = self.create_or_update_provider(cleaned_result)
return redirect('registration_providers:detail', registration_provider_id=registration_provider.id)
def parse_file(self, f):
parsed_file = ''
for chunk in f.chunks():
parsed_file += chunk.decode('utf-8')
return parsed_file
def get_page_provider(self):
page_provider_id = self.kwargs.get('registration_provider_id', '')
if page_provider_id:
return RegistrationProvider.objects.get(id=page_provider_id)
def add_subjects(self, provider, subject_data):
call_command('populate_custom_taxonomies', '--provider', provider._id, '--data', json.dumps(subject_data), '--type', 'osf.registrationprovider')
def create_or_update_provider(self, provider_data):
provider = self.get_page_provider()
licenses = [NodeLicense.objects.get(license_id=license_id) for license_id in provider_data.pop('licenses_acceptable', [])]
default_license = provider_data.pop('default_license', False)
subject_data = provider_data.pop('subjects', False)
provider_data.pop('additional_providers')
if provider:
for key, val in provider_data.items():
setattr(provider, key, val)
provider.save()
else:
provider = RegistrationProvider(**provider_data)
provider._creator = self.request.user
provider.save()
if licenses:
provider.licenses_acceptable = licenses
if default_license:
provider.default_license = NodeLicense.objects.get(license_id=default_license)
# Only adds the JSON taxonomy if there is no existing taxonomy data
if subject_data and not provider.subjects.count():
self.add_subjects(provider, subject_data)
return provider
class ProcessCustomTaxonomy(PermissionRequiredMixin, View):
permission_required = 'osf.change_registrationprovider'
raise_exception = True
def post(self, request, *args, **kwargs):
# Import here to avoid test DB access errors when importing registration provider views
from osf.management.commands.populate_custom_taxonomies import validate_input, migrate
provider_form = RegistrationProviderCustomTaxonomyForm(request.POST)
if provider_form.is_valid():
provider = RegistrationProvider.objects.get(id=provider_form.cleaned_data['provider_id'])
try:
taxonomy_json = json.loads(provider_form.cleaned_data['custom_taxonomy_json'])
if request.is_ajax():
# An ajax request is for validation only, so run that validation!
try:
response_data = validate_input(
custom_provider=provider,
data=taxonomy_json,
provider_type='osf.registrationprovider',
add_missing=provider_form.cleaned_data['add_missing'])
if response_data:
added_subjects = [subject.text for subject in response_data]
response_data = {'message': 'Custom taxonomy validated with added subjects: {}'.format(added_subjects), 'feedback_type': 'success'}
except (RuntimeError, AssertionError) as script_feedback:
response_data = {'message': script_feedback.message, 'feedback_type': 'error'}
if not response_data:
response_data = {'message': 'Custom taxonomy validated!', 'feedback_type': 'success'}
else:
# Actually do the migration of the custom taxonomies
migrate(
provider=provider._id,
data=taxonomy_json,
provider_type='osf.registrationprovider',
add_missing=provider_form.cleaned_data['add_missing'])
return redirect('registration_providers:detail', registration_provider_id=provider.id)
except (ValueError, RuntimeError) as error:
response_data = {
'message': 'There is an error with the submitted JSON or the provider. Here are some details: ' + error.message,
'feedback_type': 'error'
}
else:
response_data = {
'message': 'There is a problem with the form. Here are some details: ' + unicode(provider_form.errors),
'feedback_type': 'error'
}
# Return a JsonResponse with the JSON error or the validation error if it's not doing an actual migration
return JsonResponse(response_data)
| apache-2.0 |
meteorcloudy/bazel | third_party/java/proguard/proguard6.2.2/src/proguard/classfile/attribute/annotation/AnnotationElementValue.java | 2188 | /*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2019 Guardsquare NV
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.classfile.attribute.annotation;
import proguard.classfile.*;
import proguard.classfile.attribute.annotation.visitor.*;
/**
* This ElementValue represents an annotation element value.
*
* @author Eric Lafortune
*/
public class AnnotationElementValue extends ElementValue
{
public Annotation annotationValue;
/**
* Creates an uninitialized AnnotationElementValue.
*/
public AnnotationElementValue()
{
}
/**
* Creates an initialized AnnotationElementValue.
*/
public AnnotationElementValue(int u2elementNameIndex,
Annotation annotationValue)
{
super(u2elementNameIndex);
this.annotationValue = annotationValue;
}
/**
* Applies the given visitor to the annotation.
*/
public void annotationAccept(Clazz clazz, AnnotationVisitor annotationVisitor)
{
annotationVisitor.visitAnnotation(clazz, annotationValue);
}
// Implementations for ElementValue.
public char getTag()
{
return ClassConstants.ELEMENT_VALUE_ANNOTATION;
}
public void accept(Clazz clazz, Annotation annotation, ElementValueVisitor elementValueVisitor)
{
elementValueVisitor.visitAnnotationElementValue(clazz, annotation, this);
}
}
| apache-2.0 |
spinolacastro/origin | Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/helpers.go | 16088 | /*
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 util
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
"time"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/errors"
"k8s.io/kubernetes/pkg/api/meta"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
"k8s.io/kubernetes/pkg/kubectl"
"k8s.io/kubernetes/pkg/kubectl/resource"
"k8s.io/kubernetes/pkg/runtime"
utilerrors "k8s.io/kubernetes/pkg/util/errors"
"k8s.io/kubernetes/pkg/util/strategicpatch"
"github.com/evanphx/json-patch"
"github.com/golang/glog"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
const (
ApplyAnnotationsFlag = "save-config"
)
type debugError interface {
DebugError() (msg string, args []interface{})
}
// AddSourceToErr adds handleResourcePrefix and source string to error message.
// verb is the string like "creating", "deleting" etc.
// souce is the filename or URL to the template file(*.json or *.yaml), or stdin to use to handle the resource.
func AddSourceToErr(verb string, source string, err error) error {
if source != "" {
if statusError, ok := err.(errors.APIStatus); ok {
status := statusError.Status()
status.Message = fmt.Sprintf("error when %s %q: %v", verb, source, status.Message)
return &errors.StatusError{ErrStatus: status}
}
return fmt.Errorf("error when %s %q: %v", verb, source, err)
}
return err
}
var fatalErrHandler = fatal
// BehaviorOnFatal allows you to override the default behavior when a fatal
// error occurs, which is call os.Exit(1). You can pass 'panic' as a function
// here if you prefer the panic() over os.Exit(1).
func BehaviorOnFatal(f func(string)) {
fatalErrHandler = f
}
// DefaultBehaviorOnFatal allows you to undo any previous override. Useful in
// tests.
func DefaultBehaviorOnFatal() {
fatalErrHandler = fatal
}
// fatal prints the message and then exits. If V(2) or greater, glog.Fatal
// is invoked for extended information.
func fatal(msg string) {
// add newline if needed
if !strings.HasSuffix(msg, "\n") {
msg += "\n"
}
if glog.V(2) {
glog.FatalDepth(2, msg)
}
fmt.Fprint(os.Stderr, msg)
os.Exit(1)
}
// CheckErr prints a user friendly error to STDERR and exits with a non-zero
// exit code. Unrecognized errors will be printed with an "error: " prefix.
//
// This method is generic to the command in use and may be used by non-Kubectl
// commands.
func CheckErr(err error) {
checkErr(err, fatalErrHandler)
}
func checkErr(err error, handleErr func(string)) {
if err == nil {
return
}
if errors.IsInvalid(err) {
details := err.(*errors.StatusError).Status().Details
prefix := fmt.Sprintf("The %s %q is invalid.\n", details.Kind, details.Name)
errs := statusCausesToAggrError(details.Causes)
handleErr(MultilineError(prefix, errs))
}
if meta.IsNoResourceMatchError(err) {
noMatch := err.(*meta.NoResourceMatchError)
switch {
case len(noMatch.PartialResource.Group) > 0 && len(noMatch.PartialResource.Version) > 0:
handleErr(fmt.Sprintf("the server doesn't have a resource type %q in group %q and version %q", noMatch.PartialResource.Resource, noMatch.PartialResource.Group, noMatch.PartialResource.Version))
case len(noMatch.PartialResource.Group) > 0:
handleErr(fmt.Sprintf("the server doesn't have a resource type %q in group %q", noMatch.PartialResource.Resource, noMatch.PartialResource.Group))
case len(noMatch.PartialResource.Version) > 0:
handleErr(fmt.Sprintf("the server doesn't have a resource type %q in version %q", noMatch.PartialResource.Resource, noMatch.PartialResource.Version))
default:
handleErr(fmt.Sprintf("the server doesn't have a resource type %q", noMatch.PartialResource.Resource))
}
return
}
// handle multiline errors
if clientcmd.IsConfigurationInvalid(err) {
handleErr(MultilineError("Error in configuration: ", err))
}
if agg, ok := err.(utilerrors.Aggregate); ok && len(agg.Errors()) > 0 {
handleErr(MultipleErrors("", agg.Errors()))
}
msg, ok := StandardErrorMessage(err)
if !ok {
msg = err.Error()
if !strings.HasPrefix(msg, "error: ") {
msg = fmt.Sprintf("error: %s", msg)
}
}
handleErr(msg)
}
func statusCausesToAggrError(scs []unversioned.StatusCause) utilerrors.Aggregate {
errs := make([]error, len(scs))
for i, sc := range scs {
errs[i] = fmt.Errorf("%s: %s", sc.Field, sc.Message)
}
return utilerrors.NewAggregate(errs)
}
// StandardErrorMessage translates common errors into a human readable message, or returns
// false if the error is not one of the recognized types. It may also log extended
// information to glog.
//
// This method is generic to the command in use and may be used by non-Kubectl
// commands.
func StandardErrorMessage(err error) (string, bool) {
if debugErr, ok := err.(debugError); ok {
glog.V(4).Infof(debugErr.DebugError())
}
status, isStatus := err.(errors.APIStatus)
switch {
case isStatus:
switch s := status.Status(); {
case s.Reason == "Unauthorized":
return fmt.Sprintf("error: You must be logged in to the server (%s)", s.Message), true
default:
return fmt.Sprintf("Error from server: %s", err.Error()), true
}
case errors.IsUnexpectedObjectError(err):
return fmt.Sprintf("Server returned an unexpected response: %s", err.Error()), true
}
switch t := err.(type) {
case *url.Error:
glog.V(4).Infof("Connection error: %s %s: %v", t.Op, t.URL, t.Err)
switch {
case strings.Contains(t.Err.Error(), "connection refused"):
host := t.URL
if server, err := url.Parse(t.URL); err == nil {
host = server.Host
}
return fmt.Sprintf("The connection to the server %s was refused - did you specify the right host or port?", host), true
}
return fmt.Sprintf("Unable to connect to the server: %v", t.Err), true
}
return "", false
}
// MultilineError returns a string representing an error that splits sub errors into their own
// lines. The returned string will end with a newline.
func MultilineError(prefix string, err error) string {
if agg, ok := err.(utilerrors.Aggregate); ok {
errs := utilerrors.Flatten(agg).Errors()
buf := &bytes.Buffer{}
switch len(errs) {
case 0:
return fmt.Sprintf("%s%v\n", prefix, err)
case 1:
return fmt.Sprintf("%s%v\n", prefix, messageForError(errs[0]))
default:
fmt.Fprintln(buf, prefix)
for _, err := range errs {
fmt.Fprintf(buf, "* %v\n", messageForError(err))
}
return buf.String()
}
}
return fmt.Sprintf("%s%s\n", prefix, err)
}
// MultipleErrors returns a newline delimited string containing
// the prefix and referenced errors in standard form.
func MultipleErrors(prefix string, errs []error) string {
buf := &bytes.Buffer{}
for _, err := range errs {
fmt.Fprintf(buf, "%s%v\n", prefix, messageForError(err))
}
return buf.String()
}
// messageForError returns the string representing the error.
func messageForError(err error) string {
msg, ok := StandardErrorMessage(err)
if !ok {
msg = err.Error()
}
return msg
}
func UsageError(cmd *cobra.Command, format string, args ...interface{}) error {
msg := fmt.Sprintf(format, args...)
return fmt.Errorf("%s\nSee '%s -h' for help and examples.", msg, cmd.CommandPath())
}
// Whether this cmd need watching objects.
func isWatch(cmd *cobra.Command) bool {
if w, err := cmd.Flags().GetBool("watch"); w && err == nil {
return true
}
if wo, err := cmd.Flags().GetBool("watch-only"); wo && err == nil {
return true
}
return false
}
func getFlag(cmd *cobra.Command, flag string) *pflag.Flag {
f := cmd.Flags().Lookup(flag)
if f == nil {
glog.Fatalf("flag accessed but not defined for command %s: %s", cmd.Name(), flag)
}
return f
}
func GetFlagString(cmd *cobra.Command, flag string) string {
s, err := cmd.Flags().GetString(flag)
if err != nil {
glog.Fatalf("err accessing flag %s for command %s: %v", flag, cmd.Name(), err)
}
return s
}
// GetFlagStringList can be used to accept multiple argument with flag repetition (e.g. -f arg1 -f arg2 ...)
func GetFlagStringSlice(cmd *cobra.Command, flag string) []string {
s, err := cmd.Flags().GetStringSlice(flag)
if err != nil {
glog.Fatalf("err accessing flag %s for command %s: %v", flag, cmd.Name(), err)
}
return s
}
// GetWideFlag is used to determine if "-o wide" is used
func GetWideFlag(cmd *cobra.Command) bool {
f := cmd.Flags().Lookup("output")
if f.Value.String() == "wide" {
return true
}
return false
}
func GetFlagBool(cmd *cobra.Command, flag string) bool {
b, err := cmd.Flags().GetBool(flag)
if err != nil {
glog.Fatalf("err accessing flag %s for command %s: %v", flag, cmd.Name(), err)
}
return b
}
// Assumes the flag has a default value.
func GetFlagInt(cmd *cobra.Command, flag string) int {
i, err := cmd.Flags().GetInt(flag)
if err != nil {
glog.Fatalf("err accessing flag %s for command %s: %v", flag, cmd.Name(), err)
}
return i
}
// Assumes the flag has a default value.
func GetFlagInt64(cmd *cobra.Command, flag string) int64 {
i, err := cmd.Flags().GetInt64(flag)
if err != nil {
glog.Fatalf("err accessing flag %s for command %s: %v", flag, cmd.Name(), err)
}
return i
}
func GetFlagDuration(cmd *cobra.Command, flag string) time.Duration {
d, err := cmd.Flags().GetDuration(flag)
if err != nil {
glog.Fatalf("err accessing flag %s for command %s: %v", flag, cmd.Name(), err)
}
return d
}
func AddValidateFlags(cmd *cobra.Command) {
cmd.Flags().Bool("validate", true, "If true, use a schema to validate the input before sending it")
cmd.Flags().String("schema-cache-dir", fmt.Sprintf("~/%s/%s", clientcmd.RecommendedHomeDir, clientcmd.RecommendedSchemaName), fmt.Sprintf("If non-empty, load/store cached API schemas in this directory, default is '$HOME/%s/%s'", clientcmd.RecommendedHomeDir, clientcmd.RecommendedSchemaName))
cmd.MarkFlagFilename("schema-cache-dir")
}
func AddApplyAnnotationFlags(cmd *cobra.Command) {
cmd.Flags().Bool(ApplyAnnotationsFlag, false, "If true, the configuration of current object will be saved in its annotation. This is useful when you want to perform kubectl apply on this object in the future.")
}
// AddGeneratorFlags adds flags common to resource generation commands
// TODO: need to take a pass at other generator commands to use this set of flags
func AddGeneratorFlags(cmd *cobra.Command, defaultGenerator string) {
cmd.Flags().String("generator", defaultGenerator, "The name of the API generator to use.")
cmd.Flags().Bool("dry-run", false, "If true, only print the object that would be sent, without sending it.")
}
func ReadConfigDataFromReader(reader io.Reader, source string) ([]byte, error) {
data, err := ioutil.ReadAll(reader)
if err != nil {
return nil, err
}
if len(data) == 0 {
return nil, fmt.Errorf(`Read from %s but no data found`, source)
}
return data, nil
}
// ReadConfigData reads the bytes from the specified filesystem or network
// location or from stdin if location == "-".
// TODO: replace with resource.Builder
func ReadConfigData(location string) ([]byte, error) {
if len(location) == 0 {
return nil, fmt.Errorf("location given but empty")
}
if location == "-" {
// Read from stdin.
return ReadConfigDataFromReader(os.Stdin, "stdin ('-')")
}
// Use the location as a file path or URL.
return ReadConfigDataFromLocation(location)
}
// TODO: replace with resource.Builder
func ReadConfigDataFromLocation(location string) ([]byte, error) {
// we look for http:// or https:// to determine if valid URL, otherwise do normal file IO
if strings.Index(location, "http://") == 0 || strings.Index(location, "https://") == 0 {
resp, err := http.Get(location)
if err != nil {
return nil, fmt.Errorf("unable to access URL %s: %v\n", location, err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("unable to read URL, server reported %d %s", resp.StatusCode, resp.Status)
}
return ReadConfigDataFromReader(resp.Body, location)
} else {
file, err := os.Open(location)
if err != nil {
return nil, fmt.Errorf("unable to read %s: %v\n", location, err)
}
return ReadConfigDataFromReader(file, location)
}
}
// Merge requires JSON serialization
// TODO: merge assumes JSON serialization, and does not properly abstract API retrieval
func Merge(codec runtime.Codec, dst runtime.Object, fragment, kind string) (runtime.Object, error) {
// encode dst into versioned json and apply fragment directly too it
target, err := runtime.Encode(codec, dst)
if err != nil {
return nil, err
}
patched, err := jsonpatch.MergePatch(target, []byte(fragment))
if err != nil {
return nil, err
}
out, err := runtime.Decode(codec, patched)
if err != nil {
return nil, err
}
return out, nil
}
// DumpReaderToFile writes all data from the given io.Reader to the specified file
// (usually for temporary use).
func DumpReaderToFile(reader io.Reader, filename string) error {
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
defer f.Close()
if err != nil {
return err
}
buffer := make([]byte, 1024)
for {
count, err := reader.Read(buffer)
if err == io.EOF {
break
}
if err != nil {
return err
}
_, err = f.Write(buffer[:count])
if err != nil {
return err
}
}
return nil
}
// UpdateObject updates resource object with updateFn
func UpdateObject(info *resource.Info, codec runtime.Codec, updateFn func(runtime.Object) error) (runtime.Object, error) {
helper := resource.NewHelper(info.Client, info.Mapping)
if err := updateFn(info.Object); err != nil {
return nil, err
}
// Update the annotation used by kubectl apply
if err := kubectl.UpdateApplyAnnotation(info, codec); err != nil {
return nil, err
}
if _, err := helper.Replace(info.Namespace, info.Name, true, info.Object); err != nil {
return nil, err
}
return info.Object, nil
}
// AddCmdRecordFlag adds --record flag to command
func AddRecordFlag(cmd *cobra.Command) {
cmd.Flags().Bool("record", false, "Record current kubectl command in the resource annotation.")
}
func GetRecordFlag(cmd *cobra.Command) bool {
return GetFlagBool(cmd, "record")
}
// RecordChangeCause annotate change-cause to input runtime object.
func RecordChangeCause(obj runtime.Object, changeCause string) error {
meta, err := api.ObjectMetaFor(obj)
if err != nil {
return err
}
if meta.Annotations == nil {
meta.Annotations = make(map[string]string)
}
meta.Annotations[kubectl.ChangeCauseAnnotation] = changeCause
return nil
}
// ChangeResourcePatch creates a strategic merge patch between the origin input resource info
// and the annotated with change-cause input resource info.
func ChangeResourcePatch(info *resource.Info, changeCause string) ([]byte, error) {
oldData, err := json.Marshal(info.Object)
if err != nil {
return nil, err
}
if err := RecordChangeCause(info.Object, changeCause); err != nil {
return nil, err
}
newData, err := json.Marshal(info.Object)
if err != nil {
return nil, err
}
return strategicpatch.CreateTwoWayMergePatch(oldData, newData, info.Object)
}
// containsChangeCause checks if input resource info contains change-cause annotation.
func ContainsChangeCause(info *resource.Info) bool {
annotations, err := info.Mapping.MetadataAccessor.Annotations(info.Object)
if err != nil {
return false
}
return len(annotations[kubectl.ChangeCauseAnnotation]) > 0
}
// ShouldRecord checks if we should record current change cause
func ShouldRecord(cmd *cobra.Command, info *resource.Info) bool {
return GetRecordFlag(cmd) || ContainsChangeCause(info)
}
| apache-2.0 |
gnodet/camel | core/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DigitalOceanEndpointBuilderFactory.java | 15024 | /*
* 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.builder.endpoint.dsl;
import javax.annotation.Generated;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;
/**
* Manage Droplets and resources within the DigitalOcean cloud.
*
* Generated by camel build tools - do NOT edit this file!
*/
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface DigitalOceanEndpointBuilderFactory {
/**
* Builder for endpoint for the DigitalOcean component.
*/
public interface DigitalOceanEndpointBuilder
extends
EndpointProducerBuilder {
default AdvancedDigitalOceanEndpointBuilder advanced() {
return (AdvancedDigitalOceanEndpointBuilder) this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default DigitalOceanEndpointBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default DigitalOceanEndpointBuilder lazyStartProducer(
String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Use for pagination. Force the page number.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Default: 1
* Group: producer
*
* @param page the value to set
* @return the dsl builder
*/
default DigitalOceanEndpointBuilder page(Integer page) {
doSetProperty("page", page);
return this;
}
/**
* Use for pagination. Force the page number.
*
* The option will be converted to a
* <code>java.lang.Integer</code> type.
*
* Default: 1
* Group: producer
*
* @param page the value to set
* @return the dsl builder
*/
default DigitalOceanEndpointBuilder page(String page) {
doSetProperty("page", page);
return this;
}
/**
* Use for pagination. Set the number of item per request. The maximum
* number of results per page is 200.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Default: 25
* Group: producer
*
* @param perPage the value to set
* @return the dsl builder
*/
default DigitalOceanEndpointBuilder perPage(Integer perPage) {
doSetProperty("perPage", perPage);
return this;
}
/**
* Use for pagination. Set the number of item per request. The maximum
* number of results per page is 200.
*
* The option will be converted to a
* <code>java.lang.Integer</code> type.
*
* Default: 25
* Group: producer
*
* @param perPage the value to set
* @return the dsl builder
*/
default DigitalOceanEndpointBuilder perPage(String perPage) {
doSetProperty("perPage", perPage);
return this;
}
/**
* The DigitalOcean resource type on which perform the operation.
*
* The option is a:
* <code>org.apache.camel.component.digitalocean.constants.DigitalOceanResources</code> type.
*
* Required: true
* Group: producer
*
* @param resource the value to set
* @return the dsl builder
*/
default DigitalOceanEndpointBuilder resource(
DigitalOceanResources resource) {
doSetProperty("resource", resource);
return this;
}
/**
* The DigitalOcean resource type on which perform the operation.
*
* The option will be converted to a
* <code>org.apache.camel.component.digitalocean.constants.DigitalOceanResources</code> type.
*
* Required: true
* Group: producer
*
* @param resource the value to set
* @return the dsl builder
*/
default DigitalOceanEndpointBuilder resource(String resource) {
doSetProperty("resource", resource);
return this;
}
/**
* Set a proxy host if needed.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: proxy
*
* @param httpProxyHost the value to set
* @return the dsl builder
*/
default DigitalOceanEndpointBuilder httpProxyHost(String httpProxyHost) {
doSetProperty("httpProxyHost", httpProxyHost);
return this;
}
/**
* Set a proxy password if needed.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: proxy
*
* @param httpProxyPassword the value to set
* @return the dsl builder
*/
default DigitalOceanEndpointBuilder httpProxyPassword(
String httpProxyPassword) {
doSetProperty("httpProxyPassword", httpProxyPassword);
return this;
}
/**
* Set a proxy port if needed.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Group: proxy
*
* @param httpProxyPort the value to set
* @return the dsl builder
*/
default DigitalOceanEndpointBuilder httpProxyPort(Integer httpProxyPort) {
doSetProperty("httpProxyPort", httpProxyPort);
return this;
}
/**
* Set a proxy port if needed.
*
* The option will be converted to a
* <code>java.lang.Integer</code> type.
*
* Group: proxy
*
* @param httpProxyPort the value to set
* @return the dsl builder
*/
default DigitalOceanEndpointBuilder httpProxyPort(String httpProxyPort) {
doSetProperty("httpProxyPort", httpProxyPort);
return this;
}
/**
* Set a proxy host if needed.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: proxy
*
* @param httpProxyUser the value to set
* @return the dsl builder
*/
default DigitalOceanEndpointBuilder httpProxyUser(String httpProxyUser) {
doSetProperty("httpProxyUser", httpProxyUser);
return this;
}
/**
* DigitalOcean OAuth Token.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param oAuthToken the value to set
* @return the dsl builder
*/
default DigitalOceanEndpointBuilder oAuthToken(String oAuthToken) {
doSetProperty("oAuthToken", oAuthToken);
return this;
}
}
/**
* Advanced builder for endpoint for the DigitalOcean component.
*/
public interface AdvancedDigitalOceanEndpointBuilder
extends
EndpointProducerBuilder {
default DigitalOceanEndpointBuilder basic() {
return (DigitalOceanEndpointBuilder) this;
}
/**
* To use a existing configured DigitalOceanClient as client.
*
* The option is a:
* <code>com.myjeeva.digitalocean.impl.DigitalOceanClient</code> type.
*
* Group: advanced
*
* @param digitalOceanClient the value to set
* @return the dsl builder
*/
default AdvancedDigitalOceanEndpointBuilder digitalOceanClient(
Object digitalOceanClient) {
doSetProperty("digitalOceanClient", digitalOceanClient);
return this;
}
/**
* To use a existing configured DigitalOceanClient as client.
*
* The option will be converted to a
* <code>com.myjeeva.digitalocean.impl.DigitalOceanClient</code> type.
*
* Group: advanced
*
* @param digitalOceanClient the value to set
* @return the dsl builder
*/
default AdvancedDigitalOceanEndpointBuilder digitalOceanClient(
String digitalOceanClient) {
doSetProperty("digitalOceanClient", digitalOceanClient);
return this;
}
}
/**
* Proxy enum for
* <code>org.apache.camel.component.digitalocean.constants.DigitalOceanResources</code> enum.
*/
enum DigitalOceanResources {
account,
actions,
blockStorages,
droplets,
images,
snapshots,
keys,
regions,
sizes,
floatingIPs,
tags;
}
public interface DigitalOceanBuilders {
/**
* DigitalOcean (camel-digitalocean)
* Manage Droplets and resources within the DigitalOcean cloud.
*
* Category: cloud,management
* Since: 2.19
* Maven coordinates: org.apache.camel:camel-digitalocean
*
* Syntax: <code>digitalocean:operation</code>
*
* Path parameter: operation
* The operation to perform to the given resource.
* There are 36 enums and the value can be one of: create, update,
* delete, list, ownList, get, listBackups, listActions, listNeighbors,
* listSnapshots, listKernels, listAllNeighbors, enableBackups,
* disableBackups, reboot, powerCycle, shutdown, powerOn, powerOff,
* restore, resetPassword, resize, rebuild, rename, changeKernel,
* enableIpv6, enablePrivateNetworking, takeSnapshot, transfer, convert,
* attach, detach, assign, unassign, tag, untag
*
* @param path operation
* @return the dsl builder
*/
default DigitalOceanEndpointBuilder digitalocean(String path) {
return DigitalOceanEndpointBuilderFactory.endpointBuilder("digitalocean", path);
}
/**
* DigitalOcean (camel-digitalocean)
* Manage Droplets and resources within the DigitalOcean cloud.
*
* Category: cloud,management
* Since: 2.19
* Maven coordinates: org.apache.camel:camel-digitalocean
*
* Syntax: <code>digitalocean:operation</code>
*
* Path parameter: operation
* The operation to perform to the given resource.
* There are 36 enums and the value can be one of: create, update,
* delete, list, ownList, get, listBackups, listActions, listNeighbors,
* listSnapshots, listKernels, listAllNeighbors, enableBackups,
* disableBackups, reboot, powerCycle, shutdown, powerOn, powerOff,
* restore, resetPassword, resize, rebuild, rename, changeKernel,
* enableIpv6, enablePrivateNetworking, takeSnapshot, transfer, convert,
* attach, detach, assign, unassign, tag, untag
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path operation
* @return the dsl builder
*/
default DigitalOceanEndpointBuilder digitalocean(
String componentName,
String path) {
return DigitalOceanEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
static DigitalOceanEndpointBuilder endpointBuilder(
String componentName,
String path) {
class DigitalOceanEndpointBuilderImpl extends AbstractEndpointBuilder implements DigitalOceanEndpointBuilder, AdvancedDigitalOceanEndpointBuilder {
public DigitalOceanEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new DigitalOceanEndpointBuilderImpl(path);
}
} | apache-2.0 |
louyihua/origin | vendor/k8s.io/kubernetes/staging/src/k8s.io/apiserver/pkg/server/drop_patch.go | 937 | /*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package server
import (
"k8s.io/apiserver/pkg/admission"
)
// SetAdmission gives access to the admission plugin. We need this in 3.6 to allow us to twiddle admission
// until we are aggregating
// TODO drop this after we aggregate ourselvse
func (s *GenericAPIServer) SetAdmission(admissionControl admission.Interface) {
s.admissionControl = admissionControl
}
| apache-2.0 |
OSUCartography/MapComposer | src/main/java/com/jhlabs/image/BumpFilter.java | 931 | /*
Copyright 2006 Jerry Huxtable
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.jhlabs.image;
import java.awt.image.*;
/**
* A simple embossing filter.
*/
public class BumpFilter extends ConvolveFilter {
private static float[] embossMatrix = {
-1.0f, -1.0f, 0.0f,
-1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f
};
public BumpFilter() {
super(embossMatrix);
}
public String toString() {
return "Blur/Emboss Edges";
}
}
| apache-2.0 |
nssales/OG-Platform | projects/OG-TimeSeries/src/main/java/com/opengamma/timeseries/date/DateDoubleTimeSeries.java | 8995 | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.timeseries.date;
import java.util.NoSuchElementException;
import com.opengamma.timeseries.DoubleTimeSeries;
import com.opengamma.timeseries.DoubleTimeSeriesOperators.BinaryOperator;
import com.opengamma.timeseries.DoubleTimeSeriesOperators.UnaryOperator;
/**
* A time series that stores {@code double} data values against dates.
* <p>
* The "time" key to the time-series is a date.
* See {@link DateTimeSeries} for details about the "time" represented as an {@code int}.
*
* @param <T> the date type
*/
public interface DateDoubleTimeSeries<T>
extends DoubleTimeSeries<T>, DateTimeSeries<T, Double> {
/**
* Gets the value at the specified index.
*
* @param index the index to retrieve
* @return the value at the index
* @throws IndexOutOfBoundsException if the index is invalid
*/
double getValueAtIndexFast(int index);
//-------------------------------------------------------------------------
/**
* Gets the value at the earliest date in the series.
*
* @return the value at the earliest date
* @throws NoSuchElementException if empty
*/
double getEarliestValueFast();
/**
* Gets the value at the latest date in the series.
*
* @return the value at the latest date
* @throws NoSuchElementException if empty
*/
double getLatestValueFast();
//-------------------------------------------------------------------------
/**
* Gets an iterator over the date-value pairs.
* <p>
* Although the pairs are expressed as instances of {@code Map.Entry},
* it is recommended to use the primitive methods on {@code DateDoubleEntryIterator}.
*
* @return the iterator, not null
*/
DateDoubleEntryIterator<T> iterator();
//-------------------------------------------------------------------------
@Override // override for covariant return type
DateDoubleTimeSeries<T> subSeries(T startTime, T endTime);
@Override // override for covariant return type
DateDoubleTimeSeries<T> subSeries(T startTime, boolean includeStart, T endTime, boolean includeEnd);
DateDoubleTimeSeries<T> subSeriesFast(int startTime, int endTime);
DateDoubleTimeSeries<T> subSeriesFast(int startTime, boolean includeStart, int endTime, boolean includeEnd);
//-------------------------------------------------------------------------
@Override // override for covariant return type
DateDoubleTimeSeries<T> head(int numItems);
@Override // override for covariant return type
DateDoubleTimeSeries<T> tail(int numItems);
@Override // override for covariant return type
DateDoubleTimeSeries<T> lag(int lagCount);
//-------------------------------------------------------------------------
/**
* Applies a unary operator to each value in the time series.
*
* @param operator the operator, not null
* @return a copy of this series with the operator applied, not null
*/
DateDoubleTimeSeries<T> operate(UnaryOperator operator);
/**
* Applies a binary operator to each value in the time series.
*
* @param other the single value passed into the binary operator
* @param operator the operator, not null
* @return a copy of this series with the operator applied, not null
*/
DateDoubleTimeSeries<T> operate(double other, BinaryOperator operator);
/**
* Applies a binary operator to each value in this time series and
* another time-series, returning the intersection of times.
*
* @param otherTimeSeries the other time-series, not null
* @param operator the operator, not null
* @return a copy of this series with the operator applied, not null
*/
DateDoubleTimeSeries<T> operate(DateDoubleTimeSeries<?> otherTimeSeries, BinaryOperator operator);
/**
* Applies a binary operator to each value in this time series and
* another time-series, returning the union of times.
*
* @param otherTimeSeries the other time-series, not null
* @param operator the operator, not null
* @return a copy of this series with the operator applied, not null
*/
DateDoubleTimeSeries<T> unionOperate(DateDoubleTimeSeries<?> otherTimeSeries, BinaryOperator operator);
//-------------------------------------------------------------------------
@Override // override for covariant return type
DateDoubleTimeSeries<T> add(double amountToAdd);
@Override // override for covariant return type
DateDoubleTimeSeries<T> add(DoubleTimeSeries<?> other);
@Override // override for covariant return type
DateDoubleTimeSeries<T> unionAdd(DoubleTimeSeries<?> other);
//-------------------------------------------------------------------------
@Override // override for covariant return type
DateDoubleTimeSeries<T> subtract(double amountToSubtract);
@Override // override for covariant return type
DateDoubleTimeSeries<T> subtract(DoubleTimeSeries<?> other);
@Override // override for covariant return type
DateDoubleTimeSeries<T> unionSubtract(DoubleTimeSeries<?> other);
//-------------------------------------------------------------------------
@Override // override for covariant return type
DateDoubleTimeSeries<T> multiply(double amountToMultiplyBy);
@Override // override for covariant return type
DateDoubleTimeSeries<T> multiply(DoubleTimeSeries<?> other);
@Override // override for covariant return type
DateDoubleTimeSeries<T> unionMultiply(DoubleTimeSeries<?> other);
//-------------------------------------------------------------------------
@Override // override for covariant return type
DateDoubleTimeSeries<T> divide(double amountToDivideBy);
@Override // override for covariant return type
DateDoubleTimeSeries<T> divide(DoubleTimeSeries<?> other);
@Override // override for covariant return type
DateDoubleTimeSeries<T> unionDivide(DoubleTimeSeries<?> other);
//-------------------------------------------------------------------------
@Override // override for covariant return type
DateDoubleTimeSeries<T> power(double power);
@Override // override for covariant return type
DateDoubleTimeSeries<T> power(DoubleTimeSeries<?> other);
@Override // override for covariant return type
DateDoubleTimeSeries<T> unionPower(DoubleTimeSeries<?> other);
//-------------------------------------------------------------------------
@Override // override for covariant return type
DateDoubleTimeSeries<T> minimum(double minValue);
@Override // override for covariant return type
DateDoubleTimeSeries<T> minimum(DoubleTimeSeries<?> other);
@Override // override for covariant return type
DateDoubleTimeSeries<T> unionMinimum(DoubleTimeSeries<?> other);
//-------------------------------------------------------------------------
@Override // override for covariant return type
DateDoubleTimeSeries<T> maximum(double maxValue);
@Override // override for covariant return type
DateDoubleTimeSeries<T> maximum(DoubleTimeSeries<?> other);
@Override // override for covariant return type
DateDoubleTimeSeries<T> unionMaximum(DoubleTimeSeries<?> other);
//-------------------------------------------------------------------------
@Override // override for covariant return type
DateDoubleTimeSeries<T> average(double value);
@Override // override for covariant return type
DateDoubleTimeSeries<T> average(DoubleTimeSeries<?> other);
@Override // override for covariant return type
DateDoubleTimeSeries<T> unionAverage(DoubleTimeSeries<?> other);
//-------------------------------------------------------------------------
@Override // override for covariant return type
DateDoubleTimeSeries<T> intersectionFirstValue(DoubleTimeSeries<?> other);
@Override // override for covariant return type
DateDoubleTimeSeries<T> intersectionSecondValue(DoubleTimeSeries<?> other);
@Override // override for covariant return type
DateDoubleTimeSeries<T> noIntersectionOperation(DoubleTimeSeries<?> other);
//-------------------------------------------------------------------------
@Override // override for covariant return type
DateDoubleTimeSeries<T> negate();
@Override // override for covariant return type
DateDoubleTimeSeries<T> reciprocal();
@Override // override for covariant return type
DateDoubleTimeSeries<T> log();
@Override // override for covariant return type
DateDoubleTimeSeries<T> log10();
@Override // override for covariant return type
DateDoubleTimeSeries<T> abs();
//-------------------------------------------------------------------------
/**
* Returns a builder containing the same data as this time-series.
* <p>
* The builder has methods to modify the time-series.
* Entries can be added, or removed via the iterator.
*
* @return the builder, not null
*/
DateDoubleTimeSeriesBuilder<T> toBuilder();
}
| apache-2.0 |
KaranToor/MA450 | google-cloud-sdk/.install/.backup/lib/surface/debug/snapshots/create.py | 4234 | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Create command for gcloud debug snapshots command group."""
from googlecloudsdk.api_lib.debug import debug
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
class Create(base.CreateCommand):
"""Create debug snapshots."""
detailed_help = {
'DESCRIPTION': """\
This command creates a debug snapshot on a Cloud Debugger debug
target. Snapshots allow you to capture stack traces and local
variables from your running service without interfering with normal
operations.
When any instance of the target executes the snapshot location, the
optional condition expression is evaluated. If the result is true
(or if there is no condition), the instance captures the current
thread state and reports it back to Cloud Debugger. Once any instance
captures a snapshot, the snapshot is marked as completed, and it
will not be captured again.
You can most easily view snapshot results in the developer console. It
is also possible to inspect snapshot results with the "snapshots
describe" command.
"""
}
@staticmethod
def Args(parser):
parser.add_argument(
'location',
help="""\
The location where the snapshot should be taken. Locations are of
the form FILE:LINE, where FILE can be simply the file name, or the
file name preceded by enough path components to differntiate it from
other files with the same name. If the file name is not unique in
the debug target, the behavior is unspecified.
""")
parser.add_argument(
'--condition',
help="""\
A condition to restrict when the snapshot is taken. When the
snapshot location is executed, the condition will be evaluated, and
the snapshot will be generated only if the condition is true.
""")
parser.add_argument(
'--expression', action='append',
help="""\
An expression to evaluate when the snapshot is taken. You may
specify --expression multiple times.
""")
parser.add_argument(
'--wait', default=10,
help="""\
The number of seconds to wait to ensure that no error is returned
from a debugger agent when creating the snapshot. When a snapshot
is created, there will be a delay before the agents see and apply
the snapshot. Until at least one agent has attempted to
enable the snapshot, it cannot be determined if the snapshot is
valid.
""")
def Run(self, args):
"""Run the create command."""
project_id = properties.VALUES.core.project.Get(required=True)
user_email = properties.VALUES.core.account.Get(required=True)
debugger = debug.Debugger(project_id)
debuggee = debugger.FindDebuggee(args.target)
snapshot = debuggee.CreateSnapshot(
location=args.location, expressions=args.expression,
condition=args.condition, user_email=user_email)
final_snapshot = debuggee.WaitForBreakpointSet(snapshot.id, args.wait,
args.location)
if args.location != final_snapshot.location:
log.status.write(
'The debugger adjusted the snapshot location to {0}'.format(
final_snapshot.location))
return final_snapshot or snapshot
def Collection(self):
return 'debug.snapshots.create'
def Format(self, args):
return self.ListFormat(args)
| apache-2.0 |
msebire/intellij-community | plugins/tasks/tasks-tests/test/com/intellij/tasks/live/TrelloIntegrationTest.java | 10724 | package com.intellij.tasks.live;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.tasks.CustomTaskState;
import com.intellij.tasks.trello.TrelloRepository;
import com.intellij.tasks.trello.TrelloRepositoryType;
import com.intellij.tasks.trello.TrelloTask;
import com.intellij.tasks.trello.model.*;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xmlb.XmlSerializer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import static com.intellij.tasks.trello.model.TrelloLabel.LabelColor.*;
/**
* @author Mikhail Golubev
*/
public class TrelloIntegrationTest extends LiveIntegrationTestCase<TrelloRepository> {
// Basic functionality (searching, filtering, etc.)
private static final String BASIC_FUNCTIONALITY_BOARD_NAME = "Basic Functionality";
private static final String BASIC_FUNCTIONALITY_BOARD_ID = "53c416a8a6e5a78753562043";
private static final String LIST_1_1_NAME = "List 1-1";
private static final String LIST_1_1_ID = "53c416a8a6e5a78753562044";
private static final String CARD_1_1_1_NAME = "Card 1-1-1";
private static final String CARD_1_1_1_ID = "53c416d8b4bd36fb078446e5";
private static final String CARD_1_1_1_NUMBER = "1";
// Labels and colors
private static final String LABELS_AND_COLORS_BOARD_NAME = "Labels and Colors";
private static final String COLORED_CARD_ID = "548591e00f3d598512ced37b";
private static final String CARD_WITH_COLORLESS_LABELS_ID = "5714ccd9f6ab69c4de522346";
// State updates
private static final String STATE_UPDATES_BOARD_NAME = "State Updates";
private static final String STATE_UPDATES_BOARD_ID = "54b3e0e3b4f415b3c9d03449";
private static final String BACKLOG_LIST_ID = "54b3e0e849e831746351e063";
private static final String IN_PROGRESS_LIST_ID = "54b3e0ebf5035aaddcbe15b4";
private static final String FEATURE_CARD_ID = "54b3e0efed4db033b634cd39";
@Override
protected TrelloRepository createRepository() throws Exception {
try {
TrelloRepository repository = new TrelloRepository(new TrelloRepositoryType());
String token = System.getProperty("tasks.tests.trello.token");
assertTrue("Authorization token is not set", !StringUtil.isEmpty(token));
repository.setPassword(token);
TrelloUser user = repository.fetchUserByToken();
assertNotNull(user);
repository.setCurrentUser(user);
return repository;
}
catch (AssertionError ae){
tearDown();
throw ae;
}
}
// TODO Check closed tasks exclusion
// TODO Check various cards visibility corner cases
public void testFetchBoard() throws Exception {
TrelloBoard board = myRepository.fetchBoardById(BASIC_FUNCTIONALITY_BOARD_ID);
assertNotNull(board);
assertEquals(BASIC_FUNCTIONALITY_BOARD_NAME, board.getName());
}
public void testFetchList() throws Exception {
TrelloList list = myRepository.fetchListById(LIST_1_1_ID);
assertNotNull(list);
assertEquals(LIST_1_1_NAME, list.getName());
}
public void testFetchCard() throws Exception {
TrelloCard card = myRepository.fetchCardById(CARD_1_1_1_ID);
assertNotNull(card);
assertEquals(CARD_1_1_1_NAME, card.getName());
}
public void testFetchBoardsOfUser() throws Exception {
List<TrelloBoard> boards = myRepository.fetchUserBoards();
assertEquals(3, boards.size());
assertObjectsNamed("All boards of the user should be included", boards,
BASIC_FUNCTIONALITY_BOARD_NAME, LABELS_AND_COLORS_BOARD_NAME, STATE_UPDATES_BOARD_NAME);
}
public void testFetchListsOfBoard() throws Exception {
TrelloBoard selectedBoard = myRepository.fetchBoardById(BASIC_FUNCTIONALITY_BOARD_ID);
assertNotNull(selectedBoard);
myRepository.setCurrentBoard(selectedBoard);
List<TrelloList> lists = myRepository.fetchBoardLists();
assertEquals(3, lists.size());
assertObjectsNamed("All lists of the board should be included", lists, "List 1-1", "List 1-2", "List 1-3");
}
@NotNull
private List<TrelloCard> fetchCards(@Nullable String boardId, @Nullable String listId, boolean withClosed) throws Exception {
if (boardId != null) {
TrelloBoard selectedBoard = myRepository.fetchBoardById(BASIC_FUNCTIONALITY_BOARD_ID);
assertNotNull(selectedBoard);
myRepository.setCurrentBoard(selectedBoard);
}
if (listId != null) {
TrelloList selectedList = myRepository.fetchListById(LIST_1_1_ID);
assertNotNull(selectedList);
myRepository.setCurrentList(selectedList);
}
return myRepository.fetchCards(100, withClosed);
}
public void testFetchingCardsOfUser() throws Exception {
myRepository.setIncludeAllCards(true);
List<TrelloCard> cards = fetchCards(null, null, true);
assertObjectsNamed("All cards assigned to user should be included", cards, "Card 1-1-1");
}
public void testFetchingCardsOfBoard() throws Exception {
myRepository.setIncludeAllCards(true);
List<TrelloCard> cards = fetchCards(BASIC_FUNCTIONALITY_BOARD_ID, null, true);
assertObjectsNamed("All cards of the board should be included",
cards, "Card 1-1-1", "Card 1-1-2", "Card 1-2-1", "Card 1-3-1", "Archived Card");
}
public void testCardsFilteringByMembership() throws Exception {
myRepository.setIncludeAllCards(true);
List<TrelloCard> allCards = fetchCards(BASIC_FUNCTIONALITY_BOARD_ID, LIST_1_1_ID, true);
assertObjectsNamed("All cards of the list should be included", allCards, "Card 1-1-1", "Card 1-1-2", "Archived Card");
myRepository.setIncludeAllCards(false);
List<TrelloCard> assignedCards = fetchCards(BASIC_FUNCTIONALITY_BOARD_ID, LIST_1_1_ID, true);
assertObjectsNamed("Only cards of the list assigned to user should be included", assignedCards, "Card 1-1-1");
}
public void testCardsFilteringByStatus() throws Exception {
myRepository.setIncludeAllCards(true);
List<TrelloCard> allCards = fetchCards(BASIC_FUNCTIONALITY_BOARD_ID, LIST_1_1_NAME, true);
assertObjectsNamed("All cards of the list should be included", allCards, "Card 1-1-1", "Card 1-1-2", "Archived Card");
TrelloCard card = ContainerUtil.find(allCards, card1 -> card1.getName().equals("Archived Card"));
assertNotNull(card);
assertTrue(card.isClosed());
assertFalse(card.isVisible());
}
public void testTestConnection() {
assertNull(myRepository.createCancellableConnection().call());
myRepository.setPassword("illegal password");
final Exception error = myRepository.createCancellableConnection().call();
assertNotNull(error);
assertTrue(error.getMessage().contains("Unauthorized"));
}
public void testLabelsAndColors() throws Exception {
final TrelloCard card = myRepository.fetchCardById(COLORED_CARD_ID);
assertNotNull(card);
final List<TrelloLabel> labels = card.getLabels();
assertEquals(6, labels.size());
final Set<String> labelNames = ContainerUtil.map2Set(labels, TrelloLabel::getName);
assertSameElements(labelNames, "Sky colored label", "Boring label", "Dull label", "");
assertEquals(EnumSet.of(SKY, LIME, PINK, BLACK), card.getColors());
}
// EA-81551
public void testAllLabelsWithoutColor() throws Exception {
final TrelloCard card = myRepository.fetchCardById(CARD_WITH_COLORLESS_LABELS_ID);
assertNotNull(card);
final List<TrelloLabel> labels = card.getLabels();
assertSize(2, labels);
final List<String> labelNames = ContainerUtil.map(labels, TrelloLabel::getName);
assertSameElements(labelNames, "Boring label", "Dull label");
assertEmpty(card.getColors());
}
public void testStateUpdates() throws Exception {
TrelloCard card = myRepository.fetchCardById(FEATURE_CARD_ID);
assertNotNull(card);
assertEquals(STATE_UPDATES_BOARD_ID, card.getIdBoard());
assertEquals(BACKLOG_LIST_ID, card.getIdList());
// Discover "In Progress" list
TrelloTask task = new TrelloTask(card, myRepository);
Set<CustomTaskState> states = myRepository.getAvailableTaskStates(task);
assertEquals(1, states.size());
final CustomTaskState inProgressState = states.iterator().next();
assertEquals(IN_PROGRESS_LIST_ID, inProgressState.getId());
assertEquals("In Progress", inProgressState.getPresentableName());
// Backlog -> In Progress
myRepository.setTaskState(task, inProgressState);
card = myRepository.fetchCardById(FEATURE_CARD_ID);
assertNotNull(card);
assertEquals(STATE_UPDATES_BOARD_ID, card.getIdBoard());
assertEquals(IN_PROGRESS_LIST_ID, card.getIdList());
// Discover "Backlog" list
task = new TrelloTask(card, myRepository);
states = myRepository.getAvailableTaskStates(task);
assertEquals(1, states.size());
final CustomTaskState backlogState = states.iterator().next();
assertEquals(BACKLOG_LIST_ID, backlogState.getId());
assertEquals("Backlog", backlogState.getPresentableName());
// In Progress -> Backlog
myRepository.setTaskState(task, backlogState);
card = myRepository.fetchCardById(FEATURE_CARD_ID);
assertNotNull(card);
assertEquals(STATE_UPDATES_BOARD_ID, card.getIdBoard());
assertEquals(BACKLOG_LIST_ID, card.getIdList());
}
// IDEA-139903
public void testCardBoardLocalNumber() throws Exception {
final TrelloCard card = myRepository.fetchCardById(CARD_1_1_1_ID);
assertNotNull(card);
assertEquals(CARD_1_1_1_ID, card.getId());
assertEquals(CARD_1_1_1_NUMBER, new TrelloTask(card, myRepository).getNumber());
}
private static void assertObjectsNamed(@NotNull String message,
@NotNull Collection<? extends TrelloModel> objects,
@NotNull String... names) {
assertEquals(message, ContainerUtil.newHashSet(names), ContainerUtil.map2Set(objects,
(Function<TrelloModel, String>)model -> model.getName()));
}
// IDEA-187507
public void testSerialization() {
final TrelloRepository repository = new TrelloRepository(new TrelloRepositoryType());
final TrelloBoard board = new TrelloBoard();
// Otherwise it will be replaced by TrelloRepository.UNSPECIFIED_BOARD excluded from serialization
board.setId("realID");
repository.setCurrentBoard(board);
final TrelloList list = new TrelloList();
list.setId("realID");
repository.setCurrentList(list);
repository.setCurrentUser(new TrelloUser());
XmlSerializer.serialize(repository);
}
}
| apache-2.0 |
dgageot/getme | vendor/github.com/minio/minio-go/api-put-object-readat.go | 8216 | /*
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015, 2016 Minio, 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 minio
import (
"bytes"
"crypto/md5"
"crypto/sha256"
"fmt"
"hash"
"io"
"io/ioutil"
"sort"
)
// uploadedPartRes - the response received from a part upload.
type uploadedPartRes struct {
Error error // Any error encountered while uploading the part.
PartNum int // Number of the part uploaded.
Size int64 // Size of the part uploaded.
Part *ObjectPart
}
type uploadPartReq struct {
PartNum int // Number of the part uploaded.
Part *ObjectPart // Size of the part uploaded.
}
// shouldUploadPartReadAt - verify if part should be uploaded.
func shouldUploadPartReadAt(objPart ObjectPart, uploadReq uploadPartReq) bool {
// If part not found part should be uploaded.
if uploadReq.Part == nil {
return true
}
// if size mismatches part should be uploaded.
if uploadReq.Part.Size != objPart.Size {
return true
}
return false
}
// putObjectMultipartFromReadAt - Uploads files bigger than 5MiB. Supports reader
// of type which implements io.ReaderAt interface (ReadAt method).
//
// NOTE: This function is meant to be used for all readers which
// implement io.ReaderAt which allows us for resuming multipart
// uploads but reading at an offset, which would avoid re-read the
// data which was already uploaded. Internally this function uses
// temporary files for staging all the data, these temporary files are
// cleaned automatically when the caller i.e http client closes the
// stream after uploading all the contents successfully.
func (c Client) putObjectMultipartFromReadAt(bucketName, objectName string, reader io.ReaderAt, size int64, metaData map[string][]string, progress io.Reader) (n int64, err error) {
// Input validation.
if err := isValidBucketName(bucketName); err != nil {
return 0, err
}
if err := isValidObjectName(objectName); err != nil {
return 0, err
}
// Get the upload id of a previously partially uploaded object or initiate a new multipart upload
uploadID, partsInfo, err := c.getMpartUploadSession(bucketName, objectName, metaData)
if err != nil {
return 0, err
}
// Total data read and written to server. should be equal to 'size' at the end of the call.
var totalUploadedSize int64
// Complete multipart upload.
var complMultipartUpload completeMultipartUpload
// Calculate the optimal parts info for a given size.
totalPartsCount, partSize, lastPartSize, err := optimalPartInfo(size)
if err != nil {
return 0, err
}
// Used for readability, lastPartNumber is always totalPartsCount.
lastPartNumber := totalPartsCount
// Declare a channel that sends the next part number to be uploaded.
// Buffered to 10000 because thats the maximum number of parts allowed
// by S3.
uploadPartsCh := make(chan uploadPartReq, 10000)
// Declare a channel that sends back the response of a part upload.
// Buffered to 10000 because thats the maximum number of parts allowed
// by S3.
uploadedPartsCh := make(chan uploadedPartRes, 10000)
// Send each part number to the channel to be processed.
for p := 1; p <= totalPartsCount; p++ {
part, ok := partsInfo[p]
if ok {
uploadPartsCh <- uploadPartReq{PartNum: p, Part: &part}
} else {
uploadPartsCh <- uploadPartReq{PartNum: p, Part: nil}
}
}
close(uploadPartsCh)
// Receive each part number from the channel allowing three parallel uploads.
for w := 1; w <= totalWorkers; w++ {
go func() {
// Read defaults to reading at 5MiB buffer.
readAtBuffer := make([]byte, optimalReadBufferSize)
// Each worker will draw from the part channel and upload in parallel.
for uploadReq := range uploadPartsCh {
// Declare a new tmpBuffer.
tmpBuffer := new(bytes.Buffer)
// If partNumber was not uploaded we calculate the missing
// part offset and size. For all other part numbers we
// calculate offset based on multiples of partSize.
readOffset := int64(uploadReq.PartNum-1) * partSize
missingPartSize := partSize
// As a special case if partNumber is lastPartNumber, we
// calculate the offset based on the last part size.
if uploadReq.PartNum == lastPartNumber {
readOffset = (size - lastPartSize)
missingPartSize = lastPartSize
}
// Get a section reader on a particular offset.
sectionReader := io.NewSectionReader(reader, readOffset, missingPartSize)
// Choose the needed hash algorithms to be calculated by hashCopyBuffer.
// Sha256 is avoided in non-v4 signature requests or HTTPS connections
hashSums := make(map[string][]byte)
hashAlgos := make(map[string]hash.Hash)
hashAlgos["md5"] = md5.New()
if c.signature.isV4() && !c.secure {
hashAlgos["sha256"] = sha256.New()
}
var prtSize int64
var err error
prtSize, err = hashCopyBuffer(hashAlgos, hashSums, tmpBuffer, sectionReader, readAtBuffer)
if err != nil {
// Send the error back through the channel.
uploadedPartsCh <- uploadedPartRes{
Size: 0,
Error: err,
}
// Exit the goroutine.
return
}
// Verify object if its uploaded.
verifyObjPart := ObjectPart{
PartNumber: uploadReq.PartNum,
Size: partSize,
}
// Special case if we see a last part number, save last part
// size as the proper part size.
if uploadReq.PartNum == lastPartNumber {
verifyObjPart.Size = lastPartSize
}
// Only upload the necessary parts. Otherwise return size through channel
// to update any progress bar.
if shouldUploadPartReadAt(verifyObjPart, uploadReq) {
// Proceed to upload the part.
var objPart ObjectPart
objPart, err = c.uploadPart(bucketName, objectName, uploadID, tmpBuffer, uploadReq.PartNum, hashSums["md5"], hashSums["sha256"], prtSize)
if err != nil {
uploadedPartsCh <- uploadedPartRes{
Size: 0,
Error: err,
}
// Exit the goroutine.
return
}
// Save successfully uploaded part metadata.
uploadReq.Part = &objPart
}
// Send successful part info through the channel.
uploadedPartsCh <- uploadedPartRes{
Size: verifyObjPart.Size,
PartNum: uploadReq.PartNum,
Part: uploadReq.Part,
Error: nil,
}
}
}()
}
// Gather the responses as they occur and update any
// progress bar.
for u := 1; u <= totalPartsCount; u++ {
uploadRes := <-uploadedPartsCh
if uploadRes.Error != nil {
return totalUploadedSize, uploadRes.Error
}
// Retrieve each uploaded part and store it to be completed.
// part, ok := partsInfo[uploadRes.PartNum]
part := uploadRes.Part
if part == nil {
return 0, ErrInvalidArgument(fmt.Sprintf("Missing part number %d", uploadRes.PartNum))
}
// Update the totalUploadedSize.
totalUploadedSize += uploadRes.Size
// Update the progress bar if there is one.
if progress != nil {
if _, err = io.CopyN(ioutil.Discard, progress, uploadRes.Size); err != nil {
return totalUploadedSize, err
}
}
// Store the parts to be completed in order.
complMultipartUpload.Parts = append(complMultipartUpload.Parts, CompletePart{
ETag: part.ETag,
PartNumber: part.PartNumber,
})
}
// Verify if we uploaded all the data.
if totalUploadedSize != size {
return totalUploadedSize, ErrUnexpectedEOF(totalUploadedSize, size, bucketName, objectName)
}
// Sort all completed parts.
sort.Sort(completedParts(complMultipartUpload.Parts))
_, err = c.completeMultipartUpload(bucketName, objectName, uploadID, complMultipartUpload)
if err != nil {
return totalUploadedSize, err
}
// Return final size.
return totalUploadedSize, nil
}
| apache-2.0 |
pawanpal01/biodata | biodata-formats/src/main/java/org/opencb/biodata/formats/variant/clinvar/v19jaxb/CoOccurrenceType.java | 4155 | /*
* Copyright 2015 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.09.26 at 06:05:35 PM CEST
//
package org.opencb.biodata.formats.variant.clinvar.v19jaxb;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Co-occurrenceType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Co-occurrenceType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Zygosity" type="{}ZygosityType" minOccurs="0"/>
* <element name="AlleleDescSet" type="{}AlleleDescType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="Count" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Co-occurrenceType", propOrder = {
"zygosity",
"alleleDescSet",
"count"
})
public class CoOccurrenceType {
@XmlElement(name = "Zygosity")
protected ZygosityType zygosity;
@XmlElement(name = "AlleleDescSet")
protected List<AlleleDescType> alleleDescSet;
@XmlElement(name = "Count")
protected Integer count;
/**
* Gets the value of the zygosity property.
*
* @return
* possible object is
* {@link ZygosityType }
*
*/
public ZygosityType getZygosity() {
return zygosity;
}
/**
* Sets the value of the zygosity property.
*
* @param value
* allowed object is
* {@link ZygosityType }
*
*/
public void setZygosity(ZygosityType value) {
this.zygosity = value;
}
/**
* Gets the value of the alleleDescSet property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the alleleDescSet property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAlleleDescSet().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AlleleDescType }
*
*
*/
public List<AlleleDescType> getAlleleDescSet() {
if (alleleDescSet == null) {
alleleDescSet = new ArrayList<AlleleDescType>();
}
return this.alleleDescSet;
}
/**
* Gets the value of the count property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getCount() {
return count;
}
/**
* Sets the value of the count property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setCount(Integer value) {
this.count = value;
}
}
| apache-2.0 |
asashour/selenium | rb/lib/selenium/webdriver/remote/w3c/commands.rb | 6459 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC 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.
module Selenium
module WebDriver
module Remote
module W3C
#
# http://www.w3.org/TR/2015/WD-webdriver-20150918/#list-of-endpoints
# @api private
#
class Bridge
COMMANDS = {
#
# session handling
#
new_session: [:post, 'session'.freeze],
delete_session: [:delete, 'session/:session_id'.freeze],
#
# basic driver
#
get: [:post, 'session/:session_id/url'.freeze],
get_current_url: [:get, 'session/:session_id/url'.freeze],
back: [:post, 'session/:session_id/back'.freeze],
forward: [:post, 'session/:session_id/forward'.freeze],
refresh: [:post, 'session/:session_id/refresh'.freeze],
get_title: [:get, 'session/:session_id/title'.freeze],
#
# window and Frame handling
#
get_window_handle: [:get, 'session/:session_id/window'.freeze],
close_window: [:delete, 'session/:session_id/window'.freeze],
switch_to_window: [:post, 'session/:session_id/window'.freeze],
get_window_handles: [:get, 'session/:session_id/window/handles'.freeze],
fullscreen_window: [:post, 'session/:session_id/window/fullscreen'.freeze],
minimize_window: [:post, 'session/:session_id/window/minimize'.freeze],
maximize_window: [:post, 'session/:session_id/window/maximize'.freeze],
set_window_size: [:post, 'session/:session_id/window/size'.freeze],
get_window_size: [:get, 'session/:session_id/window/size'.freeze],
set_window_position: [:post, 'session/:session_id/window/position'.freeze],
get_window_position: [:get, 'session/:session_id/window/position'.freeze],
set_window_rect: [:post, 'session/:session_id/window/rect'.freeze],
get_window_rect: [:get, 'session/:session_id/window/rect'.freeze],
switch_to_frame: [:post, 'session/:session_id/frame'.freeze],
switch_to_parent_frame: [:post, 'session/:session_id/frame/parent'.freeze],
#
# element
#
find_element: [:post, 'session/:session_id/element'.freeze],
find_elements: [:post, 'session/:session_id/elements'.freeze],
find_child_element: [:post, 'session/:session_id/element/:id/element'.freeze],
find_child_elements: [:post, 'session/:session_id/element/:id/elements'.freeze],
get_active_element: [:get, 'session/:session_id/element/active'.freeze],
is_element_selected: [:get, 'session/:session_id/element/:id/selected'.freeze],
get_element_attribute: [:get, 'session/:session_id/element/:id/attribute/:name'.freeze],
get_element_property: [:get, 'session/:session_id/element/:id/property/:name'.freeze],
get_element_css_value: [:get, 'session/:session_id/element/:id/css/:property_name'.freeze],
get_element_text: [:get, 'session/:session_id/element/:id/text'.freeze],
get_element_tag_name: [:get, 'session/:session_id/element/:id/name'.freeze],
get_element_rect: [:get, 'session/:session_id/element/:id/rect'.freeze],
is_element_enabled: [:get, 'session/:session_id/element/:id/enabled'.freeze],
#
# document handling
#
get_page_source: [:get, 'session/:session_id/source'.freeze],
execute_script: [:post, 'session/:session_id/execute/sync'.freeze],
execute_async_script: [:post, 'session/:session_id/execute/async'.freeze],
#
# cookies
#
get_all_cookies: [:get, 'session/:session_id/cookie'.freeze],
get_cookie: [:get, 'session/:session_id/cookie/:name'.freeze],
add_cookie: [:post, 'session/:session_id/cookie'.freeze],
delete_cookie: [:delete, 'session/:session_id/cookie/:name'.freeze],
delete_all_cookies: [:delete, 'session/:session_id/cookie'.freeze],
#
# timeouts
#
set_timeout: [:post, 'session/:session_id/timeouts'.freeze],
#
# actions
#
actions: [:post, 'session/:session_id/actions'.freeze],
release_actions: [:delete, 'session/:session_id/actions'.freeze],
#
# Element Operations
#
element_click: [:post, 'session/:session_id/element/:id/click'.freeze],
element_tap: [:post, 'session/:session_id/element/:id/tap'.freeze],
element_clear: [:post, 'session/:session_id/element/:id/clear'.freeze],
element_send_keys: [:post, 'session/:session_id/element/:id/value'.freeze],
#
# alerts
#
dismiss_alert: [:post, 'session/:session_id/alert/dismiss'.freeze],
accept_alert: [:post, 'session/:session_id/alert/accept'.freeze],
get_alert_text: [:get, 'session/:session_id/alert/text'.freeze],
send_alert_text: [:post, 'session/:session_id/alert/text'.freeze],
#
# screenshot
#
take_screenshot: [:get, 'session/:session_id/screenshot'.freeze],
take_element_screenshot: [:get, 'session/:session_id/element/:id/screenshot'.freeze],
#
# server extensions
#
upload_file: [:post, 'session/:session_id/se/file'.freeze]
}.freeze
end # Bridge
end # W3C
end # Remote
end # WebDriver
end # Selenium
| apache-2.0 |
gotroy/elasticsearch | src/test/java/org/elasticsearch/cluster/routing/allocation/TenShardsOneReplicaRoutingTests.java | 10834 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.cluster.routing.allocation;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.test.ElasticsearchAllocationTestCase;
import org.junit.Test;
import static org.elasticsearch.cluster.routing.ShardRoutingState.*;
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
import static org.hamcrest.Matchers.*;
/**
*
*/
public class TenShardsOneReplicaRoutingTests extends ElasticsearchAllocationTestCase {
private final ESLogger logger = Loggers.getLogger(TenShardsOneReplicaRoutingTests.class);
@Test
public void testSingleIndexFirstStartPrimaryThenBackups() {
AllocationService strategy = createAllocationService(settingsBuilder()
.put("cluster.routing.allocation.node_concurrent_recoveries", 10)
.put("cluster.routing.allocation.node_initial_primaries_recoveries", 10)
.put("cluster.routing.allocation.allow_rebalance", "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1)
.put("cluster.routing.allocation.balance.index", 0.0f)
.put("cluster.routing.allocation.balance.replica", 1.0f)
.put("cluster.routing.allocation.balance.primary", 0.0f)
.build());
logger.info("Building initial routing table");
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder("test").numberOfShards(10).numberOfReplicas(1))
.build();
RoutingTable routingTable = RoutingTable.builder()
.addAsNew(metaData.index("test"))
.build();
ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build();
assertThat(routingTable.index("test").shards().size(), equalTo(10));
for (int i = 0; i < routingTable.index("test").shards().size(); i++) {
assertThat(routingTable.index("test").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().get(0).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test").shard(i).shards().get(1).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test").shard(i).shards().get(0).currentNodeId(), nullValue());
assertThat(routingTable.index("test").shard(i).shards().get(1).currentNodeId(), nullValue());
}
logger.info("Adding one node and performing rerouting");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1"))).build();
RoutingTable prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(10));
for (int i = 0; i < routingTable.index("test").shards().size(); i++) {
assertThat(routingTable.index("test").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test").shard(i).primaryShard().currentNodeId(), equalTo("node1"));
assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1));
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).currentNodeId(), nullValue());
}
logger.info("Add another node and perform rerouting, nothing will happen since primary not started");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node2"))).build();
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable == routingTable, equalTo(true));
logger.info("Start the primary shard (on node1)");
RoutingNodes routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.node("node1").shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(10));
for (int i = 0; i < routingTable.index("test").shards().size(); i++) {
assertThat(routingTable.index("test").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test").shard(i).primaryShard().currentNodeId(), equalTo("node1"));
assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1));
// backup shards are initializing as well, we make sure that they recover from primary *started* shards in the IndicesClusterStateService
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).currentNodeId(), equalTo("node2"));
}
logger.info("Reroute, nothing should change");
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
assertThat(prevRoutingTable == routingTable, equalTo(true));
logger.info("Start the backup shard");
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.node("node2").shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(10));
for (int i = 0; i < routingTable.index("test").shards().size(); i++) {
assertThat(routingTable.index("test").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test").shard(i).primaryShard().currentNodeId(), equalTo("node1"));
assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1));
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(STARTED));
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).currentNodeId(), equalTo("node2"));
}
assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), equalTo(10));
assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), equalTo(10));
logger.info("Add another node and perform rerouting");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node3"))).build();
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(10));
assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED, RELOCATING), equalTo(10));
assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), lessThan(10));
assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED, RELOCATING), equalTo(10));
assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), lessThan(10));
assertThat(routingNodes.node("node3").numberOfShardsWithState(INITIALIZING), equalTo(6));
logger.info("Start the shards on node 3");
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.node("node3").shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(10));
assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), equalTo(7));
assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), equalTo(7));
assertThat(routingNodes.node("node3").numberOfShardsWithState(STARTED), equalTo(6));
}
}
| apache-2.0 |
metamx/druid | api/src/main/java/io/druid/segment/loading/SegmentLoadingException.java | 1351 | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.segment.loading;
import io.druid.guice.annotations.PublicApi;
import io.druid.java.util.common.StringUtils;
/**
*/
@PublicApi
public class SegmentLoadingException extends Exception
{
public SegmentLoadingException(
String formatString,
Object... objs
)
{
super(StringUtils.nonStrictFormat(formatString, objs));
}
public SegmentLoadingException(
Throwable cause,
String formatString,
Object... objs
)
{
super(StringUtils.nonStrictFormat(formatString, objs), cause);
}
}
| apache-2.0 |
IanvsPoplicola/elasticsearch | core/src/main/java/org/elasticsearch/index/mapper/MapperService.java | 35821 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index.mapper;
import com.carrotsearch.hppc.ObjectHashSet;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.DelegatingAnalyzerWrapper;
import org.elasticsearch.ElasticsearchGenerationException;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.AbstractIndexComponent;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.IndexAnalyzers;
import org.elasticsearch.index.mapper.Mapper.BuilderContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.similarity.SimilarityService;
import org.elasticsearch.indices.InvalidTypeNameException;
import org.elasticsearch.indices.TypeMissingException;
import org.elasticsearch.indices.mapper.MapperRegistry;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static java.util.Collections.unmodifiableMap;
public class MapperService extends AbstractIndexComponent implements Closeable {
/**
* The reason why a mapping is being merged.
*/
public enum MergeReason {
/**
* Create or update a mapping.
*/
MAPPING_UPDATE,
/**
* Recovery of an existing mapping, for instance because of a restart,
* if a shard was moved to a different node or for administrative
* purposes.
*/
MAPPING_RECOVERY;
}
public static final String DEFAULT_MAPPING = "_default_";
public static final Setting<Long> INDEX_MAPPING_NESTED_FIELDS_LIMIT_SETTING =
Setting.longSetting("index.mapping.nested_fields.limit", 50L, 0, Property.Dynamic, Property.IndexScope);
public static final Setting<Long> INDEX_MAPPING_TOTAL_FIELDS_LIMIT_SETTING =
Setting.longSetting("index.mapping.total_fields.limit", 1000L, 0, Property.Dynamic, Property.IndexScope);
public static final Setting<Long> INDEX_MAPPING_DEPTH_LIMIT_SETTING =
Setting.longSetting("index.mapping.depth.limit", 20L, 1, Property.Dynamic, Property.IndexScope);
public static final boolean INDEX_MAPPER_DYNAMIC_DEFAULT = true;
public static final Setting<Boolean> INDEX_MAPPER_DYNAMIC_SETTING =
Setting.boolSetting("index.mapper.dynamic", INDEX_MAPPER_DYNAMIC_DEFAULT, Property.Dynamic, Property.IndexScope);
private static ObjectHashSet<String> META_FIELDS = ObjectHashSet.from(
"_uid", "_id", "_type", "_all", "_parent", "_routing", "_index",
"_size", "_timestamp", "_ttl"
);
private final IndexAnalyzers indexAnalyzers;
/**
* Will create types automatically if they do not exists in the mapping definition yet
*/
private final boolean dynamic;
private volatile String defaultMappingSource;
private volatile Map<String, DocumentMapper> mappers = emptyMap();
private volatile FieldTypeLookup fieldTypes;
private volatile Map<String, ObjectMapper> fullPathObjectMappers = emptyMap();
private boolean hasNested = false; // updated dynamically to true when a nested object is added
private boolean allEnabled = false; // updated dynamically to true when _all is enabled
private final DocumentMapperParser documentParser;
private final MapperAnalyzerWrapper indexAnalyzer;
private final MapperAnalyzerWrapper searchAnalyzer;
private final MapperAnalyzerWrapper searchQuoteAnalyzer;
private volatile Map<String, MappedFieldType> unmappedFieldTypes = emptyMap();
private volatile Set<String> parentTypes = emptySet();
final MapperRegistry mapperRegistry;
public MapperService(IndexSettings indexSettings, IndexAnalyzers indexAnalyzers, NamedXContentRegistry xContentRegistry,
SimilarityService similarityService, MapperRegistry mapperRegistry,
Supplier<QueryShardContext> queryShardContextSupplier) {
super(indexSettings);
this.indexAnalyzers = indexAnalyzers;
this.fieldTypes = new FieldTypeLookup();
this.documentParser = new DocumentMapperParser(indexSettings, this, indexAnalyzers, xContentRegistry, similarityService,
mapperRegistry, queryShardContextSupplier);
this.indexAnalyzer = new MapperAnalyzerWrapper(indexAnalyzers.getDefaultIndexAnalyzer(), p -> p.indexAnalyzer());
this.searchAnalyzer = new MapperAnalyzerWrapper(indexAnalyzers.getDefaultSearchAnalyzer(), p -> p.searchAnalyzer());
this.searchQuoteAnalyzer = new MapperAnalyzerWrapper(indexAnalyzers.getDefaultSearchQuoteAnalyzer(), p -> p.searchQuoteAnalyzer());
this.mapperRegistry = mapperRegistry;
this.dynamic = this.indexSettings.getValue(INDEX_MAPPER_DYNAMIC_SETTING);
defaultMappingSource = "{\"_default_\":{}}";
if (logger.isTraceEnabled()) {
logger.trace("using dynamic[{}], default mapping source[{}]", dynamic, defaultMappingSource);
} else if (logger.isDebugEnabled()) {
logger.debug("using dynamic[{}]", dynamic);
}
}
public boolean hasNested() {
return this.hasNested;
}
/**
* Returns true if the "_all" field is enabled on any type.
*/
public boolean allEnabled() {
return this.allEnabled;
}
/**
* returns an immutable iterator over current document mappers.
*
* @param includingDefaultMapping indicates whether the iterator should contain the {@link #DEFAULT_MAPPING} document mapper.
* As is this not really an active type, you would typically set this to false
*/
public Iterable<DocumentMapper> docMappers(final boolean includingDefaultMapping) {
return () -> {
final Collection<DocumentMapper> documentMappers;
if (includingDefaultMapping) {
documentMappers = mappers.values();
} else {
documentMappers = mappers.values().stream().filter(mapper -> !DEFAULT_MAPPING.equals(mapper.type())).collect(Collectors.toList());
}
return Collections.unmodifiableCollection(documentMappers).iterator();
};
}
public IndexAnalyzers getIndexAnalyzers() {
return this.indexAnalyzers;
}
public DocumentMapperParser documentMapperParser() {
return this.documentParser;
}
/**
* Parses the mappings (formatted as JSON) into a map
*/
public static Map<String, Object> parseMapping(NamedXContentRegistry xContentRegistry, String mappingSource) throws Exception {
try (XContentParser parser = XContentType.JSON.xContent().createParser(xContentRegistry, mappingSource)) {
return parser.map();
}
}
/**
* Update mapping by only merging the metadata that is different between received and stored entries
*/
public boolean updateMapping(IndexMetaData indexMetaData) throws IOException {
assert indexMetaData.getIndex().equals(index()) : "index mismatch: expected " + index() + " but was " + indexMetaData.getIndex();
// go over and add the relevant mappings (or update them)
final Set<String> existingMappers = new HashSet<>(mappers.keySet());
final Map<String, DocumentMapper> updatedEntries;
try {
// only update entries if needed
updatedEntries = internalMerge(indexMetaData, MergeReason.MAPPING_RECOVERY, true, true);
} catch (Exception e) {
logger.warn((org.apache.logging.log4j.util.Supplier<?>) () -> new ParameterizedMessage("[{}] failed to apply mappings", index()), e);
throw e;
}
boolean requireRefresh = false;
for (DocumentMapper documentMapper : updatedEntries.values()) {
String mappingType = documentMapper.type();
CompressedXContent incomingMappingSource = indexMetaData.mapping(mappingType).source();
String op = existingMappers.contains(mappingType) ? "updated" : "added";
if (logger.isDebugEnabled() && incomingMappingSource.compressed().length < 512) {
logger.debug("[{}] {} mapping [{}], source [{}]", index(), op, mappingType, incomingMappingSource.string());
} else if (logger.isTraceEnabled()) {
logger.trace("[{}] {} mapping [{}], source [{}]", index(), op, mappingType, incomingMappingSource.string());
} else {
logger.debug("[{}] {} mapping [{}] (source suppressed due to length, use TRACE level if needed)", index(), op, mappingType);
}
// refresh mapping can happen when the parsing/merging of the mapping from the metadata doesn't result in the same
// mapping, in this case, we send to the master to refresh its own version of the mappings (to conform with the
// merge version of it, which it does when refreshing the mappings), and warn log it.
if (documentMapper(mappingType).mappingSource().equals(incomingMappingSource) == false) {
logger.debug("[{}] parsed mapping [{}], and got different sources\noriginal:\n{}\nparsed:\n{}", index(), mappingType,
incomingMappingSource, documentMapper(mappingType).mappingSource());
requireRefresh = true;
}
}
return requireRefresh;
}
public void merge(Map<String, Map<String, Object>> mappings, MergeReason reason, boolean updateAllTypes) {
Map<String, CompressedXContent> mappingSourcesCompressed = new LinkedHashMap<>(mappings.size());
for (Map.Entry<String, Map<String, Object>> entry : mappings.entrySet()) {
try {
mappingSourcesCompressed.put(entry.getKey(), new CompressedXContent(XContentFactory.jsonBuilder().map(entry.getValue()).string()));
} catch (Exception e) {
throw new MapperParsingException("Failed to parse mapping [{}]: {}", e, entry.getKey(), e.getMessage());
}
}
internalMerge(mappingSourcesCompressed, reason, updateAllTypes);
}
public void merge(IndexMetaData indexMetaData, MergeReason reason, boolean updateAllTypes) {
internalMerge(indexMetaData, reason, updateAllTypes, false);
}
public DocumentMapper merge(String type, CompressedXContent mappingSource, MergeReason reason, boolean updateAllTypes) {
return internalMerge(Collections.singletonMap(type, mappingSource), reason, updateAllTypes).get(type);
}
private synchronized Map<String, DocumentMapper> internalMerge(IndexMetaData indexMetaData, MergeReason reason, boolean updateAllTypes,
boolean onlyUpdateIfNeeded) {
Map<String, CompressedXContent> map = new LinkedHashMap<>();
for (ObjectCursor<MappingMetaData> cursor : indexMetaData.getMappings().values()) {
MappingMetaData mappingMetaData = cursor.value;
if (onlyUpdateIfNeeded) {
DocumentMapper existingMapper = documentMapper(mappingMetaData.type());
if (existingMapper == null || mappingMetaData.source().equals(existingMapper.mappingSource()) == false) {
map.put(mappingMetaData.type(), mappingMetaData.source());
}
} else {
map.put(mappingMetaData.type(), mappingMetaData.source());
}
}
return internalMerge(map, reason, updateAllTypes);
}
private synchronized Map<String, DocumentMapper> internalMerge(Map<String, CompressedXContent> mappings, MergeReason reason, boolean updateAllTypes) {
DocumentMapper defaultMapper = null;
String defaultMappingSource = null;
if (mappings.containsKey(DEFAULT_MAPPING)) {
// verify we can parse it
// NOTE: never apply the default here
try {
defaultMapper = documentParser.parse(DEFAULT_MAPPING, mappings.get(DEFAULT_MAPPING));
} catch (Exception e) {
throw new MapperParsingException("Failed to parse mapping [{}]: {}", e, DEFAULT_MAPPING, e.getMessage());
}
try {
defaultMappingSource = mappings.get(DEFAULT_MAPPING).string();
} catch (IOException e) {
throw new ElasticsearchGenerationException("failed to un-compress", e);
}
}
final String defaultMappingSourceOrLastStored;
if (defaultMappingSource != null) {
defaultMappingSourceOrLastStored = defaultMappingSource;
} else {
defaultMappingSourceOrLastStored = this.defaultMappingSource;
}
List<DocumentMapper> documentMappers = new ArrayList<>();
for (Map.Entry<String, CompressedXContent> entry : mappings.entrySet()) {
String type = entry.getKey();
if (type.equals(DEFAULT_MAPPING)) {
continue;
}
final boolean applyDefault =
// the default was already applied if we are recovering
reason != MergeReason.MAPPING_RECOVERY
// only apply the default mapping if we don't have the type yet
&& mappers.containsKey(type) == false;
try {
DocumentMapper documentMapper =
documentParser.parse(type, entry.getValue(), applyDefault ? defaultMappingSourceOrLastStored : null);
documentMappers.add(documentMapper);
} catch (Exception e) {
throw new MapperParsingException("Failed to parse mapping [{}]: {}", e, entry.getKey(), e.getMessage());
}
}
return internalMerge(defaultMapper, defaultMappingSource, documentMappers, reason, updateAllTypes);
}
private synchronized Map<String, DocumentMapper> internalMerge(@Nullable DocumentMapper defaultMapper, @Nullable String defaultMappingSource,
List<DocumentMapper> documentMappers, MergeReason reason, boolean updateAllTypes) {
boolean hasNested = this.hasNested;
boolean allEnabled = this.allEnabled;
Map<String, ObjectMapper> fullPathObjectMappers = this.fullPathObjectMappers;
FieldTypeLookup fieldTypes = this.fieldTypes;
Set<String> parentTypes = this.parentTypes;
Map<String, DocumentMapper> mappers = new HashMap<>(this.mappers);
Map<String, DocumentMapper> results = new LinkedHashMap<>(documentMappers.size() + 1);
if (defaultMapper != null) {
assert defaultMapper.type().equals(DEFAULT_MAPPING);
mappers.put(DEFAULT_MAPPING, defaultMapper);
results.put(DEFAULT_MAPPING, defaultMapper);
}
for (DocumentMapper mapper : documentMappers) {
// check naming
if (mapper.type().length() == 0) {
throw new InvalidTypeNameException("mapping type name is empty");
}
if (mapper.type().length() > 255) {
throw new InvalidTypeNameException("mapping type name [" + mapper.type() + "] is too long; limit is length 255 but was [" + mapper.type().length() + "]");
}
if (mapper.type().charAt(0) == '_') {
throw new InvalidTypeNameException("mapping type name [" + mapper.type() + "] can't start with '_'");
}
if (mapper.type().contains("#")) {
throw new InvalidTypeNameException("mapping type name [" + mapper.type() + "] should not include '#' in it");
}
if (mapper.type().contains(",")) {
throw new InvalidTypeNameException("mapping type name [" + mapper.type() + "] should not include ',' in it");
}
if (mapper.type().equals(mapper.parentFieldMapper().type())) {
throw new IllegalArgumentException("The [_parent.type] option can't point to the same type");
}
if (typeNameStartsWithIllegalDot(mapper)) {
throw new IllegalArgumentException("mapping type name [" + mapper.type() + "] must not start with a '.'");
}
// compute the merged DocumentMapper
DocumentMapper oldMapper = mappers.get(mapper.type());
DocumentMapper newMapper;
if (oldMapper != null) {
newMapper = oldMapper.merge(mapper.mapping(), updateAllTypes);
} else {
newMapper = mapper;
}
// check basic sanity of the new mapping
List<ObjectMapper> objectMappers = new ArrayList<>();
List<FieldMapper> fieldMappers = new ArrayList<>();
Collections.addAll(fieldMappers, newMapper.mapping().metadataMappers);
MapperUtils.collect(newMapper.mapping().root(), objectMappers, fieldMappers);
checkFieldUniqueness(newMapper.type(), objectMappers, fieldMappers, fullPathObjectMappers, fieldTypes);
checkObjectsCompatibility(objectMappers, updateAllTypes, fullPathObjectMappers);
checkPartitionedIndexConstraints(newMapper);
// update lookup data-structures
// this will in particular make sure that the merged fields are compatible with other types
fieldTypes = fieldTypes.copyAndAddAll(newMapper.type(), fieldMappers, updateAllTypes);
for (ObjectMapper objectMapper : objectMappers) {
if (fullPathObjectMappers == this.fullPathObjectMappers) {
// first time through the loops
fullPathObjectMappers = new HashMap<>(this.fullPathObjectMappers);
}
fullPathObjectMappers.put(objectMapper.fullPath(), objectMapper);
if (objectMapper.nested().isNested()) {
hasNested = true;
}
}
if (reason == MergeReason.MAPPING_UPDATE) {
// this check will only be performed on the master node when there is
// a call to the update mapping API. For all other cases like
// the master node restoring mappings from disk or data nodes
// deserializing cluster state that was sent by the master node,
// this check will be skipped.
checkTotalFieldsLimit(objectMappers.size() + fieldMappers.size());
}
if (oldMapper == null && newMapper.parentFieldMapper().active()) {
if (parentTypes == this.parentTypes) {
// first time through the loop
parentTypes = new HashSet<>(this.parentTypes);
}
parentTypes.add(mapper.parentFieldMapper().type());
}
// this is only correct because types cannot be removed and we do not
// allow to disable an existing _all field
allEnabled |= mapper.allFieldMapper().enabled();
results.put(newMapper.type(), newMapper);
mappers.put(newMapper.type(), newMapper);
}
if (reason == MergeReason.MAPPING_UPDATE) {
// this check will only be performed on the master node when there is
// a call to the update mapping API. For all other cases like
// the master node restoring mappings from disk or data nodes
// deserializing cluster state that was sent by the master node,
// this check will be skipped.
checkNestedFieldsLimit(fullPathObjectMappers);
checkDepthLimit(fullPathObjectMappers.keySet());
}
for (Map.Entry<String, DocumentMapper> entry : mappers.entrySet()) {
if (entry.getKey().equals(DEFAULT_MAPPING)) {
continue;
}
DocumentMapper documentMapper = entry.getValue();
// apply changes to the field types back
DocumentMapper updatedDocumentMapper = documentMapper.updateFieldType(fieldTypes.fullNameToFieldType);
if (updatedDocumentMapper != documentMapper) {
// update both mappers and result
entry.setValue(updatedDocumentMapper);
if (results.containsKey(updatedDocumentMapper.type())) {
results.put(updatedDocumentMapper.type(), updatedDocumentMapper);
}
}
}
// make structures immutable
mappers = Collections.unmodifiableMap(mappers);
results = Collections.unmodifiableMap(results);
// only need to immutably rewrap these if the previous reference was changed.
// if not then they are already implicitly immutable.
if (fullPathObjectMappers != this.fullPathObjectMappers) {
fullPathObjectMappers = Collections.unmodifiableMap(fullPathObjectMappers);
}
if (parentTypes != this.parentTypes) {
parentTypes = Collections.unmodifiableSet(parentTypes);
}
// commit the change
if (defaultMappingSource != null) {
this.defaultMappingSource = defaultMappingSource;
}
this.mappers = mappers;
this.fieldTypes = fieldTypes;
this.hasNested = hasNested;
this.fullPathObjectMappers = fullPathObjectMappers;
this.parentTypes = parentTypes;
this.allEnabled = allEnabled;
assert assertMappersShareSameFieldType();
assert results.values().stream().allMatch(this::assertSerialization);
return results;
}
private boolean assertMappersShareSameFieldType() {
for (DocumentMapper mapper : docMappers(false)) {
List<FieldMapper> fieldMappers = new ArrayList<>();
Collections.addAll(fieldMappers, mapper.mapping().metadataMappers);
MapperUtils.collect(mapper.root(), new ArrayList<>(), fieldMappers);
for (FieldMapper fieldMapper : fieldMappers) {
assert fieldMapper.fieldType() == fieldTypes.get(fieldMapper.name()) : fieldMapper.name();
}
}
return true;
}
private boolean typeNameStartsWithIllegalDot(DocumentMapper mapper) {
return mapper.type().startsWith(".");
}
private boolean assertSerialization(DocumentMapper mapper) {
// capture the source now, it may change due to concurrent parsing
final CompressedXContent mappingSource = mapper.mappingSource();
DocumentMapper newMapper = parse(mapper.type(), mappingSource, false);
if (newMapper.mappingSource().equals(mappingSource) == false) {
throw new IllegalStateException("DocumentMapper serialization result is different from source. \n--> Source ["
+ mappingSource + "]\n--> Result ["
+ newMapper.mappingSource() + "]");
}
return true;
}
private static void checkFieldUniqueness(String type, Collection<ObjectMapper> objectMappers, Collection<FieldMapper> fieldMappers,
Map<String, ObjectMapper> fullPathObjectMappers, FieldTypeLookup fieldTypes) {
// first check within mapping
final Set<String> objectFullNames = new HashSet<>();
for (ObjectMapper objectMapper : objectMappers) {
final String fullPath = objectMapper.fullPath();
if (objectFullNames.add(fullPath) == false) {
throw new IllegalArgumentException("Object mapper [" + fullPath + "] is defined twice in mapping for type [" + type + "]");
}
}
final Set<String> fieldNames = new HashSet<>();
for (FieldMapper fieldMapper : fieldMappers) {
final String name = fieldMapper.name();
if (objectFullNames.contains(name)) {
throw new IllegalArgumentException("Field [" + name + "] is defined both as an object and a field in [" + type + "]");
} else if (fieldNames.add(name) == false) {
throw new IllegalArgumentException("Field [" + name + "] is defined twice in [" + type + "]");
}
}
// then check other types
for (String fieldName : fieldNames) {
if (fullPathObjectMappers.containsKey(fieldName)) {
throw new IllegalArgumentException("[" + fieldName + "] is defined as a field in mapping [" + type
+ "] but this name is already used for an object in other types");
}
}
for (String objectPath : objectFullNames) {
if (fieldTypes.get(objectPath) != null) {
throw new IllegalArgumentException("[" + objectPath + "] is defined as an object in mapping [" + type
+ "] but this name is already used for a field in other types");
}
}
}
private static void checkObjectsCompatibility(Collection<ObjectMapper> objectMappers, boolean updateAllTypes,
Map<String, ObjectMapper> fullPathObjectMappers) {
for (ObjectMapper newObjectMapper : objectMappers) {
ObjectMapper existingObjectMapper = fullPathObjectMappers.get(newObjectMapper.fullPath());
if (existingObjectMapper != null) {
// simulate a merge and ignore the result, we are just interested
// in exceptions here
existingObjectMapper.merge(newObjectMapper, updateAllTypes);
}
}
}
private void checkNestedFieldsLimit(Map<String, ObjectMapper> fullPathObjectMappers) {
long allowedNestedFields = indexSettings.getValue(INDEX_MAPPING_NESTED_FIELDS_LIMIT_SETTING);
long actualNestedFields = 0;
for (ObjectMapper objectMapper : fullPathObjectMappers.values()) {
if (objectMapper.nested().isNested()) {
actualNestedFields++;
}
}
if (actualNestedFields > allowedNestedFields) {
throw new IllegalArgumentException("Limit of nested fields [" + allowedNestedFields + "] in index [" + index().getName() + "] has been exceeded");
}
}
private void checkTotalFieldsLimit(long totalMappers) {
long allowedTotalFields = indexSettings.getValue(INDEX_MAPPING_TOTAL_FIELDS_LIMIT_SETTING);
if (allowedTotalFields < totalMappers) {
throw new IllegalArgumentException("Limit of total fields [" + allowedTotalFields + "] in index [" + index().getName() + "] has been exceeded");
}
}
private void checkDepthLimit(Collection<String> objectPaths) {
final long maxDepth = indexSettings.getValue(INDEX_MAPPING_DEPTH_LIMIT_SETTING);
for (String objectPath : objectPaths) {
checkDepthLimit(objectPath, maxDepth);
}
}
private void checkDepthLimit(String objectPath, long maxDepth) {
int numDots = 0;
for (int i = 0; i < objectPath.length(); ++i) {
if (objectPath.charAt(i) == '.') {
numDots += 1;
}
}
final int depth = numDots + 2;
if (depth > maxDepth) {
throw new IllegalArgumentException("Limit of mapping depth [" + maxDepth + "] in index [" + index().getName()
+ "] has been exceeded due to object field [" + objectPath + "]");
}
}
private void checkPartitionedIndexConstraints(DocumentMapper newMapper) {
if (indexSettings.getIndexMetaData().isRoutingPartitionedIndex()) {
if (newMapper.parentFieldMapper().active()) {
throw new IllegalArgumentException("mapping type name [" + newMapper.type() + "] cannot have a "
+ "_parent field for the partitioned index [" + indexSettings.getIndex().getName() + "]");
}
if (!newMapper.routingFieldMapper().required()) {
throw new IllegalArgumentException("mapping type [" + newMapper.type() + "] must have routing "
+ "required for partitioned index [" + indexSettings.getIndex().getName() + "]");
}
}
}
public DocumentMapper parse(String mappingType, CompressedXContent mappingSource, boolean applyDefault) throws MapperParsingException {
return documentParser.parse(mappingType, mappingSource, applyDefault ? defaultMappingSource : null);
}
public boolean hasMapping(String mappingType) {
return mappers.containsKey(mappingType);
}
/**
* Return the set of concrete types that have a mapping.
* NOTE: this does not return the default mapping.
*/
public Collection<String> types() {
final Set<String> types = new HashSet<>(mappers.keySet());
types.remove(DEFAULT_MAPPING);
return Collections.unmodifiableSet(types);
}
/**
* Return the {@link DocumentMapper} for the given type. By using the special
* {@value #DEFAULT_MAPPING} type, you can get a {@link DocumentMapper} for
* the default mapping.
*/
public DocumentMapper documentMapper(String type) {
return mappers.get(type);
}
/**
* Returns the document mapper created, including a mapping update if the
* type has been dynamically created.
*/
public DocumentMapperForType documentMapperWithAutoCreate(String type) {
DocumentMapper mapper = mappers.get(type);
if (mapper != null) {
return new DocumentMapperForType(mapper, null);
}
if (!dynamic) {
throw new TypeMissingException(index(),
new IllegalStateException("trying to auto create mapping, but dynamic mapping is disabled"), type);
}
mapper = parse(type, null, true);
return new DocumentMapperForType(mapper, mapper.mapping());
}
/**
* Returns the {@link MappedFieldType} for the give fullName.
*
* If multiple types have fields with the same full name, the first is returned.
*/
public MappedFieldType fullName(String fullName) {
return fieldTypes.get(fullName);
}
/**
* Returns all the fields that match the given pattern. If the pattern is prefixed with a type
* then the fields will be returned with a type prefix.
*/
public Collection<String> simpleMatchToIndexNames(String pattern) {
if (Regex.isSimpleMatchPattern(pattern) == false) {
// no wildcards
return Collections.singletonList(pattern);
}
return fieldTypes.simpleMatchToFullName(pattern);
}
public ObjectMapper getObjectMapper(String name) {
return fullPathObjectMappers.get(name);
}
/**
* Given a type (eg. long, string, ...), return an anonymous field mapper that can be used for search operations.
*/
public MappedFieldType unmappedFieldType(String type) {
if (type.equals("string")) {
deprecationLogger.deprecated("[unmapped_type:string] should be replaced with [unmapped_type:keyword]");
type = "keyword";
}
MappedFieldType fieldType = unmappedFieldTypes.get(type);
if (fieldType == null) {
final Mapper.TypeParser.ParserContext parserContext = documentMapperParser().parserContext(type);
Mapper.TypeParser typeParser = parserContext.typeParser(type);
if (typeParser == null) {
throw new IllegalArgumentException("No mapper found for type [" + type + "]");
}
final Mapper.Builder<?, ?> builder = typeParser.parse("__anonymous_" + type, emptyMap(), parserContext);
final BuilderContext builderContext = new BuilderContext(indexSettings.getSettings(), new ContentPath(1));
fieldType = ((FieldMapper)builder.build(builderContext)).fieldType();
// There is no need to synchronize writes here. In the case of concurrent access, we could just
// compute some mappers several times, which is not a big deal
Map<String, MappedFieldType> newUnmappedFieldTypes = new HashMap<>();
newUnmappedFieldTypes.putAll(unmappedFieldTypes);
newUnmappedFieldTypes.put(type, fieldType);
unmappedFieldTypes = unmodifiableMap(newUnmappedFieldTypes);
}
return fieldType;
}
public Analyzer indexAnalyzer() {
return this.indexAnalyzer;
}
public Analyzer searchAnalyzer() {
return this.searchAnalyzer;
}
public Analyzer searchQuoteAnalyzer() {
return this.searchQuoteAnalyzer;
}
public Set<String> getParentTypes() {
return parentTypes;
}
@Override
public void close() throws IOException {
indexAnalyzers.close();
}
/**
* @return Whether a field is a metadata field.
*/
public static boolean isMetadataField(String fieldName) {
return META_FIELDS.contains(fieldName);
}
public static String[] getAllMetaFields() {
return META_FIELDS.toArray(String.class);
}
/** An analyzer wrapper that can lookup fields within the index mappings */
final class MapperAnalyzerWrapper extends DelegatingAnalyzerWrapper {
private final Analyzer defaultAnalyzer;
private final Function<MappedFieldType, Analyzer> extractAnalyzer;
MapperAnalyzerWrapper(Analyzer defaultAnalyzer, Function<MappedFieldType, Analyzer> extractAnalyzer) {
super(Analyzer.PER_FIELD_REUSE_STRATEGY);
this.defaultAnalyzer = defaultAnalyzer;
this.extractAnalyzer = extractAnalyzer;
}
@Override
protected Analyzer getWrappedAnalyzer(String fieldName) {
MappedFieldType fieldType = fullName(fieldName);
if (fieldType != null) {
Analyzer analyzer = extractAnalyzer.apply(fieldType);
if (analyzer != null) {
return analyzer;
}
}
return defaultAnalyzer;
}
}
}
| apache-2.0 |
ljhljh235/azure-sdk-for-java | azure-mgmt-appservice/src/main/java/com/microsoft/azure/management/appservice/implementation/SiteSourceControlInner.java | 4166 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.appservice.implementation;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.azure.Resource;
/**
* Source control configuration for an app.
*/
@JsonFlatten
public class SiteSourceControlInner extends Resource {
/**
* Repository or source control URL.
*/
@JsonProperty(value = "properties.repoUrl")
private String repoUrl;
/**
* Name of branch to use for deployment.
*/
@JsonProperty(value = "properties.branch")
private String branch;
/**
* <code>true</code> to limit to manual integration;
* <code>false</code> to enable continuous integration (which
* configures webhooks into online repos like GitHub).
*/
@JsonProperty(value = "properties.isManualIntegration")
private Boolean isManualIntegration;
/**
* <code>true</code> to enable deployment rollback; otherwise,
* <code>false</code>.
*/
@JsonProperty(value = "properties.deploymentRollbackEnabled")
private Boolean deploymentRollbackEnabled;
/**
* <code>true</code> for a Mercurial repository;
* <code>false</code> for a Git repository.
*/
@JsonProperty(value = "properties.isMercurial")
private Boolean isMercurial;
/**
* Get the repoUrl value.
*
* @return the repoUrl value
*/
public String repoUrl() {
return this.repoUrl;
}
/**
* Set the repoUrl value.
*
* @param repoUrl the repoUrl value to set
* @return the SiteSourceControlInner object itself.
*/
public SiteSourceControlInner withRepoUrl(String repoUrl) {
this.repoUrl = repoUrl;
return this;
}
/**
* Get the branch value.
*
* @return the branch value
*/
public String branch() {
return this.branch;
}
/**
* Set the branch value.
*
* @param branch the branch value to set
* @return the SiteSourceControlInner object itself.
*/
public SiteSourceControlInner withBranch(String branch) {
this.branch = branch;
return this;
}
/**
* Get the isManualIntegration value.
*
* @return the isManualIntegration value
*/
public Boolean isManualIntegration() {
return this.isManualIntegration;
}
/**
* Set the isManualIntegration value.
*
* @param isManualIntegration the isManualIntegration value to set
* @return the SiteSourceControlInner object itself.
*/
public SiteSourceControlInner withIsManualIntegration(Boolean isManualIntegration) {
this.isManualIntegration = isManualIntegration;
return this;
}
/**
* Get the deploymentRollbackEnabled value.
*
* @return the deploymentRollbackEnabled value
*/
public Boolean deploymentRollbackEnabled() {
return this.deploymentRollbackEnabled;
}
/**
* Set the deploymentRollbackEnabled value.
*
* @param deploymentRollbackEnabled the deploymentRollbackEnabled value to set
* @return the SiteSourceControlInner object itself.
*/
public SiteSourceControlInner withDeploymentRollbackEnabled(Boolean deploymentRollbackEnabled) {
this.deploymentRollbackEnabled = deploymentRollbackEnabled;
return this;
}
/**
* Get the isMercurial value.
*
* @return the isMercurial value
*/
public Boolean isMercurial() {
return this.isMercurial;
}
/**
* Set the isMercurial value.
*
* @param isMercurial the isMercurial value to set
* @return the SiteSourceControlInner object itself.
*/
public SiteSourceControlInner withIsMercurial(Boolean isMercurial) {
this.isMercurial = isMercurial;
return this;
}
}
| apache-2.0 |
ya7lelkom/google-api-ads-ruby | dfp_api/examples/v201408/content_service/get_all_content.rb | 2792 | #!/usr/bin/env ruby
# Encoding: utf-8
#
# Author:: api.dklimkin@gmail.com (Danial Klimkin)
#
# Copyright:: Copyright 2011, Google Inc. All Rights Reserved.
#
# License:: Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example gets all content.
#
# This feature is only available to DFP video publishers.
#
# Tags: ContentService.getContentByStatement
require 'dfp_api'
API_VERSION = :v201408
PAGE_SIZE = 500
def get_all_content()
# Get DfpApi instance and load configuration from ~/dfp_api.yml.
dfp = DfpApi::Api.new
# To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
# the configuration file or provide your own logger:
# dfp.logger = Logger.new('dfp_xml.log')
# Get the ContentService.
content_service = dfp.service(:ContentService, API_VERSION)
# Define initial values.
offset = 0
page = {}
begin
# Create statement for one page with current offset.
statement = {:query => "ORDER BY id ASC LIMIT %d OFFSET %d" %
[PAGE_SIZE, offset]}
# Get content by statement.
page = content_service.get_content_by_statement(statement)
if page[:results]
# Increase query offset by page size.
offset += PAGE_SIZE
# Get the start index for printout.
start_index = page[:start_index]
# Print details about each content object in results page.
page[:results].each_with_index do |content, index|
puts "%d) Content ID: %d, name: %s, status: %s." % [index + start_index,
content[:id], content[:name], content[:status]]
end
end
end while offset < page[:total_result_set_size]
# Print a footer
if page.include?(:total_result_set_size)
puts "Total number of results: %d" % page[:total_result_set_size]
end
end
if __FILE__ == $0
begin
get_all_content()
# HTTP errors.
rescue AdsCommon::Errors::HttpError => e
puts "HTTP Error: %s" % e
# API errors.
rescue DfpApi::Errors::ApiException => e
puts "Message: %s" % e.message
puts 'Errors:'
e.errors.each_with_index do |error, index|
puts "\tError [%d]:" % (index + 1)
error.each do |field, value|
puts "\t\t%s: %s" % [field, value]
end
end
end
end
| apache-2.0 |
lsmaira/gradle | subprojects/platform-base/src/main/java/org/gradle/api/internal/resolve/DefaultLocalLibraryResolver.java | 2229 | /*
* Copyright 2016 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
*
* 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.gradle.api.internal.resolve;
import com.google.common.collect.Lists;
import org.gradle.model.ModelMap;
import org.gradle.model.internal.registry.ModelRegistry;
import org.gradle.model.internal.type.ModelType;
import org.gradle.model.internal.type.ModelTypes;
import org.gradle.platform.base.ComponentSpec;
import org.gradle.platform.base.VariantComponent;
import org.gradle.platform.base.VariantComponentSpec;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class DefaultLocalLibraryResolver implements LocalLibraryResolver {
private static final ModelType<ModelMap<ComponentSpec>> COMPONENT_MAP_TYPE = ModelTypes.modelMap(ComponentSpec.class);
@Override
public Collection<VariantComponent> resolveCandidates(ModelRegistry projectModel, String libraryName) {
List<VariantComponent> librarySpecs = Lists.newArrayList();
collectLocalComponents(projectModel, "components", librarySpecs);
collectLocalComponents(projectModel, "testSuites", librarySpecs);
if (librarySpecs.isEmpty()) {
return Collections.emptyList();
}
return librarySpecs;
}
private void collectLocalComponents(ModelRegistry projectModel, String container, List<VariantComponent> librarySpecs) {
ModelMap<ComponentSpec> components = projectModel.find(container, COMPONENT_MAP_TYPE);
if (components != null) {
ModelMap<? extends VariantComponentSpec> libraries = components.withType(VariantComponentSpec.class);
librarySpecs.addAll(libraries.values());
}
}
}
| apache-2.0 |
chrislovecnm/kops | dnsprovider/pkg/dnsprovider/providers/aws/route53/zone.go | 1647 | /*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package route53
import (
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/route53"
"k8s.io/kops/dnsprovider/pkg/dnsprovider"
)
// Compile time check for interface adherence
var _ dnsprovider.Zone = &Zone{}
type Zone struct {
impl *route53.HostedZone
zones *Zones
}
func (zone *Zone) Name() string {
return aws.StringValue(zone.impl.Name)
}
func (zone *Zone) ID() string {
id := aws.StringValue(zone.impl.Id)
id = strings.TrimPrefix(id, "/hostedzone/")
return id
}
func (zone *Zone) ResourceRecordSets() (dnsprovider.ResourceRecordSets, bool) {
return &ResourceRecordSets{zone}, true
}
// Route53HostedZone returns the route53 HostedZone object for the zone.
// This is a "back door" that allows for limited access to the HostedZone,
// without having to requery it, so that we can expose AWS specific functionality.
// Using this method should be avoided where possible; instead prefer to add functionality
// to the cross-provider Zone interface.
func (zone *Zone) Route53HostedZone() *route53.HostedZone {
return zone.impl
}
| apache-2.0 |
jpkrohling/hawkular-btm | tests/instrumentation/src/test/java/org/hawkular/apm/tests/client/camel/ClientCamelSplitterParallelITest.java | 3766 | /*
* Copyright 2015-2017 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.hawkular.apm.tests.client.camel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.builder.xml.XPathBuilder;
import org.hawkular.apm.api.model.trace.Consumer;
import org.hawkular.apm.api.model.trace.Producer;
import org.hawkular.apm.api.model.trace.Trace;
import org.hawkular.apm.api.utils.NodeUtil;
import org.hawkular.apm.tests.common.Wait;
import org.junit.Test;
/**
* @author gbrown
*/
public class ClientCamelSplitterParallelITest extends ClientCamelITestBase {
@Override
public RouteBuilder getRouteBuilder() {
XPathBuilder xPathBuilder = new XPathBuilder("/order/item");
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("file:src/test/data/camel/splitter?noop=true")
.split(xPathBuilder)
.parallelProcessing()
.setHeader("LineItemId")
.xpath("/item/@id", String.class)
.to("file:target/data/camel/splitter?fileName="
+ "${in.header.LineItemId}-${date:now:yyyyMMddHHmmssSSSSS}.xml");
}
};
}
@Test
public void testFileSplitNotParallel() {
Wait.until(() -> getApmMockServer().getTraces().size() == 6);
List<Trace> btxns = getApmMockServer().getTraces();
// Check stored traces (including 1 for the test client)
assertEquals(6, btxns.size());
Trace parent=null;
Producer producer=null;
List<Trace> spawned=new ArrayList<Trace>();
for (Trace trace : btxns) {
List<Consumer> consumers = NodeUtil.findNodes(trace.getNodes(), Consumer.class);
List<Producer> producers = NodeUtil.findNodes(trace.getNodes(), Producer.class);
if (consumers.isEmpty()) {
if (producers.isEmpty()) {
fail("Expected producer");
}
if (producers.size() > 1) {
fail("Expected only 1 producer");
}
if (parent != null) {
fail("Already have a producer btxn");
}
parent = trace;
producer = producers.get(0);
} else if (!producers.isEmpty()) {
fail("Should not have both consumers and producer");
} else if (consumers.size() > 1) {
fail("Only 1 consumer expected per btxn, got: "+consumers.size());
} else {
spawned.add(trace);
}
}
assertEquals(5, spawned.size());
assertNotNull(parent);
// Check 'apm_publish' set on producer
assertTrue(producer.hasProperty("apm_publish"));
assertEquals(producer.getProperties("apm_publish").iterator().next().getValue(), "true");
}
}
| apache-2.0 |
nkgilley/home-assistant | tests/components/zha/test_device.py | 9565 | """Test zha device switch."""
from datetime import timedelta
import time
from unittest import mock
import pytest
import zigpy.zcl.clusters.general as general
import homeassistant.components.zha.core.device as zha_core_device
from homeassistant.const import STATE_OFF, STATE_UNAVAILABLE
import homeassistant.helpers.device_registry as ha_dev_reg
import homeassistant.util.dt as dt_util
from .common import async_enable_traffic, make_zcl_header
from tests.async_mock import patch
from tests.common import async_fire_time_changed
@pytest.fixture
def zigpy_device(zigpy_device_mock):
"""Device tracker zigpy device."""
def _dev(with_basic_channel: bool = True):
in_clusters = [general.OnOff.cluster_id]
if with_basic_channel:
in_clusters.append(general.Basic.cluster_id)
endpoints = {
3: {"in_clusters": in_clusters, "out_clusters": [], "device_type": 0}
}
return zigpy_device_mock(endpoints)
return _dev
@pytest.fixture
def zigpy_device_mains(zigpy_device_mock):
"""Device tracker zigpy device."""
def _dev(with_basic_channel: bool = True):
in_clusters = [general.OnOff.cluster_id]
if with_basic_channel:
in_clusters.append(general.Basic.cluster_id)
endpoints = {
3: {"in_clusters": in_clusters, "out_clusters": [], "device_type": 0}
}
return zigpy_device_mock(
endpoints, node_descriptor=b"\x02@\x84_\x11\x7fd\x00\x00,d\x00\x00"
)
return _dev
@pytest.fixture
def device_with_basic_channel(zigpy_device_mains):
"""Return a zha device with a basic channel present."""
return zigpy_device_mains(with_basic_channel=True)
@pytest.fixture
def device_without_basic_channel(zigpy_device):
"""Return a zha device with a basic channel present."""
return zigpy_device(with_basic_channel=False)
@pytest.fixture
async def ota_zha_device(zha_device_restored, zigpy_device_mock):
"""ZHA device with OTA cluster fixture."""
zigpy_dev = zigpy_device_mock(
{
1: {
"in_clusters": [general.Basic.cluster_id],
"out_clusters": [general.Ota.cluster_id],
"device_type": 0x1234,
}
},
"00:11:22:33:44:55:66:77",
"test manufacturer",
"test model",
)
zha_device = await zha_device_restored(zigpy_dev)
return zha_device
def _send_time_changed(hass, seconds):
"""Send a time changed event."""
now = dt_util.utcnow() + timedelta(seconds=seconds)
async_fire_time_changed(hass, now)
@patch(
"homeassistant.components.zha.core.channels.general.BasicChannel.async_initialize",
new=mock.MagicMock(),
)
async def test_check_available_success(
hass, device_with_basic_channel, zha_device_restored
):
"""Check device availability success on 1st try."""
# pylint: disable=protected-access
zha_device = await zha_device_restored(device_with_basic_channel)
await async_enable_traffic(hass, [zha_device])
basic_ch = device_with_basic_channel.endpoints[3].basic
basic_ch.read_attributes.reset_mock()
device_with_basic_channel.last_seen = None
assert zha_device.available is True
_send_time_changed(hass, zha_core_device.CONSIDER_UNAVAILABLE_MAINS + 2)
await hass.async_block_till_done()
assert zha_device.available is False
assert basic_ch.read_attributes.await_count == 0
device_with_basic_channel.last_seen = (
time.time() - zha_core_device.CONSIDER_UNAVAILABLE_MAINS - 2
)
_seens = [time.time(), device_with_basic_channel.last_seen]
def _update_last_seen(*args, **kwargs):
device_with_basic_channel.last_seen = _seens.pop()
basic_ch.read_attributes.side_effect = _update_last_seen
# successfully ping zigpy device, but zha_device is not yet available
_send_time_changed(hass, 91)
await hass.async_block_till_done()
assert basic_ch.read_attributes.await_count == 1
assert basic_ch.read_attributes.await_args[0][0] == ["manufacturer"]
assert zha_device.available is False
# There was traffic from the device: pings, but not yet available
_send_time_changed(hass, 91)
await hass.async_block_till_done()
assert basic_ch.read_attributes.await_count == 2
assert basic_ch.read_attributes.await_args[0][0] == ["manufacturer"]
assert zha_device.available is False
# There was traffic from the device: don't try to ping, marked as available
_send_time_changed(hass, 91)
await hass.async_block_till_done()
assert basic_ch.read_attributes.await_count == 2
assert basic_ch.read_attributes.await_args[0][0] == ["manufacturer"]
assert zha_device.available is True
@patch(
"homeassistant.components.zha.core.channels.general.BasicChannel.async_initialize",
new=mock.MagicMock(),
)
async def test_check_available_unsuccessful(
hass, device_with_basic_channel, zha_device_restored
):
"""Check device availability all tries fail."""
# pylint: disable=protected-access
zha_device = await zha_device_restored(device_with_basic_channel)
await async_enable_traffic(hass, [zha_device])
basic_ch = device_with_basic_channel.endpoints[3].basic
assert zha_device.available is True
assert basic_ch.read_attributes.await_count == 0
device_with_basic_channel.last_seen = (
time.time() - zha_core_device.CONSIDER_UNAVAILABLE_MAINS - 2
)
# unsuccessfuly ping zigpy device, but zha_device is still available
_send_time_changed(hass, 91)
await hass.async_block_till_done()
assert basic_ch.read_attributes.await_count == 1
assert basic_ch.read_attributes.await_args[0][0] == ["manufacturer"]
assert zha_device.available is True
# still no traffic, but zha_device is still available
_send_time_changed(hass, 91)
await hass.async_block_till_done()
assert basic_ch.read_attributes.await_count == 2
assert basic_ch.read_attributes.await_args[0][0] == ["manufacturer"]
assert zha_device.available is True
# not even trying to update, device is unavailble
_send_time_changed(hass, 91)
await hass.async_block_till_done()
assert basic_ch.read_attributes.await_count == 2
assert basic_ch.read_attributes.await_args[0][0] == ["manufacturer"]
assert zha_device.available is False
@patch(
"homeassistant.components.zha.core.channels.general.BasicChannel.async_initialize",
new=mock.MagicMock(),
)
async def test_check_available_no_basic_channel(
hass, device_without_basic_channel, zha_device_restored, caplog
):
"""Check device availability for a device without basic cluster."""
# pylint: disable=protected-access
zha_device = await zha_device_restored(device_without_basic_channel)
await async_enable_traffic(hass, [zha_device])
assert zha_device.available is True
device_without_basic_channel.last_seen = (
time.time() - zha_core_device.CONSIDER_UNAVAILABLE_BATTERY - 2
)
assert "does not have a mandatory basic cluster" not in caplog.text
_send_time_changed(hass, 91)
await hass.async_block_till_done()
assert zha_device.available is False
assert "does not have a mandatory basic cluster" in caplog.text
async def test_ota_sw_version(hass, ota_zha_device):
"""Test device entry gets sw_version updated via OTA channel."""
ota_ch = ota_zha_device.channels.pools[0].client_channels["1:0x0019"]
dev_registry = await ha_dev_reg.async_get_registry(hass)
entry = dev_registry.async_get(ota_zha_device.device_id)
assert entry.sw_version is None
cluster = ota_ch.cluster
hdr = make_zcl_header(1, global_command=False)
sw_version = 0x2345
cluster.handle_message(hdr, [1, 2, 3, sw_version, None])
await hass.async_block_till_done()
entry = dev_registry.async_get(ota_zha_device.device_id)
assert int(entry.sw_version, base=16) == sw_version
@pytest.mark.parametrize(
"device, last_seen_delta, is_available",
(
("zigpy_device", 0, True),
("zigpy_device", zha_core_device.CONSIDER_UNAVAILABLE_MAINS + 2, True,),
("zigpy_device", zha_core_device.CONSIDER_UNAVAILABLE_BATTERY - 2, True,),
("zigpy_device", zha_core_device.CONSIDER_UNAVAILABLE_BATTERY + 2, False,),
("zigpy_device_mains", 0, True),
("zigpy_device_mains", zha_core_device.CONSIDER_UNAVAILABLE_MAINS - 2, True,),
("zigpy_device_mains", zha_core_device.CONSIDER_UNAVAILABLE_MAINS + 2, False,),
(
"zigpy_device_mains",
zha_core_device.CONSIDER_UNAVAILABLE_BATTERY - 2,
False,
),
(
"zigpy_device_mains",
zha_core_device.CONSIDER_UNAVAILABLE_BATTERY + 2,
False,
),
),
)
async def test_device_restore_availability(
hass, request, device, last_seen_delta, is_available, zha_device_restored
):
"""Test initial availability for restored devices."""
zigpy_device = request.getfixturevalue(device)()
zha_device = await zha_device_restored(
zigpy_device, last_seen=time.time() - last_seen_delta
)
entity_id = "switch.fakemanufacturer_fakemodel_e769900a_on_off"
await hass.async_block_till_done()
# ensure the switch entity was created
assert hass.states.get(entity_id).state is not None
assert zha_device.available is is_available
if is_available:
assert hass.states.get(entity_id).state == STATE_OFF
else:
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
| apache-2.0 |
hgschmie/presto | presto-elasticsearch/src/main/java/io/prestosql/elasticsearch/decoders/IpAddressDecoder.java | 3190 | /*
* 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 io.prestosql.elasticsearch.decoders;
import com.google.common.net.InetAddresses;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import io.prestosql.spi.PrestoException;
import io.prestosql.spi.block.BlockBuilder;
import io.prestosql.spi.type.Type;
import org.elasticsearch.search.SearchHit;
import java.util.function.Supplier;
import static io.airlift.slice.Slices.wrappedBuffer;
import static io.prestosql.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
import static io.prestosql.spi.StandardErrorCode.INVALID_CAST_ARGUMENT;
import static io.prestosql.spi.StandardErrorCode.TYPE_MISMATCH;
import static java.lang.String.format;
import static java.lang.System.arraycopy;
import static java.util.Objects.requireNonNull;
public class IpAddressDecoder
implements Decoder
{
private final String path;
private final Type ipAddressType;
public IpAddressDecoder(String path, Type type)
{
this.path = requireNonNull(path, "path is null");
this.ipAddressType = requireNonNull(type, "type is null");
}
@Override
public void decode(SearchHit hit, Supplier<Object> getter, BlockBuilder output)
{
Object value = getter.get();
if (value == null) {
output.appendNull();
}
else if (value instanceof String) {
String address = (String) value;
Slice slice = castToIpAddress(Slices.utf8Slice(address));
ipAddressType.writeSlice(output, slice);
}
else {
throw new PrestoException(TYPE_MISMATCH, format("Expected a string value for field '%s' of type IP: %s [%s]", path, value, value.getClass().getSimpleName()));
}
}
// This is a copy of IpAddressOperators.castFromVarcharToIpAddress method
private Slice castToIpAddress(Slice slice)
{
byte[] address;
try {
address = InetAddresses.forString(slice.toStringUtf8()).getAddress();
}
catch (IllegalArgumentException e) {
throw new PrestoException(INVALID_CAST_ARGUMENT, "Cannot cast value to IPADDRESS: " + slice.toStringUtf8());
}
byte[] bytes;
if (address.length == 4) {
bytes = new byte[16];
bytes[10] = (byte) 0xff;
bytes[11] = (byte) 0xff;
arraycopy(address, 0, bytes, 12, 4);
}
else if (address.length == 16) {
bytes = address;
}
else {
throw new PrestoException(GENERIC_INTERNAL_ERROR, "Invalid InetAddress length: " + address.length);
}
return wrappedBuffer(bytes);
}
}
| apache-2.0 |
mreutegg/jackrabbit-oak | oak-security-spi/src/main/java/org/apache/jackrabbit/oak/spi/security/principal/PrincipalManagerImpl.java | 3265 | /*
* 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.jackrabbit.oak.spi.security.principal;
import java.security.Principal;
import org.apache.jackrabbit.api.security.principal.PrincipalIterator;
import org.apache.jackrabbit.api.security.principal.PrincipalManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Default implementation of the {@code PrincipalManager} interface.
*/
public class PrincipalManagerImpl implements PrincipalQueryManager, PrincipalManager {
private final PrincipalProvider principalProvider;
public PrincipalManagerImpl(@NotNull PrincipalProvider principalProvider) {
this.principalProvider = principalProvider;
}
//---------------------------------------------------< PrincipalManager >---
@Override
public boolean hasPrincipal(@NotNull String principalName) {
return principalProvider.getPrincipal(principalName) != null;
}
@Override
@Nullable
public Principal getPrincipal(@NotNull String principalName) {
return principalProvider.getPrincipal(principalName);
}
@Override
@NotNull
public PrincipalIterator findPrincipals(@Nullable String simpleFilter) {
return findPrincipals(simpleFilter, PrincipalManager.SEARCH_TYPE_ALL);
}
@Override
@NotNull
public PrincipalIterator findPrincipals(@Nullable String simpleFilter, int searchType) {
return new PrincipalIteratorAdapter(principalProvider.findPrincipals(simpleFilter, searchType));
}
@Override
@NotNull
public PrincipalIterator getPrincipals(int searchType) {
return new PrincipalIteratorAdapter(principalProvider.findPrincipals(searchType));
}
@Override
@NotNull
public PrincipalIterator getGroupMembership(@NotNull Principal principal) {
return new PrincipalIteratorAdapter(principalProvider.getMembershipPrincipals(principal));
}
@Override
@NotNull
public Principal getEveryone() {
Principal everyone = getPrincipal(EveryonePrincipal.NAME);
if (everyone == null) {
everyone = EveryonePrincipal.getInstance();
}
return everyone;
}
@NotNull
@Override
public PrincipalIterator findPrincipals(@Nullable String simpleFilter, boolean fullText, int searchType, long offset, long limit) {
return new PrincipalIteratorAdapter(principalProvider.findPrincipals(simpleFilter, fullText, searchType, offset, limit));
}
}
| apache-2.0 |
fbrier/velocity | examples/app_example1/Example.java | 4007 | /*
* 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 org.apache.velocity.app.Velocity;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.Template;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import java.io.*;
import java.util.ArrayList;
/**
* This class is a simple demonstration of how the Velocity Template Engine
* can be used in a standalone application.
*
* @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: Example.java 463298 2006-10-12 16:10:32Z henning $
*/
public class Example
{
public Example(String templateFile)
{
try
{
/*
* setup
*/
Velocity.init("velocity.properties");
/*
* Make a context object and populate with the data. This
* is where the Velocity engine gets the data to resolve the
* references (ex. $list) in the template
*/
VelocityContext context = new VelocityContext();
context.put("list", getNames());
/*
* get the Template object. This is the parsed version of your
* template input file. Note that getTemplate() can throw
* ResourceNotFoundException : if it doesn't find the template
* ParseErrorException : if there is something wrong with the VTL
* Exception : if something else goes wrong (this is generally
* indicative of as serious problem...)
*/
Template template = null;
try
{
template = Velocity.getTemplate(templateFile);
}
catch( ResourceNotFoundException rnfe )
{
System.out.println("Example : error : cannot find template " + templateFile );
}
catch( ParseErrorException pee )
{
System.out.println("Example : Syntax error in template " + templateFile + ":" + pee );
}
/*
* Now have the template engine process your template using the
* data placed into the context. Think of it as a 'merge'
* of the template and the data to produce the output stream.
*/
BufferedWriter writer = writer = new BufferedWriter(
new OutputStreamWriter(System.out));
if ( template != null)
template.merge(context, writer);
/*
* flush and cleanup
*/
writer.flush();
writer.close();
}
catch( Exception e )
{
System.out.println(e);
}
}
public ArrayList getNames()
{
ArrayList list = new ArrayList();
list.add("ArrayList element 1");
list.add("ArrayList element 2");
list.add("ArrayList element 3");
list.add("ArrayList element 4");
return list;
}
public static void main(String[] args)
{
Example t = new Example(args[0]);
}
}
| apache-2.0 |
jamiepg1/jetty.project | jetty-util/src/test/java/org/eclipse/jetty/util/ArrayQueueTest.java | 4854 | // ========================================================================
// Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ArrayQueueTest
{
@Test
public void testWrap() throws Exception
{
ArrayQueue<String> queue = new ArrayQueue<String>(3,3);
assertEquals(0,queue.size());
for (int i=0;i<10;i++)
{
queue.offer("one");
assertEquals(1,queue.size());
queue.offer("two");
assertEquals(2,queue.size());
queue.offer("three");
assertEquals(3,queue.size());
assertEquals("one",queue.get(0));
assertEquals("two",queue.get(1));
assertEquals("three",queue.get(2));
assertEquals("[one, two, three]",queue.toString());
assertEquals("two",queue.remove(1));
assertEquals(2,queue.size());
assertEquals("one",queue.remove());
assertEquals(1,queue.size());
assertEquals("three",queue.poll());
assertEquals(0,queue.size());
assertEquals(null,queue.poll());
queue.offer("xxx");
queue.offer("xxx");
assertEquals(2,queue.size());
assertEquals("xxx",queue.poll());
assertEquals("xxx",queue.poll());
assertEquals(0,queue.size());
}
}
@Test
public void testRemove() throws Exception
{
ArrayQueue<String> queue = new ArrayQueue<String>(3,3);
queue.add("0");
queue.add("x");
for (int i=1;i<100;i++)
{
queue.add(""+i);
queue.add("x");
queue.remove(queue.size()-3);
queue.set(queue.size()-3,queue.get(queue.size()-3)+"!");
}
for (int i=0;i<99;i++)
assertEquals(i+"!",queue.get(i));
}
@Test
public void testGrow() throws Exception
{
ArrayQueue<String> queue = new ArrayQueue<String>(3,5);
assertEquals(3,queue.getCapacity());
queue.add("0");
queue.add("a");
queue.add("b");
assertEquals(3,queue.getCapacity());
queue.add("c");
assertEquals(8,queue.getCapacity());
for (int i=0;i<4;i++)
queue.add(""+('d'+i));
assertEquals(8,queue.getCapacity());
for (int i=0;i<4;i++)
queue.poll();
assertEquals(8,queue.getCapacity());
for (int i=0;i<4;i++)
queue.add(""+('d'+i));
assertEquals(8,queue.getCapacity());
for (int i=0;i<4;i++)
queue.poll();
assertEquals(8,queue.getCapacity());
for (int i=0;i<4;i++)
queue.add(""+('d'+i));
assertEquals(8,queue.getCapacity());
queue.add("z");
assertEquals(13,queue.getCapacity());
queue.clear();
assertEquals(13,queue.getCapacity());
for (int i=0;i<12;i++)
queue.add(""+('a'+i));
assertEquals(13,queue.getCapacity());
queue.clear();
assertEquals(13,queue.getCapacity());
for (int i=0;i<12;i++)
queue.add(""+('a'+i));
assertEquals(13,queue.getCapacity());
}
@Test
public void testFullEmpty() throws Exception
{
ArrayQueue<String> queue = new ArrayQueue<String>(2);
assertTrue(queue.offer("one"));
assertTrue(queue.offer("two"));
assertFalse(queue.offer("three"));
try
{
queue.add("four");
assertTrue(false);
}
catch(Exception e)
{
}
assertEquals("one",queue.peek());
assertEquals("one",queue.remove());
assertEquals("two",queue.remove());
try
{
assertEquals("three",queue.remove());
assertTrue(false);
}
catch(Exception e)
{
}
assertEquals(null,queue.poll());
}
}
| apache-2.0 |
jeorme/OG-Platform | projects/OG-Analytics/src/test/java/com/opengamma/analytics/financial/interestrate/future/provider/STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethodTest.java | 15407 | /**
* Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.interestrate.future.provider;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Map.Entry;
import org.testng.annotations.Test;
import org.threeten.bp.ZonedDateTime;
import com.opengamma.analytics.financial.datasets.CalendarTarget;
import com.opengamma.analytics.financial.instrument.future.InterestRateFutureOptionMarginSecurityDefinition;
import com.opengamma.analytics.financial.instrument.future.InterestRateFutureSecurityDefinition;
import com.opengamma.analytics.financial.instrument.index.IborIndex;
import com.opengamma.analytics.financial.instrument.index.IndexIborMaster;
import com.opengamma.analytics.financial.interestrate.future.derivative.InterestRateFutureOptionMarginSecurity;
import com.opengamma.analytics.financial.interestrate.sensitivity.PresentValueBlackSTIRFuturesCubeSensitivity;
import com.opengamma.analytics.financial.model.option.pricing.analytic.formula.BlackFunctionData;
import com.opengamma.analytics.financial.model.option.pricing.analytic.formula.BlackPriceFunction;
import com.opengamma.analytics.financial.model.option.pricing.analytic.formula.EuropeanVanillaOption;
import com.opengamma.analytics.financial.model.volatility.BlackFormulaRepository;
import com.opengamma.analytics.financial.provider.description.MulticurveProviderDiscountDataSets;
import com.opengamma.analytics.financial.provider.description.StandardDataSetsBlack;
import com.opengamma.analytics.financial.provider.description.interestrate.BlackSTIRFuturesExpLogMoneynessProvider;
import com.opengamma.analytics.financial.provider.description.interestrate.MulticurveProviderDiscount;
import com.opengamma.analytics.math.surface.InterpolatedDoublesSurface;
import com.opengamma.financial.convention.calendar.Calendar;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.time.DateUtils;
import com.opengamma.util.tuple.Triple;
/**
* Test.
*/
@Test(groups = TestGroup.UNIT)
public class STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethodTest {
/** Option on STIR futures */
private static final IndexIborMaster MASTER_IBOR_INDEX = IndexIborMaster.getInstance();
private static final IborIndex EURIBOR3M = MASTER_IBOR_INDEX.getIndex("EURIBOR3M");
private static final ZonedDateTime LAST_TRADE_DATE = DateUtils.getUTCDate(2014, 12, 15);
private static final double NOTIONAL = 1000000.0; // 1m
private static final double FUTURE_FACTOR = 0.25;
private static final String NAME = "ERZ4";
private static final Calendar TARGET = new CalendarTarget("TARGET");
private static final InterestRateFutureSecurityDefinition ERZ4_DEFINITION =
new InterestRateFutureSecurityDefinition(LAST_TRADE_DATE, EURIBOR3M, NOTIONAL, FUTURE_FACTOR, NAME, TARGET);
private static final ZonedDateTime EXPIRY_DATE = DateUtils.getUTCDate(2014, 11, 17);
private static final double STRIKE_09825 = 0.9825;
private static final boolean IS_CALL = true;
private static final InterestRateFutureOptionMarginSecurityDefinition CALL_ERZ4_09825_DEFINITION =
new InterestRateFutureOptionMarginSecurityDefinition(ERZ4_DEFINITION, EXPIRY_DATE, STRIKE_09825, IS_CALL);
private static final InterestRateFutureOptionMarginSecurityDefinition PUT_ERZ4_09825_DEFINITION =
new InterestRateFutureOptionMarginSecurityDefinition(ERZ4_DEFINITION, EXPIRY_DATE, STRIKE_09825, !IS_CALL);
/** Black surface expiry/log-moneyness */
final private static InterpolatedDoublesSurface BLACK_SURFACE_LOGMONEY = StandardDataSetsBlack.blackSurfaceExpiryLogMoneyness();
/** EUR curves */
final private static MulticurveProviderDiscount MULTICURVE = MulticurveProviderDiscountDataSets.createMulticurveEUR();
final private static BlackSTIRFuturesExpLogMoneynessProvider MULTICURVE_BLACK =
new BlackSTIRFuturesExpLogMoneynessProvider(MULTICURVE, BLACK_SURFACE_LOGMONEY, EURIBOR3M);
private static final ZonedDateTime REFERENCE_DATE = DateUtils.getUTCDate(2014, 4, 10);
private static final InterestRateFutureOptionMarginSecurity CALL_ERZ4_09825 =
CALL_ERZ4_09825_DEFINITION.toDerivative(REFERENCE_DATE);
private static final InterestRateFutureOptionMarginSecurity PUT_ERZ4_09825 =
PUT_ERZ4_09825_DEFINITION.toDerivative(REFERENCE_DATE);
/** Methods and calculators */
private static final InterestRateFutureSecurityDiscountingMethod METHOD_FUTURE = InterestRateFutureSecurityDiscountingMethod.getInstance();
private static final InterestRateFutureOptionMarginSecurityBlackSTIRFuturesMethod METHOD_OPT =
InterestRateFutureOptionMarginSecurityBlackSTIRFuturesMethod.getInstance();
private static final BlackPriceFunction BLACK_FUNCTION = new BlackPriceFunction();
/** Tolerances */
private static final double TOLERANCE_RATE = 1.0E-10;
private static final double TOLERANCE_DELTA = 1.0E-8;
public void impliedVolatility() {
final double priceFutures = METHOD_FUTURE.price(CALL_ERZ4_09825.getUnderlyingFuture(), MULTICURVE);
final double rateFutures = 1.0d - priceFutures;
final double rateStrike = 1.0d - STRIKE_09825;
final double logmoney = Math.log(rateStrike / rateFutures);
final double expiry = CALL_ERZ4_09825.getExpirationTime();
final double ivExpected = BLACK_SURFACE_LOGMONEY.getZValue(expiry, logmoney);
final double ivComputed = METHOD_OPT.impliedVolatility(CALL_ERZ4_09825, MULTICURVE_BLACK);
assertEquals("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: impliedVolatility", ivExpected, ivComputed, TOLERANCE_RATE);
}
public void futurePrice() {
final double priceExpected = METHOD_FUTURE.price(CALL_ERZ4_09825.getUnderlyingFuture(), MULTICURVE);
final double priceComputed = METHOD_OPT.underlyingFuturesPrice(CALL_ERZ4_09825, MULTICURVE_BLACK);
final double priceComputed2 = METHOD_OPT.underlyingFuturesPrice(CALL_ERZ4_09825, MULTICURVE);
assertEquals("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: underlying futures price", priceExpected, priceComputed, TOLERANCE_RATE);
assertEquals("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: underlying futures price", priceExpected, priceComputed2, TOLERANCE_RATE);
}
public void priceFromFuturesPrice() {
final double priceFutures = 0.9875;
final double rateFutures = 1.0d - priceFutures;
final double rateStrike = 1.0d - STRIKE_09825;
final EuropeanVanillaOption option = new EuropeanVanillaOption(rateStrike, CALL_ERZ4_09825.getExpirationTime(), !CALL_ERZ4_09825.isCall());
final double logmoney = Math.log(rateStrike / rateFutures);
final double expiry = CALL_ERZ4_09825.getExpirationTime();
final double volatility = BLACK_SURFACE_LOGMONEY.getZValue(expiry, logmoney);
final BlackFunctionData dataBlack = new BlackFunctionData(rateFutures, 1.0, volatility);
final double priceExpected = BLACK_FUNCTION.getPriceFunction(option).evaluate(dataBlack);
final double priceComputed = METHOD_OPT.price(CALL_ERZ4_09825, MULTICURVE_BLACK, priceFutures);
assertEquals("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: underlying futures price", priceExpected, priceComputed, TOLERANCE_RATE);
}
public void priceFromCurves() {
final double priceFutures = METHOD_FUTURE.price(CALL_ERZ4_09825.getUnderlyingFuture(), MULTICURVE);
final double priceExpected = METHOD_OPT.price(CALL_ERZ4_09825, MULTICURVE_BLACK, priceFutures);
final double priceComputed = METHOD_OPT.price(CALL_ERZ4_09825, MULTICURVE_BLACK);
assertEquals("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: price", priceExpected, priceComputed, TOLERANCE_RATE);
}
public void putCallParity() {
final double priceFutures = METHOD_FUTURE.price(CALL_ERZ4_09825.getUnderlyingFuture(), MULTICURVE);
final double priceCallComputed = METHOD_OPT.price(CALL_ERZ4_09825, MULTICURVE_BLACK);
final double pricePutComputed = METHOD_OPT.price(PUT_ERZ4_09825, MULTICURVE_BLACK);
assertEquals("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: put call parity price", priceCallComputed - pricePutComputed,
priceFutures - STRIKE_09825, TOLERANCE_RATE);
}
public void priceBlackSensitivity() {
final double priceFutures = METHOD_FUTURE.price(CALL_ERZ4_09825.getUnderlyingFuture(), MULTICURVE);
final double rateFutures = 1.0d - priceFutures;
final double rateStrike = 1.0d - STRIKE_09825;
final EuropeanVanillaOption option = new EuropeanVanillaOption(rateStrike,
CALL_ERZ4_09825.getExpirationTime(), !CALL_ERZ4_09825.isCall());
final double logmoney = Math.log(rateStrike / rateFutures);
final double expiry = CALL_ERZ4_09825.getExpirationTime();
final double volatility = BLACK_SURFACE_LOGMONEY.getZValue(expiry, logmoney);
final BlackFunctionData dataBlack = new BlackFunctionData(rateFutures, 1.0, volatility);
final double[] priceAD = BLACK_FUNCTION.getPriceAdjoint(option, dataBlack);
final double vega = priceAD[2];
final PresentValueBlackSTIRFuturesCubeSensitivity vegaComputed =
METHOD_OPT.priceBlackSensitivity(CALL_ERZ4_09825, MULTICURVE_BLACK);
assertEquals("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: Black parameters sensitivity",
vega, vegaComputed.getSensitivity().toSingleValue(), TOLERANCE_DELTA);
assertEquals("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: Black parameters sensitivity",
1, vegaComputed.getSensitivity().getMap().size());
final Entry<Triple<Double, Double, Double>, Double> point =
vegaComputed.getSensitivity().getMap().entrySet().iterator().next();
assertEquals("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: Black parameters sensitivity",
CALL_ERZ4_09825.getExpirationTime(), point.getKey().getFirst(), TOLERANCE_RATE);
assertEquals("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: Black parameters sensitivity",
CALL_ERZ4_09825.getUnderlyingFuture().getTradingLastTime() - CALL_ERZ4_09825.getExpirationTime(),
point.getKey().getSecond(), TOLERANCE_RATE);
assertEquals("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: Black parameters sensitivity",
CALL_ERZ4_09825.getStrike(), point.getKey().getThird(), TOLERANCE_RATE);
}
public void theoreticalDelta() {
final double priceFutures = METHOD_FUTURE.price(CALL_ERZ4_09825.getUnderlyingFuture(), MULTICURVE);
final double rateFutures = 1.0d - priceFutures;
final double rateStrike = 1.0d - STRIKE_09825;
final EuropeanVanillaOption option = new EuropeanVanillaOption(rateStrike, CALL_ERZ4_09825.getExpirationTime(), !CALL_ERZ4_09825.isCall());
final double logmoney = Math.log(rateStrike / rateFutures);
final double expiry = CALL_ERZ4_09825.getExpirationTime();
final double volatility = BLACK_SURFACE_LOGMONEY.getZValue(expiry, logmoney);
final BlackFunctionData dataBlack = new BlackFunctionData(rateFutures, 1.0, volatility);
final double[] priceAD = BLACK_FUNCTION.getPriceAdjoint(option, dataBlack);
final double deltaCallExpected = -priceAD[1];
final double deltaCallComputed = METHOD_OPT.deltaUnderlyingPrice(CALL_ERZ4_09825, MULTICURVE_BLACK);
assertEquals("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: delta", deltaCallExpected, deltaCallComputed, TOLERANCE_DELTA);
assertTrue("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: delta", (0.0d < deltaCallComputed) && (deltaCallComputed < 1.0d));
final double deltaPutComputed = METHOD_OPT.deltaUnderlyingPrice(PUT_ERZ4_09825, MULTICURVE_BLACK);
assertEquals("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: delta", deltaCallExpected - 1.0d, deltaPutComputed, TOLERANCE_DELTA);
}
public void theoreticalGamma() {
final double priceFutures = METHOD_FUTURE.price(CALL_ERZ4_09825.getUnderlyingFuture(), MULTICURVE);
final double rateFutures = 1.0d - priceFutures;
final double rateStrike = 1.0d - STRIKE_09825;
final EuropeanVanillaOption option = new EuropeanVanillaOption(rateStrike, CALL_ERZ4_09825.getExpirationTime(), !CALL_ERZ4_09825.isCall());
final double logmoney = Math.log(rateStrike / rateFutures);
final double expiry = CALL_ERZ4_09825.getExpirationTime();
final double volatility = BLACK_SURFACE_LOGMONEY.getZValue(expiry, logmoney);
final BlackFunctionData dataBlack = new BlackFunctionData(rateFutures, 1.0, volatility);
final double[] firstDerivs = new double[3];
final double[][] secondDerivs = new double[3][3];
BLACK_FUNCTION.getPriceAdjoint2(option, dataBlack, firstDerivs, secondDerivs);
final double gammaCallExpected = secondDerivs[0][0];
final double gammaCallComputed = METHOD_OPT.gammaUnderlyingPrice(CALL_ERZ4_09825, MULTICURVE_BLACK);
assertEquals("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: gamma", gammaCallExpected, gammaCallComputed, TOLERANCE_DELTA);
assertTrue("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: gamma", (0.0d < gammaCallComputed));
}
public void theoreticalVega() {
final double priceFutures = METHOD_FUTURE.price(CALL_ERZ4_09825.getUnderlyingFuture(), MULTICURVE);
final double rateFutures = 1.0d - priceFutures;
final double rateStrike = 1.0d - STRIKE_09825;
final EuropeanVanillaOption option = new EuropeanVanillaOption(rateStrike, CALL_ERZ4_09825.getExpirationTime(), !CALL_ERZ4_09825.isCall());
final double logmoney = Math.log(rateStrike / rateFutures);
final double expiry = CALL_ERZ4_09825.getExpirationTime();
final double volatility = BLACK_SURFACE_LOGMONEY.getZValue(expiry, logmoney);
final BlackFunctionData dataBlack = new BlackFunctionData(rateFutures, 1.0, volatility);
final double[] priceAD = BLACK_FUNCTION.getPriceAdjoint(option, dataBlack);
final double vegaCallExpected = priceAD[2];
final double vegaCallComputed = METHOD_OPT.vegaUnderlyingPrice(CALL_ERZ4_09825, MULTICURVE_BLACK);
assertEquals("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: vega", vegaCallExpected, vegaCallComputed, TOLERANCE_DELTA);
assertTrue("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: vega", 0.0d < vegaCallComputed);
}
public void theoreticalTheta() {
final double priceFutures = METHOD_FUTURE.price(CALL_ERZ4_09825.getUnderlyingFuture(), MULTICURVE);
final double rateFutures = 1.0d - priceFutures;
final double rateStrike = 1.0d - STRIKE_09825;
final double logmoney = Math.log(rateStrike / rateFutures);
final double expiry = CALL_ERZ4_09825.getExpirationTime();
final double volatility = BLACK_SURFACE_LOGMONEY.getZValue(expiry, logmoney);
final double rate = -Math.log(MULTICURVE.getMulticurveProvider().getDiscountFactor(CALL_ERZ4_09825.getCurrency(), CALL_ERZ4_09825.getExpirationTime())) / CALL_ERZ4_09825.getExpirationTime();
final double thetaCallExpected = BlackFormulaRepository.theta(rateFutures, rateStrike, CALL_ERZ4_09825.getExpirationTime(), volatility, !CALL_ERZ4_09825.isCall(), rate);
final double thetaCallComputed = METHOD_OPT.thetaUnderlyingPrice(CALL_ERZ4_09825, MULTICURVE_BLACK);
assertEquals("STIRFuturesOptionMarginSecurityBlackExpLogMoneynessMethod: theta", thetaCallExpected, thetaCallComputed, TOLERANCE_DELTA);
}
}
| apache-2.0 |
feiqitian/elasticsearch | src/test/java/org/elasticsearch/index/engine/InternalEngineSettingsTest.java | 6448 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index.engine;
import org.apache.lucene.index.LiveIndexWriterConfig;
import org.elasticsearch.ElasticsearchIllegalArgumentException;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.test.ElasticsearchSingleNodeTest;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
public class InternalEngineSettingsTest extends ElasticsearchSingleNodeTest {
public void testSettingsUpdate() {
final IndexService service = createIndex("foo");
// INDEX_COMPOUND_ON_FLUSH
InternalEngine engine = ((InternalEngine)engine(service));
assertThat(engine.getCurrentIndexWriterConfig().getUseCompoundFile(), is(true));
client().admin().indices().prepareUpdateSettings("foo").setSettings(ImmutableSettings.builder().put(EngineConfig.INDEX_COMPOUND_ON_FLUSH, false).build()).get();
assertThat(engine.getCurrentIndexWriterConfig().getUseCompoundFile(), is(false));
client().admin().indices().prepareUpdateSettings("foo").setSettings(ImmutableSettings.builder().put(EngineConfig.INDEX_COMPOUND_ON_FLUSH, true).build()).get();
assertThat(engine.getCurrentIndexWriterConfig().getUseCompoundFile(), is(true));
// VERSION MAP SIZE
long indexBufferSize = engine.config().getIndexingBufferSize().bytes();
long versionMapSize = engine.config().getVersionMapSize().bytes();
assertThat(versionMapSize, equalTo((long) (indexBufferSize * 0.25)));
final int iters = between(1, 20);
for (int i = 0; i < iters; i++) {
boolean compoundOnFlush = randomBoolean();
long gcDeletes = Math.max(0, randomLong());
boolean versionMapAsPercent = randomBoolean();
double versionMapPercent = randomIntBetween(0, 100);
long versionMapSizeInMB = randomIntBetween(10, 20);
String versionMapString = versionMapAsPercent ? versionMapPercent + "%" : versionMapSizeInMB + "mb";
Settings build = ImmutableSettings.builder()
.put(EngineConfig.INDEX_COMPOUND_ON_FLUSH, compoundOnFlush)
.put(EngineConfig.INDEX_GC_DELETES_SETTING, gcDeletes)
.put(EngineConfig.INDEX_VERSION_MAP_SIZE, versionMapString)
.build();
client().admin().indices().prepareUpdateSettings("foo").setSettings(build).get();
LiveIndexWriterConfig currentIndexWriterConfig = engine.getCurrentIndexWriterConfig();
assertEquals(engine.config().isCompoundOnFlush(), compoundOnFlush);
assertEquals(currentIndexWriterConfig.getUseCompoundFile(), compoundOnFlush);
assertEquals(engine.config().getGcDeletesInMillis(), gcDeletes);
assertEquals(engine.getGcDeletesInMillis(), gcDeletes);
indexBufferSize = engine.config().getIndexingBufferSize().bytes();
versionMapSize = engine.config().getVersionMapSize().bytes();
if (versionMapAsPercent) {
assertThat(versionMapSize, equalTo((long) (indexBufferSize * (versionMapPercent / 100))));
} else {
assertThat(versionMapSize, equalTo(1024 * 1024 * versionMapSizeInMB));
}
}
Settings settings = ImmutableSettings.builder()
.put(EngineConfig.INDEX_GC_DELETES_SETTING, 1000)
.build();
client().admin().indices().prepareUpdateSettings("foo").setSettings(settings).get();
assertEquals(engine.getGcDeletesInMillis(), 1000);
assertTrue(engine.config().isEnableGcDeletes());
settings = ImmutableSettings.builder()
.put(EngineConfig.INDEX_GC_DELETES_SETTING, "0ms")
.build();
client().admin().indices().prepareUpdateSettings("foo").setSettings(settings).get();
assertEquals(engine.getGcDeletesInMillis(), 0);
assertTrue(engine.config().isEnableGcDeletes());
settings = ImmutableSettings.builder()
.put(EngineConfig.INDEX_GC_DELETES_SETTING, 1000)
.build();
client().admin().indices().prepareUpdateSettings("foo").setSettings(settings).get();
assertEquals(engine.getGcDeletesInMillis(), 1000);
assertTrue(engine.config().isEnableGcDeletes());
settings = ImmutableSettings.builder()
.put(EngineConfig.INDEX_VERSION_MAP_SIZE, "sdfasfd")
.build();
try {
client().admin().indices().prepareUpdateSettings("foo").setSettings(settings).get();
fail("settings update didn't fail, but should have");
} catch (ElasticsearchIllegalArgumentException e) {
// good
}
settings = ImmutableSettings.builder()
.put(EngineConfig.INDEX_VERSION_MAP_SIZE, "-12%")
.build();
try {
client().admin().indices().prepareUpdateSettings("foo").setSettings(settings).get();
fail("settings update didn't fail, but should have");
} catch (ElasticsearchIllegalArgumentException e) {
// good
}
settings = ImmutableSettings.builder()
.put(EngineConfig.INDEX_VERSION_MAP_SIZE, "130%")
.build();
try {
client().admin().indices().prepareUpdateSettings("foo").setSettings(settings).get();
fail("settings update didn't fail, but should have");
} catch (ElasticsearchIllegalArgumentException e) {
// good
}
}
}
| apache-2.0 |
jameswnl/manageiq | lib/acts_as_ar_model.rb | 5047 | class ActsAsArModel
include Vmdb::Logging
def self.connection
ActiveRecord::Base.connection
end
def connection
self.class.connection
end
def self.table_name
nil
end
def self.pluralize_table_names
false
end
def self.base_class
superclass == ActsAsArModel ? self : superclass.base_class
end
class << self; alias_method :base_model, :base_class; end
#
# Column methods
#
module FakeAttributeStore
extend ActiveSupport::Concern
# When ActiveRecord::Attributes gets [partially] extracted into
# ActiveModel (hopefully in 5.1), this should become redundant. For
# now, we'll just fake out the portion of the API we need.
#
# Based very heavily on matching methods in current ActiveRecord.
module ClassMethods
def load_schema
load_schema! if @attribute_types.nil?
end
def load_schema!
# no-op
end
def reload_schema_from_cache
@attribute_types = nil
end
def attribute_types
@attribute_types ||= Hash.new(ActiveModel::Type::Value.new)
end
def attribute_names
load_schema
attribute_types.keys
end
def has_attribute?(name)
load_schema
attribute_types.key?(name.to_s)
end
def type_for_attribute(attr_name)
load_schema
attribute_types[attr_name]
end
end
end
module AttributeBag
def initialize
@attributes = {}
end
def attributes=(values)
values.each do |attr, value|
send("#{attr}=", value)
end
end
def attributes
@attributes.dup
end
def [](attr)
@attributes[attr.to_s]
end
alias_method :read_attribute, :[]
def []=(attr, value)
@attributes[attr.to_s] = value
end
alias_method :write_attribute, :[]=
end
def self.set_columns_hash(hash)
hash[:id] ||= :integer
hash.each do |attribute, type|
virtual_attribute attribute, type
define_method(attribute) do
read_attribute(attribute)
end
define_method("#{attribute}=") do |val|
write_attribute(attribute, val)
end
end
end
include FakeAttributeStore
include ActiveRecord::VirtualAttributes::VirtualFields
include AttributeBag
def self.instances_are_derived?
true
end
def self.reflect_on_association(name)
virtual_reflection(name)
end
def initialize(values = {})
super()
self.attributes = values
end
#
# Reflection methods
#
def self.reflections
@reflections ||= {}
end
#
# Find routines
#
# This method is called by QueryRelation upon executing the query.
# Since it will receive non-legacy search options, we need to convert
# them to handle the legacy find.
def self.search(mode, options = {})
find(mode, to_legacy_options(options))
end
private_class_method :search
def self.to_legacy_options(options)
{
:conditions => options[:where],
:include => options[:includes],
:limit => options[:limit],
:order => options[:order],
:offset => options[:offset],
:select => options[:select],
:group => options[:group],
}.delete_blanks
end
private_class_method :to_legacy_options
def self.all(*args)
require 'query_relation'
QueryRelation.new(self, *args)
end
def self.first(*args)
find(:first, *args)
end
def self.last(*args)
find(:last, *args)
end
def self.count(*args)
all(*args).count
end
def self.find_by_id(*id)
options = id.extract_options!
options[:conditions] = {:id => id.first}
first(options)
end
def self.find_all_by_id(*ids)
options = ids.extract_options!
options[:conditions] = {:id => ids.flatten}
all(options)
end
#
# Methods pulled from ActiveRecord 2.3.8
#
# Returns the contents of the record as a nicely formatted string.
def inspect
attributes_as_nice_string = self.class.attribute_names.collect do |name|
"#{name}: #{attribute_for_inspect(name)}"
end.compact.join(", ")
"#<#{self.class} #{attributes_as_nice_string}>"
end
private
# Returns an <tt>#inspect</tt>-like string for the value of the
# attribute +attr_name+. String attributes are elided after 50
# characters, and Date and Time attributes are returned in the
# <tt>:db</tt> format. Other attributes return the value of
# <tt>#inspect</tt> without modification.
#
# person = Person.create!(:name => "David Heinemeier Hansson " * 3)
#
# person.attribute_for_inspect(:name)
# # => '"David Heinemeier Hansson David Heinemeier Hansson D..."'
#
# person.attribute_for_inspect(:created_at)
# # => '"2009-01-12 04:48:57"'
def attribute_for_inspect(attr_name)
value = self[attr_name]
if value.kind_of?(String) && value.length > 50
"#{value[0..50]}...".inspect
elsif value.kind_of?(Date) || value.kind_of?(Time)
%("#{value.to_s(:db)}")
else
value.inspect
end
end
end
| apache-2.0 |
tensorflow/tensorflow | tensorflow/core/kernels/ragged_tensor_to_sparse_kernel.cc | 9956 | /* Copyright 2018 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.
==============================================================================*/
#include <limits>
#include <memory>
#include <string>
#include <vector>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/platform/errors.h"
namespace tensorflow {
using errors::InvalidArgument;
template <typename SPLITS_TYPE>
class RaggedTensorToSparseOp : public OpKernel {
public:
using OpKernel::OpKernel;
using ConstFlatSplits = typename TTypes<SPLITS_TYPE>::ConstFlat;
void Compute(OpKernelContext* context) override {
// Read the `rt_nested_splits` input & convert to Eigen tensors.
OpInputList rt_nested_splits_in;
OP_REQUIRES_OK(
context, context->input_list("rt_nested_splits", &rt_nested_splits_in));
const int rt_nested_splits_len = rt_nested_splits_in.size();
OP_REQUIRES(context, rt_nested_splits_len > 0,
errors::InvalidArgument("rt_nested_splits must be non empty"));
std::vector<ConstFlatSplits> rt_nested_splits;
rt_nested_splits.reserve(rt_nested_splits_len);
for (int i = 0; i < rt_nested_splits_len; ++i) {
rt_nested_splits.push_back(rt_nested_splits_in[i].flat<SPLITS_TYPE>());
}
// Read the `rt_dense_values` input.
const Tensor& rt_dense_values_in = context->input(rt_nested_splits_len);
OP_REQUIRES_OK(context,
ValidateInputs(rt_nested_splits, rt_dense_values_in));
// Assemble each value in `sparse_indices` using three parts:
// - `index_prefix` is the index in dimensions up through the last ragged
// dimension.
// - `index_middle` is the index in the last ragged dimension.
// - `index_suffix` is the index in the dense value dimensions.
std::vector<int64_t> index_prefix(rt_nested_splits_len);
std::vector<std::vector<int64_t>> index_suffixes =
MakeIndexSuffixes(rt_dense_values_in.shape());
// Allocate the `sparse_indices` output tensor.
const int64_t nvals =
(rt_nested_splits.back()(rt_nested_splits.back().size() - 1) *
index_suffixes.size());
const int64_t indices_len =
rt_nested_splits_len + rt_dense_values_in.dims();
Tensor* sparse_indices_out = nullptr;
OP_REQUIRES_OK(
context, context->allocate_output(0, TensorShape({nvals, indices_len}),
&sparse_indices_out));
auto sparse_indices = sparse_indices_out->tensor<int64_t, 2>();
// pos[i] is the current position in rt_nested_splits[i]. final_pos is a
// reference to make it easier to refer to pos[-1].
std::vector<int64_t> pos(rt_nested_splits_len);
int64_t& final_pos = pos[rt_nested_splits_len - 1];
// Each iteration through the loop, we increment pos[-1], and add indices
// for all the values corresponding to
// rt_nested_splits[-1][pos[-1]:pos[-1]+1].
int next_index = 0;
int max_final_pos = rt_nested_splits.back().size() - 1;
for (; final_pos < max_final_pos; ++final_pos) {
// Update `pos` to skip over completed elements (i.e., elements where
// we have already generated indices for all contained values).
for (int dim = rt_nested_splits_len - 2; dim >= 0; --dim) {
while (IsCompleted(pos, dim, rt_nested_splits)) {
pos[dim] += 1;
}
}
// Update index_prefix.
for (int dim = 0; dim < index_prefix.size(); ++dim) {
int start = dim > 0 ? rt_nested_splits[dim - 1](pos[dim - 1]) : 0;
index_prefix[dim] = pos[dim] - start;
}
// Get length of the final-ragged-dimension slice.
const auto& final_splits = rt_nested_splits[rt_nested_splits_len - 1];
int64_t slice_len = final_splits(final_pos + 1) - final_splits(final_pos);
// Add sparse_indices for this slice.
for (int64_t i = 0; i < slice_len; ++i) {
for (const auto& index_suffix : index_suffixes) {
int dim = 0;
for (int64_t index : index_prefix) { // index_prefix
sparse_indices(next_index, dim++) = index;
}
sparse_indices(next_index, dim++) = i; // index_middle
for (int64_t index : index_suffix) { // index_suffix
sparse_indices(next_index, dim++) = index;
}
DCHECK_EQ(dim, indices_len);
++next_index;
}
}
}
DCHECK_EQ(next_index, nvals);
// Output the `sparse_values` Tensor.
if (rt_dense_values_in.dims() == 1) {
context->set_output(1, rt_dense_values_in);
} else {
Tensor sparse_values_out(rt_dense_values_in.dtype());
bool shapes_match = sparse_values_out.CopyFrom(
rt_dense_values_in, {rt_dense_values_in.NumElements()});
DCHECK(shapes_match);
context->set_output(1, sparse_values_out);
}
// Output the `sparse_dense_shape` Tensor.
int64_t ndims = rt_nested_splits_len + rt_dense_values_in.dims();
Tensor* sparse_dense_shape_out = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(2, TensorShape({ndims}),
&sparse_dense_shape_out));
auto sparse_dense_shape = sparse_dense_shape_out->vec<int64_t>();
sparse_dense_shape(0) = rt_nested_splits_in[0].dim_size(0) - 1;
for (int dim = 0; dim < rt_nested_splits_len; ++dim) {
const auto& splits = rt_nested_splits[dim];
SPLITS_TYPE max_width = 0;
for (int i = 1; i < splits.size(); ++i) {
max_width = std::max(max_width, splits(i) - splits(i - 1));
}
sparse_dense_shape(dim + 1) = max_width;
}
for (int dim = 1; dim < rt_dense_values_in.dims(); ++dim) {
sparse_dense_shape(dim + rt_nested_splits_len) =
rt_dense_values_in.dim_size(dim);
}
}
private:
// Validate `rt_nested_splits` to ensure we don't get any segfaults.
static ::tensorflow::Status ValidateInputs(
std::vector<ConstFlatSplits> rt_nested_splits,
const Tensor& rt_dense_values_in) {
for (int i = 0; i < rt_nested_splits.size(); ++i) {
if (rt_nested_splits[i].size() == 0) {
return InvalidArgument("ragged splits may not be empty.");
}
if (rt_nested_splits[i](0) != 0) {
return InvalidArgument("First value of ragged splits must be 0.");
}
for (int j = 1; j < rt_nested_splits[i].size(); ++j) {
if (rt_nested_splits[i](j) < rt_nested_splits[i](j - 1)) {
return InvalidArgument(
"Ragged splits should be non decreasing, but we got ",
rt_nested_splits[i](j - 1), " followed by ",
rt_nested_splits[i](j));
}
}
if (i > 0) {
SPLITS_TYPE last_split =
rt_nested_splits[i - 1](rt_nested_splits[i - 1].size() - 1);
if (rt_nested_splits[i].size() != last_split + 1) {
return InvalidArgument(
"Final value of ragged splits must match the length "
"the corresponding ragged values.");
}
}
}
if (rt_dense_values_in.dim_size(0) !=
rt_nested_splits.back()(rt_nested_splits.back().size() - 1)) {
return InvalidArgument(
"Final value of ragged splits must match the length "
"the corresponding ragged values.");
}
return ::tensorflow::Status::OK();
}
// Build a list of index suffixes that should be added for each ragged item,
// to encode the indices of dense values in that ragged item. This basically
// just gives a row-major enumeration of all indices in the given tensor
// shape, ignoring dim[0] (since that's the dimension that iterates over
// values, and we want index suffixes for a single value). Example:
// MakeIndexSuffixes(TensorShape({100, 3, 2})
// --> {{0, 0}, {0, 1}, {1, 0}, {1, 1}, {2, 0}, {2, 1}}
static std::vector<std::vector<int64_t>> MakeIndexSuffixes(
const TensorShape& values_shape) {
std::vector<std::vector<int64_t>> suffixes{{}};
for (int dim = 1; dim < values_shape.dims(); ++dim) {
std::vector<std::vector<int64_t>> new_suffixes;
for (const auto& suffix : suffixes) {
for (int i = 0; i < values_shape.dim_size(dim); ++i) {
new_suffixes.push_back(suffix);
new_suffixes.back().push_back(i);
}
}
suffixes.swap(new_suffixes);
}
return suffixes;
}
// Returns true if the ragged element at pos[dim] is "completed". A ragged
// element is completed if we have already generated indices for all of its
// values.
static bool IsCompleted(
const std::vector<int64_t>& pos, int dim,
const std::vector<ConstFlatSplits>& rt_nested_splits) {
int64_t current_child = pos[dim + 1];
int64_t limit_child = rt_nested_splits[dim](pos[dim] + 1);
return current_child >= limit_child;
}
};
REGISTER_KERNEL_BUILDER(Name("RaggedTensorToSparse")
.Device(DEVICE_CPU)
.TypeConstraint<int32>("Tsplits"),
RaggedTensorToSparseOp<int32>);
REGISTER_KERNEL_BUILDER(Name("RaggedTensorToSparse")
.Device(DEVICE_CPU)
.TypeConstraint<int64_t>("Tsplits"),
RaggedTensorToSparseOp<int64_t>);
} // namespace tensorflow
| apache-2.0 |
mdanielwork/intellij-community | plugins/properties/testSrc/com/intellij/lang/properties/PropertiesProjectViewTest.java | 6999 | /*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.lang.properties;
import com.intellij.ide.projectView.impl.AbstractProjectViewPSIPane;
import com.intellij.ide.projectView.impl.GroupByTypeComparator;
import com.intellij.lang.properties.projectView.ResourceBundleGrouper;
import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.openapi.application.PluginPathManager;
import com.intellij.projectView.TestProjectTreeStructure;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
import com.intellij.util.ui.tree.TreeUtil;
import java.util.ArrayList;
import java.util.List;
public class PropertiesProjectViewTest extends LightPlatformCodeInsightFixtureTestCase {
private TestProjectTreeStructure myStructure;
@Override
protected void setUp() throws Exception {
super.setUp();
myStructure = new TestProjectTreeStructure(getProject(), myFixture.getTestRootDisposable());
}
@Override
protected String getTestDataPath() {
return PluginPathManager.getPluginHomePath("properties") + "/testData/propertiesFile/projectView";
}
public void testBundle() {
myFixture.copyDirectoryToProject(getTestName(true), getTestName(true));
final AbstractProjectViewPSIPane pane = setupPane(true);
String structure = "-Project\n" +
" -PsiDirectory: src\n" +
" -PsiDirectory: bundle\n" +
" yyy.properties\n" +
" -Resource Bundle 'xxx'\n" +
" xxx.properties\n" +
" xxx_en.properties\n" +
" xxx_ru_RU.properties\n" +
" X.txt\n" +
" External Libraries\n";
PlatformTestUtil.assertTreeEqual(pane.getTree(), structure);
}
public void testStandAlone() {
myFixture.copyDirectoryToProject(getTestName(true), getTestName(true));
final AbstractProjectViewPSIPane pane = setupPane(true);
String structure = "-Project\n" +
" -PsiDirectory: src\n" +
" -PsiDirectory: standAlone\n" +
" a.properties\n" +
" xxx.properties\n" +
" xxx2.properties\n" +
" yyy.properties\n" +
" X.txt\n" +
" External Libraries\n";
PlatformTestUtil.assertTreeEqual(pane.getTree(), structure);
}
public void testSortByType() {
myFixture.copyDirectoryToProject(getTestName(true), getTestName(true));
AbstractProjectViewPSIPane pane = setupPane(true);
String structure = "-Project\n" +
" -PsiDirectory: src\n" +
" -PsiDirectory: sortByType\n" +
" a.properties\n" +
" xxx2.properties\n" +
" yyy.properties\n" +
" -Resource Bundle 'xxx'\n" +
" xxx.properties\n" +
" xxx_en.properties\n" +
" X.txt\n" +
" External Libraries\n";
PlatformTestUtil.assertTreeEqual(pane.getTree(), structure);
pane = setupPane(false);
structure = "-Project\n" +
" -PsiDirectory: src\n" +
" -PsiDirectory: sortByType\n" +
" a.properties\n" +
" X.txt\n" +
" -Resource Bundle 'xxx'\n" +
" xxx.properties\n" +
" xxx_en.properties\n" +
" xxx2.properties\n" +
" yyy.properties\n" +
" External Libraries\n";
PlatformTestUtil.assertTreeEqual(pane.getTree(), structure);
}
public void testCustomBundle() {
myFixture.copyDirectoryToProject(getTestName(true), getTestName(true));
List<PropertiesFile> customBundleFiles = new ArrayList<>(2);
PropertiesReferenceManager.getInstance(getProject()).processAllPropertiesFiles((baseName, propertiesFile) -> {
customBundleFiles.add(propertiesFile);
return true;
});
ResourceBundleManager.getInstance(getProject()).combineToResourceBundle(customBundleFiles, "some");
final AbstractProjectViewPSIPane pane = setupPane(true);
String structure = "-Project\n" +
" -PsiDirectory: src\n" +
" -PsiDirectory: customBundle\n" +
" -PsiDirectory: dev\n" +
" some.dev.properties (custom RB: some)\n" +
" -PsiDirectory: prod\n" +
" some.prod.properties (custom RB: some)\n" +
" External Libraries\n";
PlatformTestUtil.assertTreeEqual(pane.getTree(), structure);
}
public void testFewBundles() {
myFixture.copyDirectoryToProject(getTestName(true), getTestName(true));
List<PropertiesFile> customBundleFiles = new ArrayList<>(2);
PropertiesReferenceManager.getInstance(getProject()).processAllPropertiesFiles((baseName, propertiesFile) -> {
if (baseName.contains("custom")) {
customBundleFiles.add(propertiesFile);
}
return true;
});
ResourceBundleManager.getInstance(getProject()).combineToResourceBundle(customBundleFiles, "custom");
final AbstractProjectViewPSIPane pane = setupPane(true);
String structure = "-Project\n" +
" -PsiDirectory: src\n" +
" -PsiDirectory: fewBundles\n" +
" -PsiDirectory: dev\n" +
" custom.prod.properties (custom RB: custom)\n" +
" custom.dev.properties (custom RB: custom)\n" +
" xxx.properties\n" +
" -Resource Bundle 'a'\n" +
" a.properties\n" +
" a_en.properties\n" +
" -Resource Bundle 'b'\n" +
" b.properties\n" +
" b_fr.properties\n" +
" External Libraries\n";
PlatformTestUtil.assertTreeEqual(pane.getTree(), structure);
}
private AbstractProjectViewPSIPane setupPane(final boolean sortByType) {
myStructure.setProviders(new ResourceBundleGrouper(getProject()));
final AbstractProjectViewPSIPane pane = myStructure.createPane();
pane.installComparator(new GroupByTypeComparator(sortByType));
PropertiesReferenceManager.getInstance(getProject()).processAllPropertiesFiles((baseName, propertiesFile) -> {
pane.select(propertiesFile, propertiesFile.getVirtualFile(), sortByType);
return true;
});
PlatformTestUtil.waitWhileBusy(pane.getTree());
TreeUtil.expandAll(pane.getTree());
return pane;
}
}
| apache-2.0 |
DEKHTIARJonathan/BilletterieUTC | badgingServer/Install/swigwin-3.0.7/Examples/test-suite/lua/friends_runme.lua | 614 | require("import") -- the import fn
import("friends") -- import lib into global
f=friends --alias
-- catching undefined variables
local env = _ENV -- Lua 5.2
if not env then env = getfenv () end -- Lua 5.1
setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
f.globalscope()
b1 = f.B(5)
a1 = f.A(10)
assert(f.get_val1(a1) == 10)
assert(f.get_val1(a1, 2) == 12)
assert(f.get_val2(a1) == 20)
assert(f.get_val3(a1) == 30)
assert(f.get_val1(100, 1, 2) == 100)
assert(f.mix(a1,b1) == 15);
d1 = f.D_i(7)
assert(f.get_val1(d1) == 7)
f.set(d1,9)
assert(f.get_val1(d1) == 9)
| apache-2.0 |
jerrinot/hazelcast | hazelcast/src/test/java/com/hazelcast/collection/impl/queue/QueueMigrationTest.java | 4455 | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.collection.impl.queue;
import com.hazelcast.collection.IQueue;
import com.hazelcast.collection.impl.queue.model.VersionedObject;
import com.hazelcast.collection.impl.queue.model.VersionedObjectComparator;
import com.hazelcast.config.Config;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.instance.impl.TestUtil;
import com.hazelcast.test.ChangeLoggingRule;
import com.hazelcast.test.HazelcastParallelParametersRunnerFactory;
import com.hazelcast.test.HazelcastParametrizedRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.assertEquals;
import static org.junit.runners.Parameterized.UseParametersRunnerFactory;
@RunWith(HazelcastParametrizedRunner.class)
@UseParametersRunnerFactory(HazelcastParallelParametersRunnerFactory.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class QueueMigrationTest extends HazelcastTestSupport {
@ClassRule
public static ChangeLoggingRule changeLoggingRule
= new ChangeLoggingRule("log4j2-debug-queue.xml");
private TestHazelcastInstanceFactory factory;
private HazelcastInstance ownerMember;
private String queueName;
@Parameterized.Parameters(name = "comparatorClassName: {0}")
public static Collection<Object> parameters() {
return Arrays.asList(new Object[]{null, VersionedObjectComparator.class.getName()});
}
@Parameterized.Parameter
public String comparatorClassName;
@Before
public void setup() {
Config config = smallInstanceConfig();
config.getQueueConfig("default")
.setPriorityComparatorClassName(comparatorClassName);
factory = createHazelcastInstanceFactory(3);
HazelcastInstance[] cluster = factory.newInstances(config);
ownerMember = cluster[1];
queueName = randomNameOwnedBy(ownerMember);
}
@Test
public void testMigration() {
testReplication(false);
}
@Test
public void testPromotion() {
testReplication(true);
}
private void testReplication(boolean terminateOwner) {
List<VersionedObject<Integer>> expectedItems = new LinkedList<>();
IQueue<Object> queue = getRandomInstance().getQueue(queueName);
for (int i = 0; i < 100; i++) {
queue.add(new VersionedObject<>(i, i));
expectedItems.add(new VersionedObject<>(i, i));
}
if (terminateOwner) {
TestUtil.terminateInstance(ownerMember);
} else {
ownerMember.shutdown();
}
queue = getRandomInstance().getQueue(queueName);
assertEquals(expectedItems.size(), queue.size());
getRandomInstance().shutdown();
queue = getRandomInstance().getQueue(queueName);
assertEquals(expectedItems.size(), queue.size());
@SuppressWarnings("unchecked")
VersionedObject<Integer>[] a = queue.toArray(new VersionedObject[0]);
List<VersionedObject<Integer>> actualItems = Arrays.asList(a);
assertEquals(expectedItems, actualItems);
}
private HazelcastInstance getRandomInstance() {
HazelcastInstance[] instances = factory.getAllHazelcastInstances().toArray(new HazelcastInstance[0]);
Random rnd = new Random();
return instances[rnd.nextInt(instances.length)];
}
}
| apache-2.0 |
gweidner/incubator-systemml | src/test/java/org/apache/sysml/test/integration/functions/ternary/CentralMomentWeightsTest.java | 5571 | /*
* 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.sysml.test.integration.functions.ternary;
import java.util.HashMap;
import org.junit.Test;
import org.apache.sysml.api.DMLScript;
import org.apache.sysml.api.DMLScript.RUNTIME_PLATFORM;
import org.apache.sysml.lops.LopProperties.ExecType;
import org.apache.sysml.runtime.matrix.data.MatrixValue.CellIndex;
import org.apache.sysml.test.integration.AutomatedTestBase;
import org.apache.sysml.test.integration.TestConfiguration;
import org.apache.sysml.test.utils.TestUtils;
/**
*
*/
public class CentralMomentWeightsTest extends AutomatedTestBase
{
private final static String TEST_NAME = "CentralMomentWeights";
private final static String TEST_DIR = "functions/ternary/";
private final static String TEST_CLASS_DIR = TEST_DIR + CentralMomentWeightsTest.class.getSimpleName() + "/";
private final static double eps = 1e-10;
private final static int rows = 1871;
private final static int maxVal = 7;
private final static double sparsity1 = 0.65;
private final static double sparsity2 = 0.05;
@Override
public void setUp()
{
TestUtils.clearAssertionInformation();
addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[] { "R" }) );
}
@Test
public void testCentralMoment2WeightsDenseCP()
{
runCentralMomentTest(2, false, ExecType.CP);
}
@Test
public void testCentralMoment3WeightsDenseCP()
{
runCentralMomentTest(3, false, ExecType.CP);
}
@Test
public void testCentralMoment4WeightsDenseCP()
{
runCentralMomentTest(4, false, ExecType.CP);
}
@Test
public void testCentralMoment2WeightsSparseCP()
{
runCentralMomentTest(2, true, ExecType.CP);
}
@Test
public void testCentralMoment3WeightsSparseCP()
{
runCentralMomentTest(3, true, ExecType.CP);
}
@Test
public void testCentralMoment4WeightsSparseCP()
{
runCentralMomentTest(4, true, ExecType.CP);
}
@Test
public void testCentralMoment2WeightsDenseMR()
{
runCentralMomentTest(2, false, ExecType.MR);
}
@Test
public void testCentralMoment3WeightsDenseMR()
{
runCentralMomentTest(3, false, ExecType.MR);
}
@Test
public void testCentralMoment4WeightsDenseMR()
{
runCentralMomentTest(4, false, ExecType.MR);
}
@Test
public void testCentralMoment2WeightsSparseMR()
{
runCentralMomentTest(2, true, ExecType.MR);
}
@Test
public void testCentralMoment3WeightsSparseMR()
{
runCentralMomentTest(3, true, ExecType.MR);
}
@Test
public void testCentralMoment4WeightsSparseMR()
{
runCentralMomentTest(4, true, ExecType.MR);
}
@Test
public void testCentralMoment2WeightsDenseSP()
{
runCentralMomentTest(2, false, ExecType.SPARK);
}
@Test
public void testCentralMoment3WeightsDenseSP()
{
runCentralMomentTest(3, false, ExecType.SPARK);
}
@Test
public void testCentralMoment4WeightsDenseSP()
{
runCentralMomentTest(4, false, ExecType.SPARK);
}
@Test
public void testCentralMoment2WeightsSparseSP()
{
runCentralMomentTest(2, true, ExecType.SPARK);
}
@Test
public void testCentralMoment3WeightsSparseSP()
{
runCentralMomentTest(3, true, ExecType.SPARK);
}
@Test
public void testCentralMoment4WeightsSparseSP()
{
runCentralMomentTest(4, true, ExecType.SPARK);
}
/**
*
* @param sparseM1
* @param sparseM2
* @param instType
*/
private void runCentralMomentTest( int order, boolean sparse, ExecType et)
{
boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;
RUNTIME_PLATFORM platformOld = setRuntimePlatform(et);
if(shouldSkipTest())
return;
try
{
TestConfiguration config = getTestConfiguration(TEST_NAME);
loadTestConfiguration(config);
String HOME = SCRIPT_DIR + TEST_DIR;
fullDMLScriptName = HOME + TEST_NAME + ".dml";
programArgs = new String[]{"-args", input("A"),
input("B"), Integer.toString(order), output("R")};
fullRScriptName = HOME + TEST_NAME + ".R";
rCmd = "Rscript" + " " + fullRScriptName + " " +
inputDir() + " " + order + " "+ expectedDir();
//generate actual dataset (always dense because values <=0 invalid)
double sparsitya = sparse ? sparsity2 : sparsity1;
double[][] A = getRandomMatrix(rows, 1, 1, maxVal, sparsitya, 7);
writeInputMatrixWithMTD("A", A, true);
double[][] B = getRandomMatrix(rows, 1, 1, 1, 1.0, 34);
writeInputMatrixWithMTD("B", B, true);
runTest(true, false, null, -1);
runRScript(true);
//compare matrices
HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS("R");
HashMap<CellIndex, Double> rfile = readRMatrixFromFS("R");
TestUtils.compareMatrices(dmlfile, rfile, eps, "Stat-DML", "Stat-R");
}
finally
{
rtplatform = platformOld;
DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;
}
}
}
| apache-2.0 |
Melody/Webdav | tests/client_litmus_test.php | 1439 | <?php
/**
* Client test for Litmus.
*
* 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 Webdav
* @subpackage Tests
* @version //autogentag//
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
*/
require_once 'client_test_suite.php';
require_once 'client_test_continuous_setup.php';
/**
* Client test for Litmus
*
* @package Webdav
* @subpackage Tests
*/
class ezcWebdavLitmusClientTest extends ezcTestCase
{
public static function suite()
{
return new ezcWebdavClientTestSuite(
'Litmus',
'clients/litmus.php',
new ezcWebdavClientTestContinuousSetup()
);
}
}
?>
| apache-2.0 |
lanceleverich/drools | drools-compiler/src/test/java/org/drools/compiler/integrationtests/session/TypeCoercionTest.java | 10948 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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.drools.compiler.integrationtests.session;
import java.util.ArrayList;
import java.util.List;
import org.drools.compiler.CommonTestMethodBase;
import org.drools.compiler.Person;
import org.drools.compiler.PolymorphicFact;
import org.drools.compiler.Primitives;
import org.drools.compiler.integrationtests.SerializationHelper;
import org.junit.Test;
import org.kie.api.KieBase;
import org.kie.api.definition.type.FactType;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;
import static org.junit.Assert.assertEquals;
public class TypeCoercionTest extends CommonTestMethodBase {
@Test
public void testRuntimeTypeCoercion() throws Exception {
final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase("test_RuntimeTypeCoercion.drl"));
final KieSession ksession = createKnowledgeSession(kbase);
final List list = new ArrayList();
ksession.setGlobal("results", list);
final PolymorphicFact fact = new PolymorphicFact(10);
final FactHandle handle = ksession.insert(fact);
ksession.fireAllRules();
assertEquals(1, list.size());
assertEquals(fact.getData(), list.get(0));
fact.setData("10");
ksession.update(handle, fact);
ksession.fireAllRules();
assertEquals(2, list.size());
assertEquals(fact.getData(), list.get(1));
fact.setData(Boolean.TRUE);
ksession.update(handle, fact);
assertEquals(2, list.size());
}
@Test
public void testRuntimeTypeCoercion2() throws Exception {
final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase("test_RuntimeTypeCoercion2.drl"));
final KieSession ksession = createKnowledgeSession(kbase);
final List list = new ArrayList();
ksession.setGlobal("results", list);
final Primitives fact = new Primitives();
fact.setBooleanPrimitive(true);
fact.setBooleanWrapper(Boolean.TRUE);
fact.setObject(Boolean.TRUE);
fact.setCharPrimitive('X');
final FactHandle handle = ksession.insert(fact);
ksession.fireAllRules();
int index = 0;
assertEquals(list.toString(), 4, list.size());
assertEquals("boolean", list.get(index++));
assertEquals("boolean wrapper", list.get(index++));
assertEquals("boolean object", list.get(index++));
assertEquals("char", list.get(index++));
fact.setBooleanPrimitive(false);
fact.setBooleanWrapper(null);
fact.setCharPrimitive('\0');
fact.setObject('X');
ksession.update(handle, fact);
ksession.fireAllRules();
assertEquals(5, list.size());
assertEquals("char object", list.get(index++));
fact.setObject(null);
ksession.update(handle, fact);
ksession.fireAllRules();
assertEquals(6, list.size());
assertEquals("null object", list.get(index));
}
@Test
public void testUnwantedCoersion() throws Exception {
final String rule = "package org.drools.compiler\n" +
"import " + InnerBean.class.getCanonicalName() + ";\n" +
"import " + OuterBean.class.getCanonicalName() + ";\n" +
"rule \"Test.Code One\"\n" +
"when\n" +
" OuterBean($code : inner.code in (\"1.50\", \"2.50\"))\n" +
"then\n" +
" System.out.println(\"Code compared values: 1.50, 2.50 - actual code value: \" + $code);\n" +
"end\n" +
"rule \"Test.Code Two\"\n" +
"when\n" +
" OuterBean($code : inner.code in (\"1.5\", \"2.5\"))\n" +
"then\n" +
" System.out.println(\"Code compared values: 1.5, 2.5 - actual code value: \" + $code);\n" +
"end\n" +
"rule \"Big Test ID One\"\n" +
"when\n" +
" OuterBean($id : id in (\"3.5\", \"4.5\"))\n" +
"then\n" +
" System.out.println(\"ID compared values: 3.5, 4.5 - actual ID value: \" + $id);\n" +
"end\n" +
"rule \"Big Test ID Two\"\n" +
"when\n" +
" OuterBean($id : id in ( \"3.0\", \"4.0\"))\n" +
"then\n" +
" System.out.println(\"ID compared values: 3.0, 4.0 - actual ID value: \" + $id);\n" +
"end";
final KieBase kbase = loadKnowledgeBaseFromString(rule);
final KieSession ksession = kbase.newKieSession();
final InnerBean innerTest = new InnerBean();
innerTest.setCode("1.500");
ksession.insert(innerTest);
final OuterBean outerTest = new OuterBean();
outerTest.setId("3");
outerTest.setInner(innerTest);
ksession.insert(outerTest);
final OuterBean outerTest2 = new OuterBean();
outerTest2.setId("3.0");
outerTest2.setInner(innerTest);
ksession.insert(outerTest2);
final int rules = ksession.fireAllRules();
assertEquals(1, rules);
}
public static class InnerBean {
private String code;
public String getCode() {
return code;
}
public void setCode(final String code) {
this.code = code;
}
}
public static class OuterBean {
private InnerBean inner;
private String id;
public InnerBean getInner() {
return inner;
}
public void setInner(final InnerBean inner) {
this.inner = inner;
}
public String getId() {
return id;
}
public void setId(final String id) {
this.id = id;
}
}
@Test
public void testCoercionOfStringValueWithoutQuotes() throws Exception {
// JBRULES-3080
final String str = "package org.drools.compiler.test; \n" +
"declare A\n" +
" field : String\n" +
"end\n" +
"rule R when\n" +
" A( field == 12 )\n" +
"then\n" +
"end\n";
final KieBase kbase = loadKnowledgeBaseFromString(str);
final KieSession ksession = kbase.newKieSession();
final FactType typeA = kbase.getFactType("org.drools.compiler.test", "A");
final Object a = typeA.newInstance();
typeA.set(a, "field", "12");
ksession.insert(a);
assertEquals(1, ksession.fireAllRules());
}
@Test
public void testPrimitiveToBoxedCoercionInMethodArgument() throws Exception {
final String str = "package org.drools.compiler.test;\n" +
"import " + TypeCoercionTest.class.getName() + "\n" +
"import org.drools.compiler.*\n" +
"rule R1 when\n" +
" Person( $ag1 : age )" +
" $p2 : Person( name == TypeCoercionTest.integer2String($ag1) )" +
"then\n" +
"end\n";
final KieBase kbase = loadKnowledgeBaseFromString(str);
final KieSession ksession = kbase.newKieSession();
final Person p = new Person("42", 42);
ksession.insert(p);
assertEquals(1, ksession.fireAllRules());
}
public static String integer2String(final Integer value) {
return "" + value;
}
@Test
public void testStringCoercion() {
// DROOLS-1688
final String drl = "package org.drools.compiler.test;\n" +
"import " + Person.class.getCanonicalName() + "\n" +
" rule R1 when\n" +
" Person(name == \"12\")\n" +
" then end\n" +
" rule R2 when\n" +
" Person(name == 11)\n " +
" then\n end\n" +
" rule R3 when\n" +
" Person(name == \"11\")\n" +
" then end\n";
KieBase kieBase = loadKnowledgeBaseFromString(drl);
KieSession kieSession = kieBase.newKieSession();
kieSession.insert(new Person("11"));
assertEquals(2, kieSession.fireAllRules());
}
@Test
public void testIntCoercion() {
// DROOLS-1688
final String drl = "package org.drools.compiler.test;\n" +
"import " + Person.class.getCanonicalName() + "\n" +
" rule R1 when\n" +
" Person(age == 12)\n" +
" then end\n" +
" rule R2 when\n" +
" Person(age == \"11\")\n " +
" then\n end\n" +
" rule R3 when\n" +
" Person(age == 11)\n" +
" then end\n";
KieBase kieBase = loadKnowledgeBaseFromString(drl);
KieSession kieSession = kieBase.newKieSession();
kieSession.insert(new Person("Mario", 11));
assertEquals(2, kieSession.fireAllRules());
}
@Test
public void testCoercionInJoin() {
// DROOLS-2695
final String drl =
" rule R1 when\n" +
" Integer($i : intValue)\n" +
" String(this == $i)\n" +
" then end\n";
KieBase kieBase = loadKnowledgeBaseFromString(drl);
KieSession kieSession = kieBase.newKieSession();
kieSession.insert(2);
kieSession.insert("2");
assertEquals(1, kieSession.fireAllRules());
}
@Test
public void testCoercionInJoinOnField() {
// DROOLS-2695
final String drl =
"import " + Person.class.getCanonicalName() + "\n" +
" rule R1 when\n" +
" Integer($i : intValue)\n" +
" Person(name == $i)\n" +
" then end\n";
KieBase kieBase = loadKnowledgeBaseFromString(drl);
KieSession kieSession = kieBase.newKieSession();
kieSession.insert(2);
kieSession.insert(new Person("2", 11));
assertEquals(1, kieSession.fireAllRules());
}
}
| apache-2.0 |
maas-ufcg/manageiq | spec/automation/unit/method_validation/scvmm_microsoft_best_fit_least_utilized_spec.rb | 4375 | describe "SCVMM microsoft_best_fit_least_utilized" do
let(:user) { FactoryGirl.create(:user_with_group) }
let(:ws) do
MiqAeEngine.instantiate("/System/Request/Call_Instance_With_Message?" \
"namespace=Infrastructure/VM/Provisioning&class=Placement" \
"&instance=default&message=microsoft&" \
"MiqProvision::miq_provision=#{miq_provision.id}", user)
end
let(:vm_template) do
FactoryGirl.create(:template_microsoft,
:name => "template1",
:ext_management_system => FactoryGirl.create(:ems_microsoft_with_authentication))
end
let(:miq_provision) do
FactoryGirl.create(:miq_provision_microsoft,
:options => {:src_vm_id => vm_template.id,
:placement_auto => [true, 1]},
:userid => user.userid,
:state => 'active',
:status => 'Ok')
end
let(:host) { FactoryGirl.create(:host_microsoft, :power_state => "on") }
let(:storage) { FactoryGirl.create(:storage, :free_space => 10.gigabytes) }
let(:ro_storage) { FactoryGirl.create(:storage, :free_space => 20.gigabytes) }
context "provision task object" do
it "without host or storage will not set placement values" do
ws.root
miq_provision.reload
expect(miq_provision.options[:placement_host_name]).to be_nil
expect(miq_provision.options[:placement_ds_name]).to be_nil
end
context "with an eligible host" do
before do
host_struct = MiqHashStruct.new(:id => host.id,
:evm_object_class => host.class.base_class.name.to_sym)
allow_any_instance_of(ManageIQ::Providers::Microsoft::InfraManager::ProvisionWorkflow)
.to receive(:allowed_hosts).and_return([host_struct])
end
it "without storage will not set placement values" do
ws.root
miq_provision.reload
expect(miq_provision.options[:placement_host_name]).to be_nil
expect(miq_provision.options[:placement_ds_name]).to be_nil
end
context "with storage" do
before do
host.storages << storage
storage_struct = MiqHashStruct.new(:id => storage.id,
:evm_object_class => storage.class.base_class.name.to_sym)
allow_any_instance_of(ManageIQ::Providers::Microsoft::InfraManager::ProvisionWorkflow)
.to receive(:allowed_storages).and_return([storage_struct])
end
it "will set placement values" do
ws.root
miq_provision.reload
expect(miq_provision.options[:placement_host_name]).to eq([host.id, host.name])
expect(miq_provision.options[:placement_ds_name]).to eq([storage.id, storage.name])
end
it "will not set placement values when placement_auto is false" do
miq_provision.update_attributes(:options => miq_provision.options.merge(:placement_auto => [false, 0]))
ws.root
miq_provision.reload
expect(miq_provision.options[:placement_host_name]).to be_nil
expect(miq_provision.options[:placement_ds_name]).to be_nil
end
end
context "with read-only storage" do
before do
host.storages << [ro_storage, storage]
HostStorage.where(:host_id => host.id, :storage_id => ro_storage.id).update(:read_only => true)
evm_object_class = storage.class.base_class.name.to_sym
storage_struct = [MiqHashStruct.new(:id => ro_storage.id, :evm_object_class => evm_object_class),
MiqHashStruct.new(:id => storage.id, :evm_object_class => evm_object_class)]
allow_any_instance_of(ManageIQ::Providers::Microsoft::InfraManager::ProvisionWorkflow)
.to receive(:allowed_storages).and_return(storage_struct)
end
it "picks the largest writable datastore" do
ws.root
miq_provision.reload
expect(miq_provision.options[:placement_host_name]).to eq([host.id, host.name])
expect(miq_provision.options[:placement_ds_name]).to eq([storage.id, storage.name])
end
end
end
end
end
| apache-2.0 |
hbbtvSenegal/siteDeVente | antie/static/script/devices/media/samsung_maple.js | 20270 | /**
* @fileOverview Requirejs module containing samsung maple media wrapper
*
* @preserve Copyright (c) 2013 British Broadcasting Corporation
* (http://www.bbc.co.uk) and TAL Contributors (1)
*
* (1) TAL Contributors are listed in the AUTHORS file and at
* https://github.com/fmtvp/TAL/AUTHORS - please extend this file,
* not this notice.
*
* @license 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.
*
* All rights reserved
* Please contact us for an alternative licence
*/
require.def(
'antie/devices/media/samsung_maple',
[
'antie/devices/device',
'antie/devices/media/mediainterface',
'antie/events/mediaevent',
'antie/events/mediaerrorevent',
'antie/events/mediasourceerrorevent',
'antie/mediasource',
'antie/application'
],
function(Device, MediaInterface, MediaEvent, MediaErrorEvent, MediaSourceErrorEvent, MediaSource, Application) {
'use strict';
function audioLevelCorrection(t) {
return t * 40.0;
}
function invertAudioLevelCorrection(x) {
return x / 40.0;
}
var SamsungPlayer = MediaInterface.extend({
init: function(id, mediaType, eventHandlingCallback) {
this._super(id);
this._eventHandlingCallback = eventHandlingCallback;
this.playerPlugin = document.getElementById('playerPlugin');
this.audioPlugin = document.getElementById('audioPlugin');
this.tvmwPlugin = document.getElementById('pluginObjectTVMW');
this.originalSource = this.tvmwPlugin.GetSource();
this.mediaSource = null;
this._addExitStrategyEventListener();
if (mediaType == "audio") {
this._mediaType = "audio";
} else if (mediaType == "video") {
this._mediaType = "video";
} else {
throw new Error('Unrecognised media type: ' + mediaType);
}
this.videoPlayerState = {
durationSeconds : 0,
currentTime: 0,
playbackRate: undefined,
paused: false,
ended: false,
seeking: false,
playing: false
};
this.registerEventHandlers();
},
registerEventHandlers : function() {
// All functions attached to the window that start SamsungMapleOn
// will be intercepted and logged, only when test/emit_video_events.js is included
// for cucumber. Only those that are attached to the window will be intercepted, not
// functions attached later.
var self = this;
window.SamsungMapleOnBufferingStart = function() {
self._eventHandlingCallback(new MediaEvent("waiting", self));
};
this.playerPlugin.OnBufferingStart = 'SamsungMapleOnBufferingStart';
window.SamsungMapleOnBufferingComplete = function() {
self._eventHandlingCallback(new MediaEvent("playing", self));
};
this.playerPlugin.OnBufferingComplete = 'SamsungMapleOnBufferingComplete';
window.SamsungMapleOnConnectionFailed = function() {
self._eventHandlingCallback(new MediaErrorEvent(self, "Connection failed"));
};
this.playerPlugin.OnConnectionFailed = 'SamsungMapleOnConnectionFailed';
window.SamsungMapleOnNetworkDisconnected = function() {
self._eventHandlingCallback(new MediaErrorEvent(self, "Network disconnected"));
};
this.playerPlugin.OnNetworkDisconnected = 'SamsungMapleOnNetworkDisconnected';
window.SamsungMapleOnRenderError = function() {
self._eventHandlingCallback(new MediaErrorEvent(self, "Render error"));
};
this.playerPlugin.OnRenderError = 'SamsungMapleOnRenderError';
window.SamsungMapleOnStreamNotFound = function() {
self._eventHandlingCallback(new MediaErrorEvent(self, "Stream not found"));
};
this.playerPlugin.OnStreamNotFound = 'SamsungMapleOnStreamNotFound';
window.SamsungMapleOnRenderingComplete = function () {
self.videoPlayerState.ended = true;
window.SamsungMapleOnTimeUpdate(self.videoPlayerState.durationSeconds);
self._eventHandlingCallback(new MediaEvent("ended", self));
};
this.playerPlugin.OnRenderingComplete = 'SamsungMapleOnRenderingComplete';
window.SamsungMapleOnStreamInfoReady = function () {
self.videoPlayerState.durationSeconds = self.playerPlugin.GetDuration() / 1000;
self._eventHandlingCallback(new MediaEvent("loadedmetadata", self));
self._eventHandlingCallback(new MediaEvent("durationchange", self));
self._eventHandlingCallback(new MediaEvent("canplay", self));
self._eventHandlingCallback(new MediaEvent("canplaythrough", self));
};
this.playerPlugin.OnStreamInfoReady = 'SamsungMapleOnStreamInfoReady';
window.SamsungMapleOnCurrentPlayTime = function (timeMs) {
var seconds = timeMs / 1000.0;
if ((self.mediaSource.isLiveStream() && self.videoPlayerState.ended == false) ||
(seconds >= 0 && seconds < self.videoPlayerState.durationSeconds)) {
self.videoPlayerState.currentTime = seconds;
if (self.videoPlayerState.seeking) {
self.videoPlayerState.seeking = false;
self._eventHandlingCallback(new MediaEvent('seeked', self));
}
if (self.videoPlayerState.playing === false) {
self._eventHandlingCallback(new MediaEvent('play', self));
self._eventHandlingCallback(new MediaEvent('playing', self));
self.videoPlayerState.playing = true;
}
else {
// don't throw a timeupdate on the first event
window.SamsungMapleOnTimeUpdate(seconds);
}
}
};
this.playerPlugin.OnCurrentPlayTime = 'SamsungMapleOnCurrentPlayTime';
window.SamsungMapleOnTimeUpdate = function(seconds) {
self._eventHandlingCallback(new MediaEvent("timeupdate", self));
};
},
render: function(device) {
if (!this.outputElement) {
this.outputElement = document.createElement("div");
}
return this.outputElement;
},
// (not part of HTML5 media)
setWindow: function(left, top, width, height) {
if (this._mediaType == "audio") {
throw new Error('Unable to set window size for Samsung audio.');
}
this.playerPlugin.SetDisplayArea(left, top, width, height);
},
// readonly attribute MediaError error;
getError: function() {
// TODO: Samsung implementation
},
// Similar to src attribute or 'source' child elements:
// attribute DOMString src;
setSources: function(sources, tags) {
this.videoPlayerState = {
durationSeconds : 0,
currentTime: 0,
playbackRate: undefined,
paused: false,
ended: false,
seeking: false,
playing: false
};
this.mediaSource = sources[0];
this.playerPlugin.Stop();
// SamsungMaple.pluginAPI.setOffScreenSaver(); // @see http://www.samsungdforum.com/Board/FAQView?BoardID=28797
this.tvmwPlugin.SetMediaSource();
this._getSamsungFormattedUrl = this.mediaSource.getURL(tags);
if (this.mediaSource.isLiveStream()) {
this._getSamsungFormattedUrl += "|COMPONENT=HLS";
}
this._resetVideoSize();
},
getSources: function() {
return [this.mediaSource];
},
// readonly attribute DOMString currentSrc;
getCurrentSource: function() {
return this.mediaSource.src;
},
/*
const unsigned short NETWORK_EMPTY = 0;
const unsigned short NETWORK_IDLE = 1;
const unsigned short NETWORK_LOADING = 2;
const unsigned short NETWORK_NO_SOURCE = 3;
readonly attribute unsigned short networkState;
*/
getNetworkState: function() {
// TODO: Samsung implementation
},
// attribute DOMString preload;
// @returns "none", "metadata" or "auto"
getPreload: function() {
// TODO: Samsung implementation
return "none";
},
setPreload: function(preload) {
// TODO: Samsung implementation
},
// readonly attribute TimeRanges buffered;
getBuffered: function() {
// TODO: Samsung implementation
return [];
},
// void load();
load: function() {
this.videoPlayerState.playbackRate = 1;
this.videoPlayerState.paused = false;
this.videoPlayerState.ended = false;
this.videoPlayerState.playing = false;
if (this.videoPlayerState.currentTime > 0) {
this.playerPlugin.ResumePlay(this._getSamsungFormattedUrl, this.videoPlayerState.currentTime);
}
else {
this.playerPlugin.Play(this._getSamsungFormattedUrl);
}
},
// DOMString canPlayType(in DOMString type);
canPlayType: function(type) {
// TODO: Samsung implementation
return true;
},
/*
const unsigned short HAVE_NOTHING = 0;
const unsigned short HAVE_METADATA = 1;
const unsigned short HAVE_CURRENT_DATA = 2;
const unsigned short HAVE_FUTURE_DATA = 3;
const unsigned short HAVE_ENOUGH_DATA = 4;
readonly attribute unsigned short readyState;
*/
getReadyState: function() {
// TODO: Samsung implementation
return 0;
},
// readonly attribute boolean seeking;
getSeeking: function() {
// TODO: Samsung implementation
return false;
},
// attribute double currentTime;
setCurrentTime: function(timeToSeekTo) {
var offsetInSeconds = timeToSeekTo - this.videoPlayerState.currentTime;
if (offsetInSeconds > 0) {
var jumped = this.playerPlugin.JumpForward(offsetInSeconds);
// Jump forward appears not to work consistently in the initial moments of a video playback.
// if we are in the initial set up, lets try resuming instead
// Samsung 2010 returns -1 for failure. Newer API returns false.
if ((!jumped || jumped < 0) && this.videoPlayerState.currentTime < 1) {
this.playerPlugin.Stop();
this._resetVideoSize();
this.playerPlugin.ResumePlay(this._getSamsungFormattedUrl, timeToSeekTo);
}
} else if (offsetInSeconds < 0) {
this.playerPlugin.JumpBackward(Math.abs(offsetInSeconds));
}
this.videoPlayerState.seeking = true;
this._eventHandlingCallback(new MediaEvent('seeking', this));
this.videoPlayerState.currentTime = timeToSeekTo;
},
getCurrentTime: function() {
// TODO: Samsung implementation
return this.videoPlayerState.currentTime;
},
// readonly attribute double initialTime;
getInitialTime: function() {
// TODO: Samsung implementation
return 0;
},
// readonly attribute double duration;
getDuration: function() {
// TODO: Samsung implementation
return this.videoPlayerState.durationSeconds;
},
// readonly attribute Date startOffsetTime;
getStartOffsetTime: function() {
// TODO: Samsung implementation
return 0;
},
// readonly attribute boolean paused;
getPaused: function() {
return this.videoPlayerState.paused;
},
// attribute double defaultPlaybackRate;
getDefaultPlaybackRate: function() {
// TODO: Samsung implementation
return 1;
},
// attribute double playbackRate;
getPlaybackRate: function() {
// TODO: Samsung implementation
return 1;
},
setPlaybackRate: function(playbackRate) {
// TODO: Samsung implementation
},
// readonly attribute TimeRanges played;
getPlayed: function() {
// TODO: Samsung implementation
return [];
},
// readonly attribute TimeRanges seekable;
getSeekable: function() {
// TODO: Samsung implementation
return [];
},
// readonly attribute boolean ended;
getEnded: function() {
// TODO: Samsung implementation
return false;
},
// attribute boolean autoplay;
getAutoPlay: function() {
// TODO: Samsung implementation
return false;
},
setAutoPlay: function(autoplay) {
// TODO: Samsung implementation
},
// attribute boolean loop;
getLoop: function() {
// TODO: Samsung implementation
return false;
},
setLoop: function(loop) {
// TODO: Samsung implementation
},
// void play();
play: function() {
if (this.videoPlayerState.paused) {
this.playerPlugin.Resume();
this.videoPlayerState.paused = false;
this._eventHandlingCallback(new MediaEvent("play", this));
this._eventHandlingCallback(new MediaEvent("playing", this));
}
},
stop: function() {
this.playerPlugin.Stop();
},
// void pause();
pause: function() {
var self = this;
self.playerPlugin.Pause();
self.videoPlayerState.paused = true;
window.setTimeout(function() {
self._eventHandlingCallback(new MediaEvent("pause", self))
}, 0);
},
// attribute boolean controls;
setNativeControls: function(controls) {
// TODO: Samsung implementation
},
getNativeControls: function() {
// TODO: Samsung implementation
return false;
},
destroy: function() {
this.stop();
},
_resetVideoSize: function() {
// Workaround for the Samsung 2010 device: video playback starts in a small window by default.
if (this._mediaType === "video") {
var dimensions = Application.getCurrentApplication().getDevice().getScreenSize();
this.setWindow(0, 0, dimensions.width, dimensions.height);
}
},
_addExitStrategyEventListener: function() {
var self = this;
window.addEventListener('hide', function() {
self.playerPlugin.Stop();
self.tvmwPlugin.SetSource(self.originalSource);
}, false);
}
});
Device.prototype.createMediaInterface = function(id, mediaType, eventCallback) {
return new SamsungPlayer(id, mediaType, eventCallback);
};
Device.prototype.getPlayerEmbedMode = function(mediaType) {
return MediaInterface.EMBED_MODE_BACKGROUND;
};
/**
* Check to see if volume control is supported on this device.
* @returns Boolean true if volume control is supported.
*/
Device.prototype.isVolumeControlSupported = function() {
return true;
};
/**
* Get the current volume.
* @returns The current volume (0.0 to 1.0)
*/
Device.prototype.getVolume = function() {
var audio = document.getElementById('audioPlugin');
return invertAudioLevelCorrection(audio.GetVolume());
};
/**
* Set the current volume.
* @param {Float} volume The new volume level (0.0 to 1.0).
*/
Device.prototype.setVolume = function(volume) {
var audio = document.getElementById('audioPlugin');
if (volume > 1.0) {
this.getLogger().warn("Samsung setVolume - Invalid volume specified (" + volume + " > 1.0). Clipped to 1.0");
volume = 1.0;
} else if (volume < 0.0) {
this.getLogger().warn("Samsung setVolume - Invalid volume specified (" + volume + " < 0.0). Clipped to 0.0");
volume = 0;
}
var currentVolume = audio.GetVolume();
var newVolume = audioLevelCorrection(volume);
if ((newVolume > currentVolume) && (newVolume - currentVolume < 1.0)) {
newVolume = currentVolume + 1;
} else if ((newVolume < currentVolume) && (currentVolume - newVolume < 1.0)) {
newVolume = currentVolume - 1;
}
audio.SetVolume(newVolume);
return newVolume;
};
/**
* Check to see if the volume is currently muted.
* @returns Boolean true if the device is currently muted. Otherwise false.
*/
Device.prototype.getMuted = function() {
var audio = document.getElementById('audioPlugin');
return audio.GetSystemMute();
};
/**
* Mute or unmute the device.
* @param {Boolean} muted The new muted state. Boolean true to mute, false to unmute.
*/
Device.prototype.setMuted = function(muted) {
var audio = document.getElementById('audioPlugin');
audio.SetSystemMute(muted);
};
return SamsungPlayer;
}
);
| apache-2.0 |
roberth/pitest | pitest/src/main/java/org/pitest/mutationtest/engine/Mutant.java | 1005 | /*
* Copyright 2010 Henry Coles
*
* 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.pitest.mutationtest.engine;
public final class Mutant {
private final MutationDetails details;
private final byte[] bytes;
public Mutant(final MutationDetails details, final byte[] bytes) {
this.details = details;
this.bytes = bytes;
}
public MutationDetails getDetails() {
return this.details;
}
public byte[] getBytes() {
return this.bytes;
}
}
| apache-2.0 |
nlamirault/kubernetes | pkg/kubectl/cmd/create_service_test.go | 1779 | /*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"bytes"
"net/http"
"testing"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/client/unversioned/fake"
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
)
func TestCreateService(t *testing.T) {
service := &api.Service{}
service.Name = "my-service"
f, tf, codec, negSer := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{
NegotiatedSerializer: negSer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
switch p, m := req.URL.Path, req.Method; {
case p == "/namespaces/test/services" && m == "POST":
return &http.Response{StatusCode: 201, Header: defaultHeader(), Body: objBody(codec, service)}, nil
default:
t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
return nil, nil
}
}),
}
tf.Namespace = "test"
buf := bytes.NewBuffer([]byte{})
cmd := NewCmdCreateServiceClusterIP(f, buf)
cmd.Flags().Set("output", "name")
cmd.Flags().Set("tcp", "8080:8000")
cmd.Run(cmd, []string{service.Name})
expectedOutput := "service/" + service.Name + "\n"
if buf.String() != expectedOutput {
t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String())
}
}
| apache-2.0 |
kuali/rice-playground | rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/util/UrlInfo.java | 10802 | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krad.uif.util;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.krad.datadictionary.parse.BeanTag;
import org.kuali.rice.krad.datadictionary.parse.BeanTagAttribute;
import org.kuali.rice.krad.datadictionary.uif.UifDictionaryBeanBase;
import org.kuali.rice.krad.uif.UifConstants;
import org.kuali.rice.krad.util.KRADUtils;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* This object represents a url in the Krad framework. The url can be set explicitly to a specific href or a
* controller
* plus a viewId can be provided (at very minimum). By default, the krad base bean config points the baseUrl property
* to 'krad.url' configuration property and the methodToCall to 'start', but these can be reset to any value as needed.
*
* <p>
* If href is not set, the generated value of href is constructed (in general) as follows:<br/>
* baseUrl + /controllerMapping + ? + methodToCall param + viewId param + other parameters
* <br/>
* with any necessary tokens to construct a valid url. If baseUrl is not provided, the url is not valid and a
* blank string is returned.
* </p>
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
@BeanTag(name = "url", parent = "Uif-Url")
public class UrlInfo extends UifDictionaryBeanBase implements Serializable {
private static final long serialVersionUID = 3195177614468120958L;
private String href;
private String originalHref;
private String baseUrl;
private String controllerMapping;
private String viewType;
private String viewId;
private String pageId;
private String formKey;
private String methodToCall;
private Map<String, String> requestParameters;
/**
* Base constructor
*/
public UrlInfo() {}
/**
* Constructor that initializes an href value
*
* @param href the href value
*/
public UrlInfo(String href) {
this.href = href;
this.originalHref = href;
}
/**
* Constructor that sets the base url construction properties
*
* @param baseUrl the baseUrl
* @param controllerMapping the controllerMapping
* @param viewId the id of the view
* @param methodToCall the methodToCall
*/
public UrlInfo(String baseUrl, String controllerMapping, String viewId, String methodToCall) {
this.baseUrl = baseUrl;
this.controllerMapping = controllerMapping;
this.viewId = viewId;
this.methodToCall = methodToCall;
}
public boolean isFullyConfigured() {
boolean fullyConfigured = false;
if (StringUtils.isNotBlank(href)) {
fullyConfigured = true;
}
else if (StringUtils.isNotBlank(baseUrl) && StringUtils.isNotBlank(controllerMapping)) {
fullyConfigured = true;
}
return fullyConfigured;
}
/**
* Generate the url based on properties of this object
*
* @return the generatedUrl, blank if not a valid url (no baseUrl value provided)
*/
protected String generateUrl() {
String generatedUrl = "";
if (StringUtils.isBlank(baseUrl)) {
return generatedUrl;
}
generatedUrl = baseUrl;
if (StringUtils.isNotBlank(controllerMapping) && !controllerMapping.startsWith("/")) {
generatedUrl = generatedUrl + "/" + controllerMapping;
} else if (StringUtils.isNotBlank(controllerMapping)) {
generatedUrl = generatedUrl + controllerMapping;
}
Map<String, String> allRequestParameters = new HashMap<String, String>();
if (StringUtils.isNotBlank(methodToCall)) {
allRequestParameters.put(UifConstants.CONTROLLER_METHOD_DISPATCH_PARAMETER_NAME, methodToCall);
}
if (StringUtils.isNotBlank(viewId)) {
allRequestParameters.put(UifConstants.UrlParams.VIEW_ID, viewId);
}
if (StringUtils.isNotBlank(pageId)) {
allRequestParameters.put(UifConstants.UrlParams.PAGE_ID, pageId);
}
if (StringUtils.isNotBlank(formKey)) {
allRequestParameters.put(UifConstants.UrlParams.FORM_KEY, formKey);
}
if (requestParameters != null) {
allRequestParameters.putAll(requestParameters);
}
//add the request parameters
generatedUrl = generatedUrl + KRADUtils.getRequestStringFromMap(allRequestParameters);
return generatedUrl;
}
/**
* Get the href value for this url object. This is the main call to this url object as it provides the full href
* value represented by this object.
*
* <p>
* If href has NOT been explicitly set to a value, the href is generated by
* constructing pieces of the url set through the properties of this url object.
* The generated value of href is constructed (in general) as follows:<br/>
* baseUrl + /controllerMapping + ? + methodToCall param + viewId param + other parameters
* <br/>
* with any necessary tokens to construct a valid url. If baseUrl is not provided, the url is not valid and a
* blank string is returned.
* </p>
*
* @return THE href represented by this url object, or blank if not valid
*/
@BeanTagAttribute
public String getHref() {
if (StringUtils.isBlank(this.href)) {
this.href = generateUrl();
}
return href;
}
/**
* Explicitly set the href value - if this is called with a value, all other properties of the url object are
* ignored. This call is basically a full override. This also sets the orginalHref value.
*
* @param href
*/
public void setHref(String href) {
this.href = href;
this.originalHref = href;
}
/**
* The base url value (the value that comes before other properties). Default base bean value is set to use
* 'krad.url' of the configuration properties.
*
* @return the baseUrl
*/
@BeanTagAttribute
public String getBaseUrl() {
return baseUrl;
}
/**
* Set the baseUrl
*
* @param baseUrl
*/
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
/**
* The controllerMapping for the url (string that represents the controllerMapping path appended to baseUrl)
*
* @return the controllerMapping string
*/
@BeanTagAttribute
public String getControllerMapping() {
return controllerMapping;
}
/**
* Set the controllerMapping
*
* @param controllerMapping
*/
public void setControllerMapping(String controllerMapping) {
this.controllerMapping = controllerMapping;
}
/**
* The viewType representing the View's base type
*
* @return the viewType
*/
@BeanTagAttribute
public String getViewType() {
return viewType;
}
/**
* Set the viewType
*
* @param viewType
*/
public void setViewType(String viewType) {
this.viewType = viewType;
}
/**
* ViewId representing the view by id to retrieve
*
* @return the viewId
*/
@BeanTagAttribute
public String getViewId() {
return viewId;
}
/**
* Set viewId
*
* @param viewId
*/
public void setViewId(String viewId) {
this.viewId = viewId;
}
/**
* PageId representing the page of the view to retrieve by id
*
* @return the pageId
*/
@BeanTagAttribute
public String getPageId() {
return pageId;
}
/**
* Set pageId
*
* @param pageId
*/
public void setPageId(String pageId) {
this.pageId = pageId;
}
/**
* FormKey representing the key of the form data to retrieve
*
* @return the formKey
*/
@BeanTagAttribute
public String getFormKey() {
return formKey;
}
/**
* Set the formKey
*
* @param formKey
*/
public void setFormKey(String formKey) {
this.formKey = formKey;
}
/**
* MethodToCall representing the methodToCall on the controller (default base bean value is 'start')
*
* @return methodToCall on controller
*/
@BeanTagAttribute
public String getMethodToCall() {
return methodToCall;
}
/**
* Set the methodToCall
*
* @param methodToCall
*/
public void setMethodToCall(String methodToCall) {
this.methodToCall = methodToCall;
}
/**
* Map of key value pairs that will be appended to the request parameters to pass in any custom data
*
* @return the requestParameters map
*/
@BeanTagAttribute
public Map<String, String> getRequestParameters() {
return requestParameters;
}
/**
* Set the requestParameters
*
* @param requestParameters
*/
public void setRequestParameters(Map<String, String> requestParameters) {
this.requestParameters = requestParameters;
}
/**
* The original(set) href value. This is generally used to determine if the href was explicitly set and not
* generated by this url object.
*
* @return the original(set) href value
*/
public String getOriginalHref() {
return originalHref;
}
/**
* toString returns the original href value of url
*
* @param originalHref original href value
*/
protected void setOriginalHref(String originalHref) {
this.originalHref = originalHref;
}
/**
* toString override returns the href value of url
*
* @return href value
*/
@Override
public String toString() {
return this.getHref();
}
}
| apache-2.0 |
graetzer/arangodb | 3rdParty/V8/v7.9.317/src/execution/s390/simulator-s390.cc | 309119 | // Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/execution/s390/simulator-s390.h"
// Only build the simulator if not compiling for real s390 hardware.
#if defined(USE_SIMULATOR)
#include <stdarg.h>
#include <stdlib.h>
#include <cmath>
#include "src/base/bits.h"
#include "src/base/once.h"
#include "src/codegen/assembler.h"
#include "src/codegen/macro-assembler.h"
#include "src/codegen/register-configuration.h"
#include "src/codegen/s390/constants-s390.h"
#include "src/diagnostics/disasm.h"
#include "src/heap/combined-heap.h"
#include "src/objects/objects-inl.h"
#include "src/runtime/runtime-utils.h"
#include "src/utils/ostreams.h"
namespace v8 {
namespace internal {
// This macro provides a platform independent use of sscanf. The reason for
// SScanF not being implemented in a platform independent way through
// ::v8::internal::OS in the same way as SNPrintF is that the
// Windows C Run-Time Library does not provide vsscanf.
#define SScanF sscanf // NOLINT
const Simulator::fpr_t Simulator::fp_zero;
// The S390Debugger class is used by the simulator while debugging simulated
// z/Architecture code.
class S390Debugger {
public:
explicit S390Debugger(Simulator* sim) : sim_(sim) {}
void Stop(Instruction* instr);
void Debug();
private:
#if V8_TARGET_LITTLE_ENDIAN
static const Instr kBreakpointInstr = (0x0000FFB2); // TRAP4 0000
static const Instr kNopInstr = (0x00160016); // OR r0, r0 x2
#else
static const Instr kBreakpointInstr = (0xB2FF0000); // TRAP4 0000
static const Instr kNopInstr = (0x16001600); // OR r0, r0 x2
#endif
Simulator* sim_;
intptr_t GetRegisterValue(int regnum);
double GetRegisterPairDoubleValue(int regnum);
double GetFPDoubleRegisterValue(int regnum);
float GetFPFloatRegisterValue(int regnum);
bool GetValue(const char* desc, intptr_t* value);
bool GetFPDoubleValue(const char* desc, double* value);
// Set or delete a breakpoint. Returns true if successful.
bool SetBreakpoint(Instruction* break_pc);
bool DeleteBreakpoint(Instruction* break_pc);
// Undo and redo all breakpoints. This is needed to bracket disassembly and
// execution to skip past breakpoints when run from the debugger.
void UndoBreakpoints();
void RedoBreakpoints();
};
void S390Debugger::Stop(Instruction* instr) {
// Get the stop code.
// use of kStopCodeMask not right on PowerPC
uint32_t code = instr->SvcValue() & kStopCodeMask;
// Retrieve the encoded address, which comes just after this stop.
char* msg = *reinterpret_cast<char**>(sim_->get_pc() + sizeof(FourByteInstr));
// Update this stop description.
if (sim_->isWatchedStop(code) && !sim_->watched_stops_[code].desc) {
sim_->watched_stops_[code].desc = msg;
}
// Print the stop message and code if it is not the default code.
if (code != kMaxStopCode) {
PrintF("Simulator hit stop %u: %s\n", code, msg);
} else {
PrintF("Simulator hit %s\n", msg);
}
sim_->set_pc(sim_->get_pc() + sizeof(FourByteInstr) + kPointerSize);
Debug();
}
intptr_t S390Debugger::GetRegisterValue(int regnum) {
return sim_->get_register(regnum);
}
double S390Debugger::GetRegisterPairDoubleValue(int regnum) {
return sim_->get_double_from_register_pair(regnum);
}
double S390Debugger::GetFPDoubleRegisterValue(int regnum) {
return sim_->get_double_from_d_register(regnum);
}
float S390Debugger::GetFPFloatRegisterValue(int regnum) {
return sim_->get_float32_from_d_register(regnum);
}
bool S390Debugger::GetValue(const char* desc, intptr_t* value) {
int regnum = Registers::Number(desc);
if (regnum != kNoRegister) {
*value = GetRegisterValue(regnum);
return true;
} else {
if (strncmp(desc, "0x", 2) == 0) {
return SScanF(desc + 2, "%" V8PRIxPTR,
reinterpret_cast<uintptr_t*>(value)) == 1;
} else {
return SScanF(desc, "%" V8PRIuPTR, reinterpret_cast<uintptr_t*>(value)) ==
1;
}
}
return false;
}
bool S390Debugger::GetFPDoubleValue(const char* desc, double* value) {
int regnum = DoubleRegisters::Number(desc);
if (regnum != kNoRegister) {
*value = sim_->get_double_from_d_register(regnum);
return true;
}
return false;
}
bool S390Debugger::SetBreakpoint(Instruction* break_pc) {
// Check if a breakpoint can be set. If not return without any side-effects.
if (sim_->break_pc_ != nullptr) {
return false;
}
// Set the breakpoint.
sim_->break_pc_ = break_pc;
sim_->break_instr_ = break_pc->InstructionBits();
// Not setting the breakpoint instruction in the code itself. It will be set
// when the debugger shell continues.
return true;
}
bool S390Debugger::DeleteBreakpoint(Instruction* break_pc) {
if (sim_->break_pc_ != nullptr) {
sim_->break_pc_->SetInstructionBits(sim_->break_instr_);
}
sim_->break_pc_ = nullptr;
sim_->break_instr_ = 0;
return true;
}
void S390Debugger::UndoBreakpoints() {
if (sim_->break_pc_ != nullptr) {
sim_->break_pc_->SetInstructionBits(sim_->break_instr_);
}
}
void S390Debugger::RedoBreakpoints() {
if (sim_->break_pc_ != nullptr) {
sim_->break_pc_->SetInstructionBits(kBreakpointInstr);
}
}
void S390Debugger::Debug() {
intptr_t last_pc = -1;
bool done = false;
#define COMMAND_SIZE 63
#define ARG_SIZE 255
#define STR(a) #a
#define XSTR(a) STR(a)
char cmd[COMMAND_SIZE + 1];
char arg1[ARG_SIZE + 1];
char arg2[ARG_SIZE + 1];
char* argv[3] = {cmd, arg1, arg2};
// make sure to have a proper terminating character if reaching the limit
cmd[COMMAND_SIZE] = 0;
arg1[ARG_SIZE] = 0;
arg2[ARG_SIZE] = 0;
// Undo all set breakpoints while running in the debugger shell. This will
// make them invisible to all commands.
UndoBreakpoints();
// Disable tracing while simulating
bool trace = ::v8::internal::FLAG_trace_sim;
::v8::internal::FLAG_trace_sim = false;
while (!done && !sim_->has_bad_pc()) {
if (last_pc != sim_->get_pc()) {
disasm::NameConverter converter;
disasm::Disassembler dasm(converter);
// use a reasonably large buffer
v8::internal::EmbeddedVector<char, 256> buffer;
dasm.InstructionDecode(buffer, reinterpret_cast<byte*>(sim_->get_pc()));
PrintF(" 0x%08" V8PRIxPTR " %s\n", sim_->get_pc(), buffer.begin());
last_pc = sim_->get_pc();
}
char* line = ReadLine("sim> ");
if (line == nullptr) {
break;
} else {
char* last_input = sim_->last_debugger_input();
if (strcmp(line, "\n") == 0 && last_input != nullptr) {
line = last_input;
} else {
// Ownership is transferred to sim_;
sim_->set_last_debugger_input(line);
}
// Use sscanf to parse the individual parts of the command line. At the
// moment no command expects more than two parameters.
int argc = SScanF(line,
"%" XSTR(COMMAND_SIZE) "s "
"%" XSTR(ARG_SIZE) "s "
"%" XSTR(ARG_SIZE) "s",
cmd, arg1, arg2);
if ((strcmp(cmd, "si") == 0) || (strcmp(cmd, "stepi") == 0)) {
intptr_t value;
// If at a breakpoint, proceed past it.
if ((reinterpret_cast<Instruction*>(sim_->get_pc()))
->InstructionBits() == 0x7D821008) {
sim_->set_pc(sim_->get_pc() + sizeof(FourByteInstr));
} else {
sim_->ExecuteInstruction(
reinterpret_cast<Instruction*>(sim_->get_pc()));
}
if (argc == 2 && last_pc != sim_->get_pc()) {
disasm::NameConverter converter;
disasm::Disassembler dasm(converter);
// use a reasonably large buffer
v8::internal::EmbeddedVector<char, 256> buffer;
if (GetValue(arg1, &value)) {
// Interpret a numeric argument as the number of instructions to
// step past.
for (int i = 1; (!sim_->has_bad_pc()) && i < value; i++) {
dasm.InstructionDecode(buffer,
reinterpret_cast<byte*>(sim_->get_pc()));
PrintF(" 0x%08" V8PRIxPTR " %s\n", sim_->get_pc(),
buffer.begin());
sim_->ExecuteInstruction(
reinterpret_cast<Instruction*>(sim_->get_pc()));
}
} else {
// Otherwise treat it as the mnemonic of the opcode to stop at.
char mnemonic[256];
while (!sim_->has_bad_pc()) {
dasm.InstructionDecode(buffer,
reinterpret_cast<byte*>(sim_->get_pc()));
char* mnemonicStart = buffer.begin();
while (*mnemonicStart != 0 && *mnemonicStart != ' ')
mnemonicStart++;
SScanF(mnemonicStart, "%s", mnemonic);
if (!strcmp(arg1, mnemonic)) break;
PrintF(" 0x%08" V8PRIxPTR " %s\n", sim_->get_pc(),
buffer.begin());
sim_->ExecuteInstruction(
reinterpret_cast<Instruction*>(sim_->get_pc()));
}
}
}
} else if ((strcmp(cmd, "c") == 0) || (strcmp(cmd, "cont") == 0)) {
// If at a breakpoint, proceed past it.
if ((reinterpret_cast<Instruction*>(sim_->get_pc()))
->InstructionBits() == 0x7D821008) {
sim_->set_pc(sim_->get_pc() + sizeof(FourByteInstr));
} else {
// Execute the one instruction we broke at with breakpoints disabled.
sim_->ExecuteInstruction(
reinterpret_cast<Instruction*>(sim_->get_pc()));
}
// Leave the debugger shell.
done = true;
} else if ((strcmp(cmd, "p") == 0) || (strcmp(cmd, "print") == 0)) {
if (argc == 2 || (argc == 3 && strcmp(arg2, "fp") == 0)) {
intptr_t value;
double dvalue;
if (strcmp(arg1, "all") == 0) {
for (int i = 0; i < kNumRegisters; i++) {
value = GetRegisterValue(i);
PrintF(" %3s: %08" V8PRIxPTR,
RegisterName(Register::from_code(i)), value);
if ((argc == 3 && strcmp(arg2, "fp") == 0) && i < 8 &&
(i % 2) == 0) {
dvalue = GetRegisterPairDoubleValue(i);
PrintF(" (%f)\n", dvalue);
} else if (i != 0 && !((i + 1) & 3)) {
PrintF("\n");
}
}
PrintF(" pc: %08" V8PRIxPTR " cr: %08x\n", sim_->special_reg_pc_,
sim_->condition_reg_);
} else if (strcmp(arg1, "alld") == 0) {
for (int i = 0; i < kNumRegisters; i++) {
value = GetRegisterValue(i);
PrintF(" %3s: %08" V8PRIxPTR " %11" V8PRIdPTR,
RegisterName(Register::from_code(i)), value, value);
if ((argc == 3 && strcmp(arg2, "fp") == 0) && i < 8 &&
(i % 2) == 0) {
dvalue = GetRegisterPairDoubleValue(i);
PrintF(" (%f)\n", dvalue);
} else if (!((i + 1) % 2)) {
PrintF("\n");
}
}
PrintF(" pc: %08" V8PRIxPTR " cr: %08x\n", sim_->special_reg_pc_,
sim_->condition_reg_);
} else if (strcmp(arg1, "allf") == 0) {
for (int i = 0; i < DoubleRegister::kNumRegisters; i++) {
float fvalue = GetFPFloatRegisterValue(i);
uint32_t as_words = bit_cast<uint32_t>(fvalue);
PrintF("%3s: %f 0x%08x\n",
RegisterName(DoubleRegister::from_code(i)), fvalue,
as_words);
}
} else if (strcmp(arg1, "alld") == 0) {
for (int i = 0; i < DoubleRegister::kNumRegisters; i++) {
dvalue = GetFPDoubleRegisterValue(i);
uint64_t as_words = bit_cast<uint64_t>(dvalue);
PrintF("%3s: %f 0x%08x %08x\n",
RegisterName(DoubleRegister::from_code(i)), dvalue,
static_cast<uint32_t>(as_words >> 32),
static_cast<uint32_t>(as_words & 0xFFFFFFFF));
}
} else if (arg1[0] == 'r' &&
(arg1[1] >= '0' && arg1[1] <= '2' &&
(arg1[2] == '\0' || (arg1[2] >= '0' && arg1[2] <= '5' &&
arg1[3] == '\0')))) {
int regnum = strtoul(&arg1[1], 0, 10);
if (regnum != kNoRegister) {
value = GetRegisterValue(regnum);
PrintF("%s: 0x%08" V8PRIxPTR " %" V8PRIdPTR "\n", arg1, value,
value);
} else {
PrintF("%s unrecognized\n", arg1);
}
} else {
if (GetValue(arg1, &value)) {
PrintF("%s: 0x%08" V8PRIxPTR " %" V8PRIdPTR "\n", arg1, value,
value);
} else if (GetFPDoubleValue(arg1, &dvalue)) {
uint64_t as_words = bit_cast<uint64_t>(dvalue);
PrintF("%s: %f 0x%08x %08x\n", arg1, dvalue,
static_cast<uint32_t>(as_words >> 32),
static_cast<uint32_t>(as_words & 0xFFFFFFFF));
} else {
PrintF("%s unrecognized\n", arg1);
}
}
} else {
PrintF("print <register>\n");
}
} else if ((strcmp(cmd, "po") == 0) ||
(strcmp(cmd, "printobject") == 0)) {
if (argc == 2) {
intptr_t value;
StdoutStream os;
if (GetValue(arg1, &value)) {
Object obj(value);
os << arg1 << ": \n";
#ifdef DEBUG
obj.Print(os);
os << "\n";
#else
os << Brief(obj) << "\n";
#endif
} else {
os << arg1 << " unrecognized\n";
}
} else {
PrintF("printobject <value>\n");
}
} else if (strcmp(cmd, "setpc") == 0) {
intptr_t value;
if (!GetValue(arg1, &value)) {
PrintF("%s unrecognized\n", arg1);
continue;
}
sim_->set_pc(value);
} else if (strcmp(cmd, "stack") == 0 || strcmp(cmd, "mem") == 0) {
intptr_t* cur = nullptr;
intptr_t* end = nullptr;
int next_arg = 1;
if (strcmp(cmd, "stack") == 0) {
cur = reinterpret_cast<intptr_t*>(sim_->get_register(Simulator::sp));
} else { // "mem"
intptr_t value;
if (!GetValue(arg1, &value)) {
PrintF("%s unrecognized\n", arg1);
continue;
}
cur = reinterpret_cast<intptr_t*>(value);
next_arg++;
}
intptr_t words; // likely inaccurate variable name for 64bit
if (argc == next_arg) {
words = 10;
} else {
if (!GetValue(argv[next_arg], &words)) {
words = 10;
}
}
end = cur + words;
while (cur < end) {
PrintF(" 0x%08" V8PRIxPTR ": 0x%08" V8PRIxPTR " %10" V8PRIdPTR,
reinterpret_cast<intptr_t>(cur), *cur, *cur);
Object obj(*cur);
Heap* current_heap = sim_->isolate_->heap();
if (obj.IsSmi()) {
PrintF(" (smi %d)", Smi::ToInt(obj));
} else if (IsValidHeapObject(current_heap, HeapObject::cast(obj))) {
PrintF(" (");
obj.ShortPrint();
PrintF(")");
}
PrintF("\n");
cur++;
}
} else if (strcmp(cmd, "disasm") == 0 || strcmp(cmd, "di") == 0) {
disasm::NameConverter converter;
disasm::Disassembler dasm(converter);
// use a reasonably large buffer
v8::internal::EmbeddedVector<char, 256> buffer;
byte* prev = nullptr;
byte* cur = nullptr;
// Default number of instructions to disassemble.
int32_t numInstructions = 10;
if (argc == 1) {
cur = reinterpret_cast<byte*>(sim_->get_pc());
} else if (argc == 2) {
int regnum = Registers::Number(arg1);
if (regnum != kNoRegister || strncmp(arg1, "0x", 2) == 0) {
// The argument is an address or a register name.
intptr_t value;
if (GetValue(arg1, &value)) {
cur = reinterpret_cast<byte*>(value);
}
} else {
// The argument is the number of instructions.
intptr_t value;
if (GetValue(arg1, &value)) {
cur = reinterpret_cast<byte*>(sim_->get_pc());
// Disassemble <arg1> instructions.
numInstructions = static_cast<int32_t>(value);
}
}
} else {
intptr_t value1;
intptr_t value2;
if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) {
cur = reinterpret_cast<byte*>(value1);
// Disassemble <arg2> instructions.
numInstructions = static_cast<int32_t>(value2);
}
}
while (numInstructions > 0) {
prev = cur;
cur += dasm.InstructionDecode(buffer, cur);
PrintF(" 0x%08" V8PRIxPTR " %s\n", reinterpret_cast<intptr_t>(prev),
buffer.begin());
numInstructions--;
}
} else if (strcmp(cmd, "gdb") == 0) {
PrintF("relinquishing control to gdb\n");
v8::base::OS::DebugBreak();
PrintF("regaining control from gdb\n");
} else if (strcmp(cmd, "break") == 0) {
if (argc == 2) {
intptr_t value;
if (GetValue(arg1, &value)) {
if (!SetBreakpoint(reinterpret_cast<Instruction*>(value))) {
PrintF("setting breakpoint failed\n");
}
} else {
PrintF("%s unrecognized\n", arg1);
}
} else {
PrintF("break <address>\n");
}
} else if (strcmp(cmd, "del") == 0) {
if (!DeleteBreakpoint(nullptr)) {
PrintF("deleting breakpoint failed\n");
}
} else if (strcmp(cmd, "cr") == 0) {
PrintF("Condition reg: %08x\n", sim_->condition_reg_);
} else if (strcmp(cmd, "stop") == 0) {
intptr_t value;
intptr_t stop_pc =
sim_->get_pc() - (sizeof(FourByteInstr) + kPointerSize);
Instruction* stop_instr = reinterpret_cast<Instruction*>(stop_pc);
Instruction* msg_address =
reinterpret_cast<Instruction*>(stop_pc + sizeof(FourByteInstr));
if ((argc == 2) && (strcmp(arg1, "unstop") == 0)) {
// Remove the current stop.
if (sim_->isStopInstruction(stop_instr)) {
stop_instr->SetInstructionBits(kNopInstr);
msg_address->SetInstructionBits(kNopInstr);
} else {
PrintF("Not at debugger stop.\n");
}
} else if (argc == 3) {
// Print information about all/the specified breakpoint(s).
if (strcmp(arg1, "info") == 0) {
if (strcmp(arg2, "all") == 0) {
PrintF("Stop information:\n");
for (uint32_t i = 0; i < sim_->kNumOfWatchedStops; i++) {
sim_->PrintStopInfo(i);
}
} else if (GetValue(arg2, &value)) {
sim_->PrintStopInfo(value);
} else {
PrintF("Unrecognized argument.\n");
}
} else if (strcmp(arg1, "enable") == 0) {
// Enable all/the specified breakpoint(s).
if (strcmp(arg2, "all") == 0) {
for (uint32_t i = 0; i < sim_->kNumOfWatchedStops; i++) {
sim_->EnableStop(i);
}
} else if (GetValue(arg2, &value)) {
sim_->EnableStop(value);
} else {
PrintF("Unrecognized argument.\n");
}
} else if (strcmp(arg1, "disable") == 0) {
// Disable all/the specified breakpoint(s).
if (strcmp(arg2, "all") == 0) {
for (uint32_t i = 0; i < sim_->kNumOfWatchedStops; i++) {
sim_->DisableStop(i);
}
} else if (GetValue(arg2, &value)) {
sim_->DisableStop(value);
} else {
PrintF("Unrecognized argument.\n");
}
}
} else {
PrintF("Wrong usage. Use help command for more information.\n");
}
} else if (strcmp(cmd, "icount") == 0) {
PrintF("%05" PRId64 "\n", sim_->icount_);
} else if ((strcmp(cmd, "t") == 0) || strcmp(cmd, "trace") == 0) {
::v8::internal::FLAG_trace_sim = !::v8::internal::FLAG_trace_sim;
PrintF("Trace of executed instructions is %s\n",
::v8::internal::FLAG_trace_sim ? "on" : "off");
} else if ((strcmp(cmd, "h") == 0) || (strcmp(cmd, "help") == 0)) {
PrintF("cont\n");
PrintF(" continue execution (alias 'c')\n");
PrintF("stepi [num instructions]\n");
PrintF(" step one/num instruction(s) (alias 'si')\n");
PrintF("print <register>\n");
PrintF(" print register content (alias 'p')\n");
PrintF(" use register name 'all' to display all integer registers\n");
PrintF(
" use register name 'alld' to display integer registers "
"with decimal values\n");
PrintF(" use register name 'rN' to display register number 'N'\n");
PrintF(" add argument 'fp' to print register pair double values\n");
PrintF(
" use register name 'allf' to display floating-point "
"registers\n");
PrintF("printobject <register>\n");
PrintF(" print an object from a register (alias 'po')\n");
PrintF("cr\n");
PrintF(" print condition register\n");
PrintF("stack [<num words>]\n");
PrintF(" dump stack content, default dump 10 words)\n");
PrintF("mem <address> [<num words>]\n");
PrintF(" dump memory content, default dump 10 words)\n");
PrintF("disasm [<instructions>]\n");
PrintF("disasm [<address/register>]\n");
PrintF("disasm [[<address/register>] <instructions>]\n");
PrintF(" disassemble code, default is 10 instructions\n");
PrintF(" from pc (alias 'di')\n");
PrintF("gdb\n");
PrintF(" enter gdb\n");
PrintF("break <address>\n");
PrintF(" set a break point on the address\n");
PrintF("del\n");
PrintF(" delete the breakpoint\n");
PrintF("trace (alias 't')\n");
PrintF(" toogle the tracing of all executed statements\n");
PrintF("stop feature:\n");
PrintF(" Description:\n");
PrintF(" Stops are debug instructions inserted by\n");
PrintF(" the Assembler::stop() function.\n");
PrintF(" When hitting a stop, the Simulator will\n");
PrintF(" stop and give control to the S390Debugger.\n");
PrintF(" The first %d stop codes are watched:\n",
Simulator::kNumOfWatchedStops);
PrintF(" - They can be enabled / disabled: the Simulator\n");
PrintF(" will / won't stop when hitting them.\n");
PrintF(" - The Simulator keeps track of how many times they \n");
PrintF(" are met. (See the info command.) Going over a\n");
PrintF(" disabled stop still increases its counter. \n");
PrintF(" Commands:\n");
PrintF(" stop info all/<code> : print infos about number <code>\n");
PrintF(" or all stop(s).\n");
PrintF(" stop enable/disable all/<code> : enables / disables\n");
PrintF(" all or number <code> stop(s)\n");
PrintF(" stop unstop\n");
PrintF(" ignore the stop instruction at the current location\n");
PrintF(" from now on\n");
} else {
PrintF("Unknown command: %s\n", cmd);
}
}
}
// Add all the breakpoints back to stop execution and enter the debugger
// shell when hit.
RedoBreakpoints();
// Restore tracing
::v8::internal::FLAG_trace_sim = trace;
#undef COMMAND_SIZE
#undef ARG_SIZE
#undef STR
#undef XSTR
}
bool Simulator::ICacheMatch(void* one, void* two) {
DCHECK_EQ(reinterpret_cast<intptr_t>(one) & CachePage::kPageMask, 0);
DCHECK_EQ(reinterpret_cast<intptr_t>(two) & CachePage::kPageMask, 0);
return one == two;
}
static uint32_t ICacheHash(void* key) {
return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(key)) >> 2;
}
static bool AllOnOnePage(uintptr_t start, int size) {
intptr_t start_page = (start & ~CachePage::kPageMask);
intptr_t end_page = ((start + size) & ~CachePage::kPageMask);
return start_page == end_page;
}
void Simulator::set_last_debugger_input(char* input) {
DeleteArray(last_debugger_input_);
last_debugger_input_ = input;
}
void Simulator::SetRedirectInstruction(Instruction* instruction) {
// we use TRAP4 here (0xBF22)
#if V8_TARGET_LITTLE_ENDIAN
instruction->SetInstructionBits(0x1000FFB2);
#else
instruction->SetInstructionBits(0xB2FF0000 | kCallRtRedirected);
#endif
}
void Simulator::FlushICache(base::CustomMatcherHashMap* i_cache,
void* start_addr, size_t size) {
intptr_t start = reinterpret_cast<intptr_t>(start_addr);
int intra_line = (start & CachePage::kLineMask);
start -= intra_line;
size += intra_line;
size = ((size - 1) | CachePage::kLineMask) + 1;
int offset = (start & CachePage::kPageMask);
while (!AllOnOnePage(start, size - 1)) {
int bytes_to_flush = CachePage::kPageSize - offset;
FlushOnePage(i_cache, start, bytes_to_flush);
start += bytes_to_flush;
size -= bytes_to_flush;
DCHECK_EQ(0, static_cast<int>(start & CachePage::kPageMask));
offset = 0;
}
if (size != 0) {
FlushOnePage(i_cache, start, size);
}
}
CachePage* Simulator::GetCachePage(base::CustomMatcherHashMap* i_cache,
void* page) {
base::HashMap::Entry* entry = i_cache->LookupOrInsert(page, ICacheHash(page));
if (entry->value == nullptr) {
CachePage* new_page = new CachePage();
entry->value = new_page;
}
return reinterpret_cast<CachePage*>(entry->value);
}
// Flush from start up to and not including start + size.
void Simulator::FlushOnePage(base::CustomMatcherHashMap* i_cache,
intptr_t start, int size) {
DCHECK_LE(size, CachePage::kPageSize);
DCHECK(AllOnOnePage(start, size - 1));
DCHECK_EQ(start & CachePage::kLineMask, 0);
DCHECK_EQ(size & CachePage::kLineMask, 0);
void* page = reinterpret_cast<void*>(start & (~CachePage::kPageMask));
int offset = (start & CachePage::kPageMask);
CachePage* cache_page = GetCachePage(i_cache, page);
char* valid_bytemap = cache_page->ValidityByte(offset);
memset(valid_bytemap, CachePage::LINE_INVALID, size >> CachePage::kLineShift);
}
void Simulator::CheckICache(base::CustomMatcherHashMap* i_cache,
Instruction* instr) {
intptr_t address = reinterpret_cast<intptr_t>(instr);
void* page = reinterpret_cast<void*>(address & (~CachePage::kPageMask));
void* line = reinterpret_cast<void*>(address & (~CachePage::kLineMask));
int offset = (address & CachePage::kPageMask);
CachePage* cache_page = GetCachePage(i_cache, page);
char* cache_valid_byte = cache_page->ValidityByte(offset);
bool cache_hit = (*cache_valid_byte == CachePage::LINE_VALID);
char* cached_line = cache_page->CachedData(offset & ~CachePage::kLineMask);
if (cache_hit) {
// Check that the data in memory matches the contents of the I-cache.
CHECK_EQ(memcmp(reinterpret_cast<void*>(instr),
cache_page->CachedData(offset), sizeof(FourByteInstr)),
0);
} else {
// Cache miss. Load memory into the cache.
memcpy(cached_line, line, CachePage::kLineLength);
*cache_valid_byte = CachePage::LINE_VALID;
}
}
Simulator::EvaluateFuncType Simulator::EvalTable[] = {nullptr};
void Simulator::EvalTableInit() {
for (int i = 0; i < MAX_NUM_OPCODES; i++) {
EvalTable[i] = &Simulator::Evaluate_Unknown;
}
#define S390_SUPPORTED_VECTOR_OPCODE_LIST(V) \
V(vst, VST, 0xE70E) /* type = VRX VECTOR STORE */ \
V(vl, VL, 0xE706) /* type = VRX VECTOR LOAD */ \
V(vlgv, VLGV, 0xE721) /* type = VRS_C VECTOR LOAD GR FROM VR ELEMENT */ \
V(vlvg, VLVG, 0xE722) /* type = VRS_B VECTOR LOAD VR ELEMENT FROM GR */ \
V(vrep, VREP, 0xE74D) /* type = VRI_C VECTOR REPLICATE */ \
V(vlrep, VLREP, 0xE705) /* type = VRX VECTOR LOAD AND REPLICATE */ \
V(vrepi, VREPI, 0xE745) /* type = VRI_A VECTOR REPLICATE IMMEDIATE */ \
V(vlr, VLR, 0xE756) /* type = VRR_A VECTOR LOAD */ \
V(vstef, VSTEF, 0xE70B) /* type = VRX VECTOR STORE ELEMENT (32) */ \
V(vlef, VLEF, 0xE703) /* type = VRX VECTOR LOAD ELEMENT (32) */ \
V(va, VA, 0xE7F3) /* type = VRR_C VECTOR ADD */ \
V(vs, VS, 0xE7F7) /* type = VRR_C VECTOR SUBTRACT */ \
V(vml, VML, 0xE7A2) /* type = VRR_C VECTOR MULTIPLY LOW */ \
V(vsum, VSUM, 0xE764) /* type = VRR_C VECTOR SUM ACROSS WORD */ \
V(vsumg, VSUMG, 0xE765) /* type = VRR_C VECTOR SUM ACROSS DOUBLEWORD */ \
V(vpk, VPK, 0xE794) /* type = VRR_C VECTOR PACK */ \
V(vpks, VPKS, 0xE797) /* type = VRR_B VECTOR PACK SATURATE */ \
V(vpkls, VPKLS, 0xE795) /* type = VRR_B VECTOR PACK LOGICAL SATURATE */ \
V(vupll, VUPLL, 0xE7D4) /* type = VRR_A VECTOR UNPACK LOGICAL LOW */ \
V(vuplh, VUPLH, 0xE7D5) /* type = VRR_A VECTOR UNPACK LOGICAL HIGH */ \
V(vupl, VUPL, 0xE7D6) /* type = VRR_A VECTOR UNPACK LOW */ \
V(vuph, VUPH, 0xE7D7) /* type = VRR_A VECTOR UNPACK HIGH */ \
V(vmnl, VMNL, 0xE7FC) /* type = VRR_C VECTOR MINIMUM LOGICAL */ \
V(vmxl, VMXL, 0xE7FD) /* type = VRR_C VECTOR MAXIMUM LOGICAL */ \
V(vmn, VMN, 0xE7FE) /* type = VRR_C VECTOR MINIMUM */ \
V(vmx, VMX, 0xE7FF) /* type = VRR_C VECTOR MAXIMUM */ \
V(vceq, VCEQ, 0xE7F8) /* type = VRR_B VECTOR COMPARE EQUAL */ \
V(vx, VX, 0xE76D) /* type = VRR_C VECTOR EXCLUSIVE OR */ \
V(vchl, VCHL, 0xE7F9) /* type = VRR_B VECTOR COMPARE HIGH LOGICAL */ \
V(vch, VCH, 0xE7FB) /* type = VRR_B VECTOR COMPARE HIGH */ \
V(vo, VO, 0xE76A) /* type = VRR_C VECTOR OR */ \
V(vn, VN, 0xE768) /* type = VRR_C VECTOR AND */ \
V(vlc, VLC, 0xE7DE) /* type = VRR_A VECTOR LOAD COMPLEMENT */ \
V(vsel, VSEL, 0xE78D) /* type = VRR_E VECTOR SELECT */ \
V(vtm, VTM, 0xE7D8) /* type = VRR_A VECTOR TEST UNDER MASK */ \
V(vesl, VESL, 0xE730) /* type = VRS_A VECTOR ELEMENT SHIFT LEFT */ \
V(vesrl, VESRL, \
0xE738) /* type = VRS_A VECTOR ELEMENT SHIFT RIGHT LOGICAL */ \
V(vesra, VESRA, \
0xE73A) /* type = VRS_A VECTOR ELEMENT SHIFT RIGHT ARITHMETIC */ \
V(vfsq, VFSQ, 0xE7CE) /* type = VRR_A VECTOR FP SQUARE ROOT */ \
V(vfmax, VFMAX, 0xE7EF) /* type = VRR_C VECTOR FP MAXIMUM */ \
V(vfmin, VFMIN, 0xE7EE) /* type = VRR_C VECTOR FP MINIMUM */ \
V(vfce, VFCE, 0xE7E8) /* type = VRR_C VECTOR FP COMPARE EQUAL */ \
V(vfpso, VFPSO, 0xE7CC) /* type = VRR_A VECTOR FP PERFORM SIGN OPERATION */ \
V(vfche, VFCHE, 0xE7EA) /* type = VRR_C VECTOR FP COMPARE HIGH OR EQUAL */ \
V(vfch, VFCH, 0xE7EB) /* type = VRR_C VECTOR FP COMPARE HIGH */ \
V(vfi, VFI, 0xE7C7) /* type = VRR_A VECTOR LOAD FP INTEGER */ \
V(vfs, VFS, 0xE7E2) /* type = VRR_C VECTOR FP SUBTRACT */ \
V(vfa, VFA, 0xE7E3) /* type = VRR_C VECTOR FP ADD */ \
V(vfd, VFD, 0xE7E5) /* type = VRR_C VECTOR FP DIVIDE */ \
V(vfm, VFM, 0xE7E7) /* type = VRR_C VECTOR FP MULTIPLY */
#define CREATE_EVALUATE_TABLE(name, op_name, op_value) \
EvalTable[op_name] = &Simulator::Evaluate_##op_name;
S390_SUPPORTED_VECTOR_OPCODE_LIST(CREATE_EVALUATE_TABLE);
#undef CREATE_EVALUATE_TABLE
EvalTable[DUMY] = &Simulator::Evaluate_DUMY;
EvalTable[BKPT] = &Simulator::Evaluate_BKPT;
EvalTable[SPM] = &Simulator::Evaluate_SPM;
EvalTable[BALR] = &Simulator::Evaluate_BALR;
EvalTable[BCTR] = &Simulator::Evaluate_BCTR;
EvalTable[BCR] = &Simulator::Evaluate_BCR;
EvalTable[SVC] = &Simulator::Evaluate_SVC;
EvalTable[BSM] = &Simulator::Evaluate_BSM;
EvalTable[BASSM] = &Simulator::Evaluate_BASSM;
EvalTable[BASR] = &Simulator::Evaluate_BASR;
EvalTable[MVCL] = &Simulator::Evaluate_MVCL;
EvalTable[CLCL] = &Simulator::Evaluate_CLCL;
EvalTable[LPR] = &Simulator::Evaluate_LPR;
EvalTable[LNR] = &Simulator::Evaluate_LNR;
EvalTable[LTR] = &Simulator::Evaluate_LTR;
EvalTable[LCR] = &Simulator::Evaluate_LCR;
EvalTable[NR] = &Simulator::Evaluate_NR;
EvalTable[CLR] = &Simulator::Evaluate_CLR;
EvalTable[OR] = &Simulator::Evaluate_OR;
EvalTable[XR] = &Simulator::Evaluate_XR;
EvalTable[LR] = &Simulator::Evaluate_LR;
EvalTable[CR] = &Simulator::Evaluate_CR;
EvalTable[AR] = &Simulator::Evaluate_AR;
EvalTable[SR] = &Simulator::Evaluate_SR;
EvalTable[MR] = &Simulator::Evaluate_MR;
EvalTable[DR] = &Simulator::Evaluate_DR;
EvalTable[ALR] = &Simulator::Evaluate_ALR;
EvalTable[SLR] = &Simulator::Evaluate_SLR;
EvalTable[LDR] = &Simulator::Evaluate_LDR;
EvalTable[CDR] = &Simulator::Evaluate_CDR;
EvalTable[LER] = &Simulator::Evaluate_LER;
EvalTable[STH] = &Simulator::Evaluate_STH;
EvalTable[LA] = &Simulator::Evaluate_LA;
EvalTable[STC] = &Simulator::Evaluate_STC;
EvalTable[IC_z] = &Simulator::Evaluate_IC_z;
EvalTable[EX] = &Simulator::Evaluate_EX;
EvalTable[BAL] = &Simulator::Evaluate_BAL;
EvalTable[BCT] = &Simulator::Evaluate_BCT;
EvalTable[BC] = &Simulator::Evaluate_BC;
EvalTable[LH] = &Simulator::Evaluate_LH;
EvalTable[CH] = &Simulator::Evaluate_CH;
EvalTable[AH] = &Simulator::Evaluate_AH;
EvalTable[SH] = &Simulator::Evaluate_SH;
EvalTable[MH] = &Simulator::Evaluate_MH;
EvalTable[BAS] = &Simulator::Evaluate_BAS;
EvalTable[CVD] = &Simulator::Evaluate_CVD;
EvalTable[CVB] = &Simulator::Evaluate_CVB;
EvalTable[ST] = &Simulator::Evaluate_ST;
EvalTable[LAE] = &Simulator::Evaluate_LAE;
EvalTable[N] = &Simulator::Evaluate_N;
EvalTable[CL] = &Simulator::Evaluate_CL;
EvalTable[O] = &Simulator::Evaluate_O;
EvalTable[X] = &Simulator::Evaluate_X;
EvalTable[L] = &Simulator::Evaluate_L;
EvalTable[C] = &Simulator::Evaluate_C;
EvalTable[A] = &Simulator::Evaluate_A;
EvalTable[S] = &Simulator::Evaluate_S;
EvalTable[M] = &Simulator::Evaluate_M;
EvalTable[D] = &Simulator::Evaluate_D;
EvalTable[AL] = &Simulator::Evaluate_AL;
EvalTable[SL] = &Simulator::Evaluate_SL;
EvalTable[STD] = &Simulator::Evaluate_STD;
EvalTable[LD] = &Simulator::Evaluate_LD;
EvalTable[CD] = &Simulator::Evaluate_CD;
EvalTable[STE] = &Simulator::Evaluate_STE;
EvalTable[MS] = &Simulator::Evaluate_MS;
EvalTable[LE] = &Simulator::Evaluate_LE;
EvalTable[BRXH] = &Simulator::Evaluate_BRXH;
EvalTable[BRXLE] = &Simulator::Evaluate_BRXLE;
EvalTable[BXH] = &Simulator::Evaluate_BXH;
EvalTable[BXLE] = &Simulator::Evaluate_BXLE;
EvalTable[SRL] = &Simulator::Evaluate_SRL;
EvalTable[SLL] = &Simulator::Evaluate_SLL;
EvalTable[SRA] = &Simulator::Evaluate_SRA;
EvalTable[SLA] = &Simulator::Evaluate_SLA;
EvalTable[SRDL] = &Simulator::Evaluate_SRDL;
EvalTable[SLDL] = &Simulator::Evaluate_SLDL;
EvalTable[SRDA] = &Simulator::Evaluate_SRDA;
EvalTable[SLDA] = &Simulator::Evaluate_SLDA;
EvalTable[STM] = &Simulator::Evaluate_STM;
EvalTable[TM] = &Simulator::Evaluate_TM;
EvalTable[MVI] = &Simulator::Evaluate_MVI;
EvalTable[TS] = &Simulator::Evaluate_TS;
EvalTable[NI] = &Simulator::Evaluate_NI;
EvalTable[CLI] = &Simulator::Evaluate_CLI;
EvalTable[OI] = &Simulator::Evaluate_OI;
EvalTable[XI] = &Simulator::Evaluate_XI;
EvalTable[LM] = &Simulator::Evaluate_LM;
EvalTable[CS] = &Simulator::Evaluate_CS;
EvalTable[MVCLE] = &Simulator::Evaluate_MVCLE;
EvalTable[CLCLE] = &Simulator::Evaluate_CLCLE;
EvalTable[MC] = &Simulator::Evaluate_MC;
EvalTable[CDS] = &Simulator::Evaluate_CDS;
EvalTable[STCM] = &Simulator::Evaluate_STCM;
EvalTable[ICM] = &Simulator::Evaluate_ICM;
EvalTable[BPRP] = &Simulator::Evaluate_BPRP;
EvalTable[BPP] = &Simulator::Evaluate_BPP;
EvalTable[TRTR] = &Simulator::Evaluate_TRTR;
EvalTable[MVN] = &Simulator::Evaluate_MVN;
EvalTable[MVC] = &Simulator::Evaluate_MVC;
EvalTable[MVZ] = &Simulator::Evaluate_MVZ;
EvalTable[NC] = &Simulator::Evaluate_NC;
EvalTable[CLC] = &Simulator::Evaluate_CLC;
EvalTable[OC] = &Simulator::Evaluate_OC;
EvalTable[XC] = &Simulator::Evaluate_XC;
EvalTable[MVCP] = &Simulator::Evaluate_MVCP;
EvalTable[TR] = &Simulator::Evaluate_TR;
EvalTable[TRT] = &Simulator::Evaluate_TRT;
EvalTable[ED] = &Simulator::Evaluate_ED;
EvalTable[EDMK] = &Simulator::Evaluate_EDMK;
EvalTable[PKU] = &Simulator::Evaluate_PKU;
EvalTable[UNPKU] = &Simulator::Evaluate_UNPKU;
EvalTable[MVCIN] = &Simulator::Evaluate_MVCIN;
EvalTable[PKA] = &Simulator::Evaluate_PKA;
EvalTable[UNPKA] = &Simulator::Evaluate_UNPKA;
EvalTable[PLO] = &Simulator::Evaluate_PLO;
EvalTable[LMD] = &Simulator::Evaluate_LMD;
EvalTable[SRP] = &Simulator::Evaluate_SRP;
EvalTable[MVO] = &Simulator::Evaluate_MVO;
EvalTable[PACK] = &Simulator::Evaluate_PACK;
EvalTable[UNPK] = &Simulator::Evaluate_UNPK;
EvalTable[ZAP] = &Simulator::Evaluate_ZAP;
EvalTable[AP] = &Simulator::Evaluate_AP;
EvalTable[SP] = &Simulator::Evaluate_SP;
EvalTable[MP] = &Simulator::Evaluate_MP;
EvalTable[DP] = &Simulator::Evaluate_DP;
EvalTable[UPT] = &Simulator::Evaluate_UPT;
EvalTable[PFPO] = &Simulator::Evaluate_PFPO;
EvalTable[IIHH] = &Simulator::Evaluate_IIHH;
EvalTable[IIHL] = &Simulator::Evaluate_IIHL;
EvalTable[IILH] = &Simulator::Evaluate_IILH;
EvalTable[IILL] = &Simulator::Evaluate_IILL;
EvalTable[NIHH] = &Simulator::Evaluate_NIHH;
EvalTable[NIHL] = &Simulator::Evaluate_NIHL;
EvalTable[NILH] = &Simulator::Evaluate_NILH;
EvalTable[NILL] = &Simulator::Evaluate_NILL;
EvalTable[OIHH] = &Simulator::Evaluate_OIHH;
EvalTable[OIHL] = &Simulator::Evaluate_OIHL;
EvalTable[OILH] = &Simulator::Evaluate_OILH;
EvalTable[OILL] = &Simulator::Evaluate_OILL;
EvalTable[LLIHH] = &Simulator::Evaluate_LLIHH;
EvalTable[LLIHL] = &Simulator::Evaluate_LLIHL;
EvalTable[LLILH] = &Simulator::Evaluate_LLILH;
EvalTable[LLILL] = &Simulator::Evaluate_LLILL;
EvalTable[TMLH] = &Simulator::Evaluate_TMLH;
EvalTable[TMLL] = &Simulator::Evaluate_TMLL;
EvalTable[TMHH] = &Simulator::Evaluate_TMHH;
EvalTable[TMHL] = &Simulator::Evaluate_TMHL;
EvalTable[BRC] = &Simulator::Evaluate_BRC;
EvalTable[BRAS] = &Simulator::Evaluate_BRAS;
EvalTable[BRCT] = &Simulator::Evaluate_BRCT;
EvalTable[BRCTG] = &Simulator::Evaluate_BRCTG;
EvalTable[LHI] = &Simulator::Evaluate_LHI;
EvalTable[LGHI] = &Simulator::Evaluate_LGHI;
EvalTable[AHI] = &Simulator::Evaluate_AHI;
EvalTable[AGHI] = &Simulator::Evaluate_AGHI;
EvalTable[MHI] = &Simulator::Evaluate_MHI;
EvalTable[MGHI] = &Simulator::Evaluate_MGHI;
EvalTable[CHI] = &Simulator::Evaluate_CHI;
EvalTable[CGHI] = &Simulator::Evaluate_CGHI;
EvalTable[LARL] = &Simulator::Evaluate_LARL;
EvalTable[LGFI] = &Simulator::Evaluate_LGFI;
EvalTable[BRCL] = &Simulator::Evaluate_BRCL;
EvalTable[BRASL] = &Simulator::Evaluate_BRASL;
EvalTable[XIHF] = &Simulator::Evaluate_XIHF;
EvalTable[XILF] = &Simulator::Evaluate_XILF;
EvalTable[IIHF] = &Simulator::Evaluate_IIHF;
EvalTable[IILF] = &Simulator::Evaluate_IILF;
EvalTable[NIHF] = &Simulator::Evaluate_NIHF;
EvalTable[NILF] = &Simulator::Evaluate_NILF;
EvalTable[OIHF] = &Simulator::Evaluate_OIHF;
EvalTable[OILF] = &Simulator::Evaluate_OILF;
EvalTable[LLIHF] = &Simulator::Evaluate_LLIHF;
EvalTable[LLILF] = &Simulator::Evaluate_LLILF;
EvalTable[MSGFI] = &Simulator::Evaluate_MSGFI;
EvalTable[MSFI] = &Simulator::Evaluate_MSFI;
EvalTable[SLGFI] = &Simulator::Evaluate_SLGFI;
EvalTable[SLFI] = &Simulator::Evaluate_SLFI;
EvalTable[AGFI] = &Simulator::Evaluate_AGFI;
EvalTable[AFI] = &Simulator::Evaluate_AFI;
EvalTable[ALGFI] = &Simulator::Evaluate_ALGFI;
EvalTable[ALFI] = &Simulator::Evaluate_ALFI;
EvalTable[CGFI] = &Simulator::Evaluate_CGFI;
EvalTable[CFI] = &Simulator::Evaluate_CFI;
EvalTable[CLGFI] = &Simulator::Evaluate_CLGFI;
EvalTable[CLFI] = &Simulator::Evaluate_CLFI;
EvalTable[LLHRL] = &Simulator::Evaluate_LLHRL;
EvalTable[LGHRL] = &Simulator::Evaluate_LGHRL;
EvalTable[LHRL] = &Simulator::Evaluate_LHRL;
EvalTable[LLGHRL] = &Simulator::Evaluate_LLGHRL;
EvalTable[STHRL] = &Simulator::Evaluate_STHRL;
EvalTable[LGRL] = &Simulator::Evaluate_LGRL;
EvalTable[STGRL] = &Simulator::Evaluate_STGRL;
EvalTable[LGFRL] = &Simulator::Evaluate_LGFRL;
EvalTable[LRL] = &Simulator::Evaluate_LRL;
EvalTable[LLGFRL] = &Simulator::Evaluate_LLGFRL;
EvalTable[STRL] = &Simulator::Evaluate_STRL;
EvalTable[EXRL] = &Simulator::Evaluate_EXRL;
EvalTable[PFDRL] = &Simulator::Evaluate_PFDRL;
EvalTable[CGHRL] = &Simulator::Evaluate_CGHRL;
EvalTable[CHRL] = &Simulator::Evaluate_CHRL;
EvalTable[CGRL] = &Simulator::Evaluate_CGRL;
EvalTable[CGFRL] = &Simulator::Evaluate_CGFRL;
EvalTable[ECTG] = &Simulator::Evaluate_ECTG;
EvalTable[CSST] = &Simulator::Evaluate_CSST;
EvalTable[LPD] = &Simulator::Evaluate_LPD;
EvalTable[LPDG] = &Simulator::Evaluate_LPDG;
EvalTable[BRCTH] = &Simulator::Evaluate_BRCTH;
EvalTable[AIH] = &Simulator::Evaluate_AIH;
EvalTable[ALSIH] = &Simulator::Evaluate_ALSIH;
EvalTable[ALSIHN] = &Simulator::Evaluate_ALSIHN;
EvalTable[CIH] = &Simulator::Evaluate_CIH;
EvalTable[CLIH] = &Simulator::Evaluate_CLIH;
EvalTable[STCK] = &Simulator::Evaluate_STCK;
EvalTable[CFC] = &Simulator::Evaluate_CFC;
EvalTable[IPM] = &Simulator::Evaluate_IPM;
EvalTable[HSCH] = &Simulator::Evaluate_HSCH;
EvalTable[MSCH] = &Simulator::Evaluate_MSCH;
EvalTable[SSCH] = &Simulator::Evaluate_SSCH;
EvalTable[STSCH] = &Simulator::Evaluate_STSCH;
EvalTable[TSCH] = &Simulator::Evaluate_TSCH;
EvalTable[TPI] = &Simulator::Evaluate_TPI;
EvalTable[SAL] = &Simulator::Evaluate_SAL;
EvalTable[RSCH] = &Simulator::Evaluate_RSCH;
EvalTable[STCRW] = &Simulator::Evaluate_STCRW;
EvalTable[STCPS] = &Simulator::Evaluate_STCPS;
EvalTable[RCHP] = &Simulator::Evaluate_RCHP;
EvalTable[SCHM] = &Simulator::Evaluate_SCHM;
EvalTable[CKSM] = &Simulator::Evaluate_CKSM;
EvalTable[SAR] = &Simulator::Evaluate_SAR;
EvalTable[EAR] = &Simulator::Evaluate_EAR;
EvalTable[MSR] = &Simulator::Evaluate_MSR;
EvalTable[MSRKC] = &Simulator::Evaluate_MSRKC;
EvalTable[MVST] = &Simulator::Evaluate_MVST;
EvalTable[CUSE] = &Simulator::Evaluate_CUSE;
EvalTable[SRST] = &Simulator::Evaluate_SRST;
EvalTable[XSCH] = &Simulator::Evaluate_XSCH;
EvalTable[STCKE] = &Simulator::Evaluate_STCKE;
EvalTable[STCKF] = &Simulator::Evaluate_STCKF;
EvalTable[SRNM] = &Simulator::Evaluate_SRNM;
EvalTable[STFPC] = &Simulator::Evaluate_STFPC;
EvalTable[LFPC] = &Simulator::Evaluate_LFPC;
EvalTable[TRE] = &Simulator::Evaluate_TRE;
EvalTable[STFLE] = &Simulator::Evaluate_STFLE;
EvalTable[SRNMB] = &Simulator::Evaluate_SRNMB;
EvalTable[SRNMT] = &Simulator::Evaluate_SRNMT;
EvalTable[LFAS] = &Simulator::Evaluate_LFAS;
EvalTable[PPA] = &Simulator::Evaluate_PPA;
EvalTable[ETND] = &Simulator::Evaluate_ETND;
EvalTable[TEND] = &Simulator::Evaluate_TEND;
EvalTable[NIAI] = &Simulator::Evaluate_NIAI;
EvalTable[TABORT] = &Simulator::Evaluate_TABORT;
EvalTable[TRAP4] = &Simulator::Evaluate_TRAP4;
EvalTable[LPEBR] = &Simulator::Evaluate_LPEBR;
EvalTable[LNEBR] = &Simulator::Evaluate_LNEBR;
EvalTable[LTEBR] = &Simulator::Evaluate_LTEBR;
EvalTable[LCEBR] = &Simulator::Evaluate_LCEBR;
EvalTable[LDEBR] = &Simulator::Evaluate_LDEBR;
EvalTable[LXDBR] = &Simulator::Evaluate_LXDBR;
EvalTable[LXEBR] = &Simulator::Evaluate_LXEBR;
EvalTable[MXDBR] = &Simulator::Evaluate_MXDBR;
EvalTable[KEBR] = &Simulator::Evaluate_KEBR;
EvalTable[CEBR] = &Simulator::Evaluate_CEBR;
EvalTable[AEBR] = &Simulator::Evaluate_AEBR;
EvalTable[SEBR] = &Simulator::Evaluate_SEBR;
EvalTable[MDEBR] = &Simulator::Evaluate_MDEBR;
EvalTable[DEBR] = &Simulator::Evaluate_DEBR;
EvalTable[MAEBR] = &Simulator::Evaluate_MAEBR;
EvalTable[MSEBR] = &Simulator::Evaluate_MSEBR;
EvalTable[LPDBR] = &Simulator::Evaluate_LPDBR;
EvalTable[LNDBR] = &Simulator::Evaluate_LNDBR;
EvalTable[LTDBR] = &Simulator::Evaluate_LTDBR;
EvalTable[LCDBR] = &Simulator::Evaluate_LCDBR;
EvalTable[SQEBR] = &Simulator::Evaluate_SQEBR;
EvalTable[SQDBR] = &Simulator::Evaluate_SQDBR;
EvalTable[SQXBR] = &Simulator::Evaluate_SQXBR;
EvalTable[MEEBR] = &Simulator::Evaluate_MEEBR;
EvalTable[KDBR] = &Simulator::Evaluate_KDBR;
EvalTable[CDBR] = &Simulator::Evaluate_CDBR;
EvalTable[ADBR] = &Simulator::Evaluate_ADBR;
EvalTable[SDBR] = &Simulator::Evaluate_SDBR;
EvalTable[MDBR] = &Simulator::Evaluate_MDBR;
EvalTable[DDBR] = &Simulator::Evaluate_DDBR;
EvalTable[MADBR] = &Simulator::Evaluate_MADBR;
EvalTable[MSDBR] = &Simulator::Evaluate_MSDBR;
EvalTable[LPXBR] = &Simulator::Evaluate_LPXBR;
EvalTable[LNXBR] = &Simulator::Evaluate_LNXBR;
EvalTable[LTXBR] = &Simulator::Evaluate_LTXBR;
EvalTable[LCXBR] = &Simulator::Evaluate_LCXBR;
EvalTable[LEDBRA] = &Simulator::Evaluate_LEDBRA;
EvalTable[LDXBRA] = &Simulator::Evaluate_LDXBRA;
EvalTable[LEXBRA] = &Simulator::Evaluate_LEXBRA;
EvalTable[FIXBRA] = &Simulator::Evaluate_FIXBRA;
EvalTable[KXBR] = &Simulator::Evaluate_KXBR;
EvalTable[CXBR] = &Simulator::Evaluate_CXBR;
EvalTable[AXBR] = &Simulator::Evaluate_AXBR;
EvalTable[SXBR] = &Simulator::Evaluate_SXBR;
EvalTable[MXBR] = &Simulator::Evaluate_MXBR;
EvalTable[DXBR] = &Simulator::Evaluate_DXBR;
EvalTable[TBEDR] = &Simulator::Evaluate_TBEDR;
EvalTable[TBDR] = &Simulator::Evaluate_TBDR;
EvalTable[DIEBR] = &Simulator::Evaluate_DIEBR;
EvalTable[FIEBRA] = &Simulator::Evaluate_FIEBRA;
EvalTable[THDER] = &Simulator::Evaluate_THDER;
EvalTable[THDR] = &Simulator::Evaluate_THDR;
EvalTable[DIDBR] = &Simulator::Evaluate_DIDBR;
EvalTable[FIDBRA] = &Simulator::Evaluate_FIDBRA;
EvalTable[LXR] = &Simulator::Evaluate_LXR;
EvalTable[LPDFR] = &Simulator::Evaluate_LPDFR;
EvalTable[LNDFR] = &Simulator::Evaluate_LNDFR;
EvalTable[LCDFR] = &Simulator::Evaluate_LCDFR;
EvalTable[LZER] = &Simulator::Evaluate_LZER;
EvalTable[LZDR] = &Simulator::Evaluate_LZDR;
EvalTable[LZXR] = &Simulator::Evaluate_LZXR;
EvalTable[SFPC] = &Simulator::Evaluate_SFPC;
EvalTable[SFASR] = &Simulator::Evaluate_SFASR;
EvalTable[EFPC] = &Simulator::Evaluate_EFPC;
EvalTable[CELFBR] = &Simulator::Evaluate_CELFBR;
EvalTable[CDLFBR] = &Simulator::Evaluate_CDLFBR;
EvalTable[CXLFBR] = &Simulator::Evaluate_CXLFBR;
EvalTable[CEFBRA] = &Simulator::Evaluate_CEFBRA;
EvalTable[CDFBRA] = &Simulator::Evaluate_CDFBRA;
EvalTable[CXFBRA] = &Simulator::Evaluate_CXFBRA;
EvalTable[CFEBRA] = &Simulator::Evaluate_CFEBRA;
EvalTable[CFDBRA] = &Simulator::Evaluate_CFDBRA;
EvalTable[CFXBRA] = &Simulator::Evaluate_CFXBRA;
EvalTable[CLFEBR] = &Simulator::Evaluate_CLFEBR;
EvalTable[CLFDBR] = &Simulator::Evaluate_CLFDBR;
EvalTable[CLFXBR] = &Simulator::Evaluate_CLFXBR;
EvalTable[CELGBR] = &Simulator::Evaluate_CELGBR;
EvalTable[CDLGBR] = &Simulator::Evaluate_CDLGBR;
EvalTable[CXLGBR] = &Simulator::Evaluate_CXLGBR;
EvalTable[CEGBRA] = &Simulator::Evaluate_CEGBRA;
EvalTable[CDGBRA] = &Simulator::Evaluate_CDGBRA;
EvalTable[CXGBRA] = &Simulator::Evaluate_CXGBRA;
EvalTable[CGEBRA] = &Simulator::Evaluate_CGEBRA;
EvalTable[CGDBRA] = &Simulator::Evaluate_CGDBRA;
EvalTable[CGXBRA] = &Simulator::Evaluate_CGXBRA;
EvalTable[CLGEBR] = &Simulator::Evaluate_CLGEBR;
EvalTable[CLGDBR] = &Simulator::Evaluate_CLGDBR;
EvalTable[CFER] = &Simulator::Evaluate_CFER;
EvalTable[CFDR] = &Simulator::Evaluate_CFDR;
EvalTable[CFXR] = &Simulator::Evaluate_CFXR;
EvalTable[LDGR] = &Simulator::Evaluate_LDGR;
EvalTable[CGER] = &Simulator::Evaluate_CGER;
EvalTable[CGDR] = &Simulator::Evaluate_CGDR;
EvalTable[CGXR] = &Simulator::Evaluate_CGXR;
EvalTable[LGDR] = &Simulator::Evaluate_LGDR;
EvalTable[MDTRA] = &Simulator::Evaluate_MDTRA;
EvalTable[DDTRA] = &Simulator::Evaluate_DDTRA;
EvalTable[ADTRA] = &Simulator::Evaluate_ADTRA;
EvalTable[SDTRA] = &Simulator::Evaluate_SDTRA;
EvalTable[LDETR] = &Simulator::Evaluate_LDETR;
EvalTable[LEDTR] = &Simulator::Evaluate_LEDTR;
EvalTable[LTDTR] = &Simulator::Evaluate_LTDTR;
EvalTable[FIDTR] = &Simulator::Evaluate_FIDTR;
EvalTable[MXTRA] = &Simulator::Evaluate_MXTRA;
EvalTable[DXTRA] = &Simulator::Evaluate_DXTRA;
EvalTable[AXTRA] = &Simulator::Evaluate_AXTRA;
EvalTable[SXTRA] = &Simulator::Evaluate_SXTRA;
EvalTable[LXDTR] = &Simulator::Evaluate_LXDTR;
EvalTable[LDXTR] = &Simulator::Evaluate_LDXTR;
EvalTable[LTXTR] = &Simulator::Evaluate_LTXTR;
EvalTable[FIXTR] = &Simulator::Evaluate_FIXTR;
EvalTable[KDTR] = &Simulator::Evaluate_KDTR;
EvalTable[CGDTRA] = &Simulator::Evaluate_CGDTRA;
EvalTable[CUDTR] = &Simulator::Evaluate_CUDTR;
EvalTable[CDTR] = &Simulator::Evaluate_CDTR;
EvalTable[EEDTR] = &Simulator::Evaluate_EEDTR;
EvalTable[ESDTR] = &Simulator::Evaluate_ESDTR;
EvalTable[KXTR] = &Simulator::Evaluate_KXTR;
EvalTable[CGXTRA] = &Simulator::Evaluate_CGXTRA;
EvalTable[CUXTR] = &Simulator::Evaluate_CUXTR;
EvalTable[CSXTR] = &Simulator::Evaluate_CSXTR;
EvalTable[CXTR] = &Simulator::Evaluate_CXTR;
EvalTable[EEXTR] = &Simulator::Evaluate_EEXTR;
EvalTable[ESXTR] = &Simulator::Evaluate_ESXTR;
EvalTable[CDGTRA] = &Simulator::Evaluate_CDGTRA;
EvalTable[CDUTR] = &Simulator::Evaluate_CDUTR;
EvalTable[CDSTR] = &Simulator::Evaluate_CDSTR;
EvalTable[CEDTR] = &Simulator::Evaluate_CEDTR;
EvalTable[QADTR] = &Simulator::Evaluate_QADTR;
EvalTable[IEDTR] = &Simulator::Evaluate_IEDTR;
EvalTable[RRDTR] = &Simulator::Evaluate_RRDTR;
EvalTable[CXGTRA] = &Simulator::Evaluate_CXGTRA;
EvalTable[CXUTR] = &Simulator::Evaluate_CXUTR;
EvalTable[CXSTR] = &Simulator::Evaluate_CXSTR;
EvalTable[CEXTR] = &Simulator::Evaluate_CEXTR;
EvalTable[QAXTR] = &Simulator::Evaluate_QAXTR;
EvalTable[IEXTR] = &Simulator::Evaluate_IEXTR;
EvalTable[RRXTR] = &Simulator::Evaluate_RRXTR;
EvalTable[LPGR] = &Simulator::Evaluate_LPGR;
EvalTable[LNGR] = &Simulator::Evaluate_LNGR;
EvalTable[LTGR] = &Simulator::Evaluate_LTGR;
EvalTable[LCGR] = &Simulator::Evaluate_LCGR;
EvalTable[LGR] = &Simulator::Evaluate_LGR;
EvalTable[LGBR] = &Simulator::Evaluate_LGBR;
EvalTable[LGHR] = &Simulator::Evaluate_LGHR;
EvalTable[AGR] = &Simulator::Evaluate_AGR;
EvalTable[SGR] = &Simulator::Evaluate_SGR;
EvalTable[ALGR] = &Simulator::Evaluate_ALGR;
EvalTable[SLGR] = &Simulator::Evaluate_SLGR;
EvalTable[MSGR] = &Simulator::Evaluate_MSGR;
EvalTable[MSGRKC] = &Simulator::Evaluate_MSGRKC;
EvalTable[DSGR] = &Simulator::Evaluate_DSGR;
EvalTable[LRVGR] = &Simulator::Evaluate_LRVGR;
EvalTable[LPGFR] = &Simulator::Evaluate_LPGFR;
EvalTable[LNGFR] = &Simulator::Evaluate_LNGFR;
EvalTable[LTGFR] = &Simulator::Evaluate_LTGFR;
EvalTable[LCGFR] = &Simulator::Evaluate_LCGFR;
EvalTable[LGFR] = &Simulator::Evaluate_LGFR;
EvalTable[LLGFR] = &Simulator::Evaluate_LLGFR;
EvalTable[LLGTR] = &Simulator::Evaluate_LLGTR;
EvalTable[AGFR] = &Simulator::Evaluate_AGFR;
EvalTable[SGFR] = &Simulator::Evaluate_SGFR;
EvalTable[ALGFR] = &Simulator::Evaluate_ALGFR;
EvalTable[SLGFR] = &Simulator::Evaluate_SLGFR;
EvalTable[MSGFR] = &Simulator::Evaluate_MSGFR;
EvalTable[DSGFR] = &Simulator::Evaluate_DSGFR;
EvalTable[KMAC] = &Simulator::Evaluate_KMAC;
EvalTable[LRVR] = &Simulator::Evaluate_LRVR;
EvalTable[CGR] = &Simulator::Evaluate_CGR;
EvalTable[CLGR] = &Simulator::Evaluate_CLGR;
EvalTable[LBR] = &Simulator::Evaluate_LBR;
EvalTable[LHR] = &Simulator::Evaluate_LHR;
EvalTable[KMF] = &Simulator::Evaluate_KMF;
EvalTable[KMO] = &Simulator::Evaluate_KMO;
EvalTable[PCC] = &Simulator::Evaluate_PCC;
EvalTable[KMCTR] = &Simulator::Evaluate_KMCTR;
EvalTable[KM] = &Simulator::Evaluate_KM;
EvalTable[KMC] = &Simulator::Evaluate_KMC;
EvalTable[CGFR] = &Simulator::Evaluate_CGFR;
EvalTable[KIMD] = &Simulator::Evaluate_KIMD;
EvalTable[KLMD] = &Simulator::Evaluate_KLMD;
EvalTable[CFDTR] = &Simulator::Evaluate_CFDTR;
EvalTable[CLGDTR] = &Simulator::Evaluate_CLGDTR;
EvalTable[CLFDTR] = &Simulator::Evaluate_CLFDTR;
EvalTable[BCTGR] = &Simulator::Evaluate_BCTGR;
EvalTable[CFXTR] = &Simulator::Evaluate_CFXTR;
EvalTable[CLFXTR] = &Simulator::Evaluate_CLFXTR;
EvalTable[CDFTR] = &Simulator::Evaluate_CDFTR;
EvalTable[CDLGTR] = &Simulator::Evaluate_CDLGTR;
EvalTable[CDLFTR] = &Simulator::Evaluate_CDLFTR;
EvalTable[CXFTR] = &Simulator::Evaluate_CXFTR;
EvalTable[CXLGTR] = &Simulator::Evaluate_CXLGTR;
EvalTable[CXLFTR] = &Simulator::Evaluate_CXLFTR;
EvalTable[CGRT] = &Simulator::Evaluate_CGRT;
EvalTable[NGR] = &Simulator::Evaluate_NGR;
EvalTable[OGR] = &Simulator::Evaluate_OGR;
EvalTable[XGR] = &Simulator::Evaluate_XGR;
EvalTable[FLOGR] = &Simulator::Evaluate_FLOGR;
EvalTable[LLGCR] = &Simulator::Evaluate_LLGCR;
EvalTable[LLGHR] = &Simulator::Evaluate_LLGHR;
EvalTable[MLGR] = &Simulator::Evaluate_MLGR;
EvalTable[DLGR] = &Simulator::Evaluate_DLGR;
EvalTable[ALCGR] = &Simulator::Evaluate_ALCGR;
EvalTable[SLBGR] = &Simulator::Evaluate_SLBGR;
EvalTable[EPSW] = &Simulator::Evaluate_EPSW;
EvalTable[TRTT] = &Simulator::Evaluate_TRTT;
EvalTable[TRTO] = &Simulator::Evaluate_TRTO;
EvalTable[TROT] = &Simulator::Evaluate_TROT;
EvalTable[TROO] = &Simulator::Evaluate_TROO;
EvalTable[LLCR] = &Simulator::Evaluate_LLCR;
EvalTable[LLHR] = &Simulator::Evaluate_LLHR;
EvalTable[MLR] = &Simulator::Evaluate_MLR;
EvalTable[DLR] = &Simulator::Evaluate_DLR;
EvalTable[ALCR] = &Simulator::Evaluate_ALCR;
EvalTable[SLBR] = &Simulator::Evaluate_SLBR;
EvalTable[CU14] = &Simulator::Evaluate_CU14;
EvalTable[CU24] = &Simulator::Evaluate_CU24;
EvalTable[CU41] = &Simulator::Evaluate_CU41;
EvalTable[CU42] = &Simulator::Evaluate_CU42;
EvalTable[TRTRE] = &Simulator::Evaluate_TRTRE;
EvalTable[SRSTU] = &Simulator::Evaluate_SRSTU;
EvalTable[TRTE] = &Simulator::Evaluate_TRTE;
EvalTable[AHHHR] = &Simulator::Evaluate_AHHHR;
EvalTable[SHHHR] = &Simulator::Evaluate_SHHHR;
EvalTable[ALHHHR] = &Simulator::Evaluate_ALHHHR;
EvalTable[SLHHHR] = &Simulator::Evaluate_SLHHHR;
EvalTable[CHHR] = &Simulator::Evaluate_CHHR;
EvalTable[AHHLR] = &Simulator::Evaluate_AHHLR;
EvalTable[SHHLR] = &Simulator::Evaluate_SHHLR;
EvalTable[ALHHLR] = &Simulator::Evaluate_ALHHLR;
EvalTable[SLHHLR] = &Simulator::Evaluate_SLHHLR;
EvalTable[CHLR] = &Simulator::Evaluate_CHLR;
EvalTable[POPCNT_Z] = &Simulator::Evaluate_POPCNT_Z;
EvalTable[LOCGR] = &Simulator::Evaluate_LOCGR;
EvalTable[NGRK] = &Simulator::Evaluate_NGRK;
EvalTable[OGRK] = &Simulator::Evaluate_OGRK;
EvalTable[XGRK] = &Simulator::Evaluate_XGRK;
EvalTable[AGRK] = &Simulator::Evaluate_AGRK;
EvalTable[SGRK] = &Simulator::Evaluate_SGRK;
EvalTable[ALGRK] = &Simulator::Evaluate_ALGRK;
EvalTable[SLGRK] = &Simulator::Evaluate_SLGRK;
EvalTable[LOCR] = &Simulator::Evaluate_LOCR;
EvalTable[NRK] = &Simulator::Evaluate_NRK;
EvalTable[ORK] = &Simulator::Evaluate_ORK;
EvalTable[XRK] = &Simulator::Evaluate_XRK;
EvalTable[ARK] = &Simulator::Evaluate_ARK;
EvalTable[SRK] = &Simulator::Evaluate_SRK;
EvalTable[ALRK] = &Simulator::Evaluate_ALRK;
EvalTable[SLRK] = &Simulator::Evaluate_SLRK;
EvalTable[LTG] = &Simulator::Evaluate_LTG;
EvalTable[LG] = &Simulator::Evaluate_LG;
EvalTable[CVBY] = &Simulator::Evaluate_CVBY;
EvalTable[AG] = &Simulator::Evaluate_AG;
EvalTable[SG] = &Simulator::Evaluate_SG;
EvalTable[ALG] = &Simulator::Evaluate_ALG;
EvalTable[SLG] = &Simulator::Evaluate_SLG;
EvalTable[MSG] = &Simulator::Evaluate_MSG;
EvalTable[DSG] = &Simulator::Evaluate_DSG;
EvalTable[CVBG] = &Simulator::Evaluate_CVBG;
EvalTable[LRVG] = &Simulator::Evaluate_LRVG;
EvalTable[LT] = &Simulator::Evaluate_LT;
EvalTable[LGF] = &Simulator::Evaluate_LGF;
EvalTable[LGH] = &Simulator::Evaluate_LGH;
EvalTable[LLGF] = &Simulator::Evaluate_LLGF;
EvalTable[LLGT] = &Simulator::Evaluate_LLGT;
EvalTable[AGF] = &Simulator::Evaluate_AGF;
EvalTable[SGF] = &Simulator::Evaluate_SGF;
EvalTable[ALGF] = &Simulator::Evaluate_ALGF;
EvalTable[SLGF] = &Simulator::Evaluate_SLGF;
EvalTable[MSGF] = &Simulator::Evaluate_MSGF;
EvalTable[DSGF] = &Simulator::Evaluate_DSGF;
EvalTable[LRV] = &Simulator::Evaluate_LRV;
EvalTable[LRVH] = &Simulator::Evaluate_LRVH;
EvalTable[CG] = &Simulator::Evaluate_CG;
EvalTable[CLG] = &Simulator::Evaluate_CLG;
EvalTable[STG] = &Simulator::Evaluate_STG;
EvalTable[NTSTG] = &Simulator::Evaluate_NTSTG;
EvalTable[CVDY] = &Simulator::Evaluate_CVDY;
EvalTable[CVDG] = &Simulator::Evaluate_CVDG;
EvalTable[STRVG] = &Simulator::Evaluate_STRVG;
EvalTable[CGF] = &Simulator::Evaluate_CGF;
EvalTable[CLGF] = &Simulator::Evaluate_CLGF;
EvalTable[LTGF] = &Simulator::Evaluate_LTGF;
EvalTable[CGH] = &Simulator::Evaluate_CGH;
EvalTable[PFD] = &Simulator::Evaluate_PFD;
EvalTable[STRV] = &Simulator::Evaluate_STRV;
EvalTable[STRVH] = &Simulator::Evaluate_STRVH;
EvalTable[BCTG] = &Simulator::Evaluate_BCTG;
EvalTable[STY] = &Simulator::Evaluate_STY;
EvalTable[MSY] = &Simulator::Evaluate_MSY;
EvalTable[MSC] = &Simulator::Evaluate_MSC;
EvalTable[NY] = &Simulator::Evaluate_NY;
EvalTable[CLY] = &Simulator::Evaluate_CLY;
EvalTable[OY] = &Simulator::Evaluate_OY;
EvalTable[XY] = &Simulator::Evaluate_XY;
EvalTable[LY] = &Simulator::Evaluate_LY;
EvalTable[CY] = &Simulator::Evaluate_CY;
EvalTable[AY] = &Simulator::Evaluate_AY;
EvalTable[SY] = &Simulator::Evaluate_SY;
EvalTable[MFY] = &Simulator::Evaluate_MFY;
EvalTable[ALY] = &Simulator::Evaluate_ALY;
EvalTable[SLY] = &Simulator::Evaluate_SLY;
EvalTable[STHY] = &Simulator::Evaluate_STHY;
EvalTable[LAY] = &Simulator::Evaluate_LAY;
EvalTable[STCY] = &Simulator::Evaluate_STCY;
EvalTable[ICY] = &Simulator::Evaluate_ICY;
EvalTable[LAEY] = &Simulator::Evaluate_LAEY;
EvalTable[LB] = &Simulator::Evaluate_LB;
EvalTable[LGB] = &Simulator::Evaluate_LGB;
EvalTable[LHY] = &Simulator::Evaluate_LHY;
EvalTable[CHY] = &Simulator::Evaluate_CHY;
EvalTable[AHY] = &Simulator::Evaluate_AHY;
EvalTable[SHY] = &Simulator::Evaluate_SHY;
EvalTable[MHY] = &Simulator::Evaluate_MHY;
EvalTable[NG] = &Simulator::Evaluate_NG;
EvalTable[OG] = &Simulator::Evaluate_OG;
EvalTable[XG] = &Simulator::Evaluate_XG;
EvalTable[LGAT] = &Simulator::Evaluate_LGAT;
EvalTable[MLG] = &Simulator::Evaluate_MLG;
EvalTable[DLG] = &Simulator::Evaluate_DLG;
EvalTable[ALCG] = &Simulator::Evaluate_ALCG;
EvalTable[SLBG] = &Simulator::Evaluate_SLBG;
EvalTable[STPQ] = &Simulator::Evaluate_STPQ;
EvalTable[LPQ] = &Simulator::Evaluate_LPQ;
EvalTable[LLGC] = &Simulator::Evaluate_LLGC;
EvalTable[LLGH] = &Simulator::Evaluate_LLGH;
EvalTable[LLC] = &Simulator::Evaluate_LLC;
EvalTable[LLH] = &Simulator::Evaluate_LLH;
EvalTable[ML] = &Simulator::Evaluate_ML;
EvalTable[DL] = &Simulator::Evaluate_DL;
EvalTable[ALC] = &Simulator::Evaluate_ALC;
EvalTable[SLB] = &Simulator::Evaluate_SLB;
EvalTable[LLGTAT] = &Simulator::Evaluate_LLGTAT;
EvalTable[LLGFAT] = &Simulator::Evaluate_LLGFAT;
EvalTable[LAT] = &Simulator::Evaluate_LAT;
EvalTable[LBH] = &Simulator::Evaluate_LBH;
EvalTable[LLCH] = &Simulator::Evaluate_LLCH;
EvalTable[STCH] = &Simulator::Evaluate_STCH;
EvalTable[LHH] = &Simulator::Evaluate_LHH;
EvalTable[LLHH] = &Simulator::Evaluate_LLHH;
EvalTable[STHH] = &Simulator::Evaluate_STHH;
EvalTable[LFHAT] = &Simulator::Evaluate_LFHAT;
EvalTable[LFH] = &Simulator::Evaluate_LFH;
EvalTable[STFH] = &Simulator::Evaluate_STFH;
EvalTable[CHF] = &Simulator::Evaluate_CHF;
EvalTable[MVCDK] = &Simulator::Evaluate_MVCDK;
EvalTable[MVHHI] = &Simulator::Evaluate_MVHHI;
EvalTable[MVGHI] = &Simulator::Evaluate_MVGHI;
EvalTable[MVHI] = &Simulator::Evaluate_MVHI;
EvalTable[CHHSI] = &Simulator::Evaluate_CHHSI;
EvalTable[CGHSI] = &Simulator::Evaluate_CGHSI;
EvalTable[CHSI] = &Simulator::Evaluate_CHSI;
EvalTable[CLFHSI] = &Simulator::Evaluate_CLFHSI;
EvalTable[TBEGIN] = &Simulator::Evaluate_TBEGIN;
EvalTable[TBEGINC] = &Simulator::Evaluate_TBEGINC;
EvalTable[LMG] = &Simulator::Evaluate_LMG;
EvalTable[SRAG] = &Simulator::Evaluate_SRAG;
EvalTable[SLAG] = &Simulator::Evaluate_SLAG;
EvalTable[SRLG] = &Simulator::Evaluate_SRLG;
EvalTable[SLLG] = &Simulator::Evaluate_SLLG;
EvalTable[CSY] = &Simulator::Evaluate_CSY;
EvalTable[CSG] = &Simulator::Evaluate_CSG;
EvalTable[RLLG] = &Simulator::Evaluate_RLLG;
EvalTable[RLL] = &Simulator::Evaluate_RLL;
EvalTable[STMG] = &Simulator::Evaluate_STMG;
EvalTable[STMH] = &Simulator::Evaluate_STMH;
EvalTable[STCMH] = &Simulator::Evaluate_STCMH;
EvalTable[STCMY] = &Simulator::Evaluate_STCMY;
EvalTable[CDSY] = &Simulator::Evaluate_CDSY;
EvalTable[CDSG] = &Simulator::Evaluate_CDSG;
EvalTable[BXHG] = &Simulator::Evaluate_BXHG;
EvalTable[BXLEG] = &Simulator::Evaluate_BXLEG;
EvalTable[ECAG] = &Simulator::Evaluate_ECAG;
EvalTable[TMY] = &Simulator::Evaluate_TMY;
EvalTable[MVIY] = &Simulator::Evaluate_MVIY;
EvalTable[NIY] = &Simulator::Evaluate_NIY;
EvalTable[CLIY] = &Simulator::Evaluate_CLIY;
EvalTable[OIY] = &Simulator::Evaluate_OIY;
EvalTable[XIY] = &Simulator::Evaluate_XIY;
EvalTable[ASI] = &Simulator::Evaluate_ASI;
EvalTable[ALSI] = &Simulator::Evaluate_ALSI;
EvalTable[AGSI] = &Simulator::Evaluate_AGSI;
EvalTable[ALGSI] = &Simulator::Evaluate_ALGSI;
EvalTable[ICMH] = &Simulator::Evaluate_ICMH;
EvalTable[ICMY] = &Simulator::Evaluate_ICMY;
EvalTable[MVCLU] = &Simulator::Evaluate_MVCLU;
EvalTable[CLCLU] = &Simulator::Evaluate_CLCLU;
EvalTable[STMY] = &Simulator::Evaluate_STMY;
EvalTable[LMH] = &Simulator::Evaluate_LMH;
EvalTable[LMY] = &Simulator::Evaluate_LMY;
EvalTable[TP] = &Simulator::Evaluate_TP;
EvalTable[SRAK] = &Simulator::Evaluate_SRAK;
EvalTable[SLAK] = &Simulator::Evaluate_SLAK;
EvalTable[SRLK] = &Simulator::Evaluate_SRLK;
EvalTable[SLLK] = &Simulator::Evaluate_SLLK;
EvalTable[LOCG] = &Simulator::Evaluate_LOCG;
EvalTable[STOCG] = &Simulator::Evaluate_STOCG;
EvalTable[LANG] = &Simulator::Evaluate_LANG;
EvalTable[LAOG] = &Simulator::Evaluate_LAOG;
EvalTable[LAXG] = &Simulator::Evaluate_LAXG;
EvalTable[LAAG] = &Simulator::Evaluate_LAAG;
EvalTable[LAALG] = &Simulator::Evaluate_LAALG;
EvalTable[LOC] = &Simulator::Evaluate_LOC;
EvalTable[STOC] = &Simulator::Evaluate_STOC;
EvalTable[LAN] = &Simulator::Evaluate_LAN;
EvalTable[LAO] = &Simulator::Evaluate_LAO;
EvalTable[LAX] = &Simulator::Evaluate_LAX;
EvalTable[LAA] = &Simulator::Evaluate_LAA;
EvalTable[LAAL] = &Simulator::Evaluate_LAAL;
EvalTable[BRXHG] = &Simulator::Evaluate_BRXHG;
EvalTable[BRXLG] = &Simulator::Evaluate_BRXLG;
EvalTable[RISBLG] = &Simulator::Evaluate_RISBLG;
EvalTable[RNSBG] = &Simulator::Evaluate_RNSBG;
EvalTable[RISBG] = &Simulator::Evaluate_RISBG;
EvalTable[ROSBG] = &Simulator::Evaluate_ROSBG;
EvalTable[RXSBG] = &Simulator::Evaluate_RXSBG;
EvalTable[RISBGN] = &Simulator::Evaluate_RISBGN;
EvalTable[RISBHG] = &Simulator::Evaluate_RISBHG;
EvalTable[CGRJ] = &Simulator::Evaluate_CGRJ;
EvalTable[CGIT] = &Simulator::Evaluate_CGIT;
EvalTable[CIT] = &Simulator::Evaluate_CIT;
EvalTable[CLFIT] = &Simulator::Evaluate_CLFIT;
EvalTable[CGIJ] = &Simulator::Evaluate_CGIJ;
EvalTable[CIJ] = &Simulator::Evaluate_CIJ;
EvalTable[AHIK] = &Simulator::Evaluate_AHIK;
EvalTable[AGHIK] = &Simulator::Evaluate_AGHIK;
EvalTable[ALHSIK] = &Simulator::Evaluate_ALHSIK;
EvalTable[ALGHSIK] = &Simulator::Evaluate_ALGHSIK;
EvalTable[CGRB] = &Simulator::Evaluate_CGRB;
EvalTable[CGIB] = &Simulator::Evaluate_CGIB;
EvalTable[CIB] = &Simulator::Evaluate_CIB;
EvalTable[LDEB] = &Simulator::Evaluate_LDEB;
EvalTable[LXDB] = &Simulator::Evaluate_LXDB;
EvalTable[LXEB] = &Simulator::Evaluate_LXEB;
EvalTable[MXDB] = &Simulator::Evaluate_MXDB;
EvalTable[KEB] = &Simulator::Evaluate_KEB;
EvalTable[CEB] = &Simulator::Evaluate_CEB;
EvalTable[AEB] = &Simulator::Evaluate_AEB;
EvalTable[SEB] = &Simulator::Evaluate_SEB;
EvalTable[MDEB] = &Simulator::Evaluate_MDEB;
EvalTable[DEB] = &Simulator::Evaluate_DEB;
EvalTable[MAEB] = &Simulator::Evaluate_MAEB;
EvalTable[MSEB] = &Simulator::Evaluate_MSEB;
EvalTable[TCEB] = &Simulator::Evaluate_TCEB;
EvalTable[TCDB] = &Simulator::Evaluate_TCDB;
EvalTable[TCXB] = &Simulator::Evaluate_TCXB;
EvalTable[SQEB] = &Simulator::Evaluate_SQEB;
EvalTable[SQDB] = &Simulator::Evaluate_SQDB;
EvalTable[MEEB] = &Simulator::Evaluate_MEEB;
EvalTable[KDB] = &Simulator::Evaluate_KDB;
EvalTable[CDB] = &Simulator::Evaluate_CDB;
EvalTable[ADB] = &Simulator::Evaluate_ADB;
EvalTable[SDB] = &Simulator::Evaluate_SDB;
EvalTable[MDB] = &Simulator::Evaluate_MDB;
EvalTable[DDB] = &Simulator::Evaluate_DDB;
EvalTable[MADB] = &Simulator::Evaluate_MADB;
EvalTable[MSDB] = &Simulator::Evaluate_MSDB;
EvalTable[SLDT] = &Simulator::Evaluate_SLDT;
EvalTable[SRDT] = &Simulator::Evaluate_SRDT;
EvalTable[SLXT] = &Simulator::Evaluate_SLXT;
EvalTable[SRXT] = &Simulator::Evaluate_SRXT;
EvalTable[TDCET] = &Simulator::Evaluate_TDCET;
EvalTable[TDGET] = &Simulator::Evaluate_TDGET;
EvalTable[TDCDT] = &Simulator::Evaluate_TDCDT;
EvalTable[TDGDT] = &Simulator::Evaluate_TDGDT;
EvalTable[TDCXT] = &Simulator::Evaluate_TDCXT;
EvalTable[TDGXT] = &Simulator::Evaluate_TDGXT;
EvalTable[LEY] = &Simulator::Evaluate_LEY;
EvalTable[LDY] = &Simulator::Evaluate_LDY;
EvalTable[STEY] = &Simulator::Evaluate_STEY;
EvalTable[STDY] = &Simulator::Evaluate_STDY;
EvalTable[CZDT] = &Simulator::Evaluate_CZDT;
EvalTable[CZXT] = &Simulator::Evaluate_CZXT;
EvalTable[CDZT] = &Simulator::Evaluate_CDZT;
EvalTable[CXZT] = &Simulator::Evaluate_CXZT;
} // NOLINT
Simulator::Simulator(Isolate* isolate) : isolate_(isolate) {
static base::OnceType once = V8_ONCE_INIT;
base::CallOnce(&once, &Simulator::EvalTableInit);
// Set up simulator support first. Some of this information is needed to
// setup the architecture state.
#if V8_TARGET_ARCH_S390X
size_t stack_size = FLAG_sim_stack_size * KB;
#else
size_t stack_size = MB; // allocate 1MB for stack
#endif
stack_size += 2 * stack_protection_size_;
stack_ = reinterpret_cast<char*>(malloc(stack_size));
pc_modified_ = false;
icount_ = 0;
break_pc_ = nullptr;
break_instr_ = 0;
// make sure our register type can hold exactly 4/8 bytes
#ifdef V8_TARGET_ARCH_S390X
DCHECK_EQ(sizeof(intptr_t), 8);
#else
DCHECK_EQ(sizeof(intptr_t), 4);
#endif
// Set up architecture state.
// All registers are initialized to zero to start with.
for (int i = 0; i < kNumGPRs; i++) {
registers_[i] = 0;
}
condition_reg_ = 0;
special_reg_pc_ = 0;
// Initializing FP registers.
for (int i = 0; i < kNumFPRs; i++) {
set_simd_register_by_lane<double>(i, 0, 0.0);
set_simd_register_by_lane<double>(i, 1, 0.0);
}
// The sp is initialized to point to the bottom (high address) of the
// allocated stack area. To be safe in potential stack underflows we leave
// some buffer below.
registers_[sp] =
reinterpret_cast<intptr_t>(stack_) + stack_size - stack_protection_size_;
last_debugger_input_ = nullptr;
}
Simulator::~Simulator() { free(stack_); }
// Get the active Simulator for the current thread.
Simulator* Simulator::current(Isolate* isolate) {
v8::internal::Isolate::PerIsolateThreadData* isolate_data =
isolate->FindOrAllocatePerThreadDataForThisThread();
DCHECK_NOT_NULL(isolate_data);
Simulator* sim = isolate_data->simulator();
if (sim == nullptr) {
// TODO(146): delete the simulator object when a thread/isolate goes away.
sim = new Simulator(isolate);
isolate_data->set_simulator(sim);
}
return sim;
}
// Sets the register in the architecture state.
void Simulator::set_register(int reg, uint64_t value) {
DCHECK((reg >= 0) && (reg < kNumGPRs));
registers_[reg] = value;
}
// Get the register from the architecture state.
const uint64_t& Simulator::get_register(int reg) const {
DCHECK((reg >= 0) && (reg < kNumGPRs));
return registers_[reg];
}
uint64_t& Simulator::get_register(int reg) {
DCHECK((reg >= 0) && (reg < kNumGPRs));
return registers_[reg];
}
template <typename T>
T Simulator::get_low_register(int reg) const {
DCHECK((reg >= 0) && (reg < kNumGPRs));
// Stupid code added to avoid bug in GCC.
// See: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43949
if (reg >= kNumGPRs) return 0;
// End stupid code.
return static_cast<T>(registers_[reg] & 0xFFFFFFFF);
}
template <typename T>
T Simulator::get_high_register(int reg) const {
DCHECK((reg >= 0) && (reg < kNumGPRs));
// Stupid code added to avoid bug in GCC.
// See: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43949
if (reg >= kNumGPRs) return 0;
// End stupid code.
return static_cast<T>(registers_[reg] >> 32);
}
void Simulator::set_low_register(int reg, uint32_t value) {
uint64_t shifted_val = static_cast<uint64_t>(value);
uint64_t orig_val = static_cast<uint64_t>(registers_[reg]);
uint64_t result = (orig_val >> 32 << 32) | shifted_val;
registers_[reg] = result;
}
void Simulator::set_high_register(int reg, uint32_t value) {
uint64_t shifted_val = static_cast<uint64_t>(value) << 32;
uint64_t orig_val = static_cast<uint64_t>(registers_[reg]);
uint64_t result = (orig_val & 0xFFFFFFFF) | shifted_val;
registers_[reg] = result;
}
double Simulator::get_double_from_register_pair(int reg) {
DCHECK((reg >= 0) && (reg < kNumGPRs) && ((reg % 2) == 0));
double dm_val = 0.0;
#if 0 && !V8_TARGET_ARCH_S390X // doesn't make sense in 64bit mode
// Read the bits from the unsigned integer register_[] array
// into the double precision floating point value and return it.
char buffer[sizeof(fp_registers_[0])];
memcpy(buffer, ®isters_[reg], 2 * sizeof(registers_[0]));
memcpy(&dm_val, buffer, 2 * sizeof(registers_[0]));
#endif
return (dm_val);
}
// Raw access to the PC register.
void Simulator::set_pc(intptr_t value) {
pc_modified_ = true;
special_reg_pc_ = value;
}
bool Simulator::has_bad_pc() const {
return ((special_reg_pc_ == bad_lr) || (special_reg_pc_ == end_sim_pc));
}
// Raw access to the PC register without the special adjustment when reading.
intptr_t Simulator::get_pc() const { return special_reg_pc_; }
// Runtime FP routines take:
// - two double arguments
// - one double argument and zero or one integer arguments.
// All are consructed here from d1, d2 and r2.
void Simulator::GetFpArgs(double* x, double* y, intptr_t* z) {
*x = get_double_from_d_register(0);
*y = get_double_from_d_register(2);
*z = get_register(2);
}
// The return value is in d0.
void Simulator::SetFpResult(const double& result) {
set_d_register_from_double(0, result);
}
void Simulator::TrashCallerSaveRegisters() {
// We don't trash the registers with the return value.
#if 0 // A good idea to trash volatile registers, needs to be done
registers_[2] = 0x50BAD4U;
registers_[3] = 0x50BAD4U;
registers_[12] = 0x50BAD4U;
#endif
}
uint32_t Simulator::ReadWU(intptr_t addr, Instruction* instr) {
uint32_t* ptr = reinterpret_cast<uint32_t*>(addr);
return *ptr;
}
int64_t Simulator::ReadW64(intptr_t addr, Instruction* instr) {
int64_t* ptr = reinterpret_cast<int64_t*>(addr);
return *ptr;
}
int32_t Simulator::ReadW(intptr_t addr, Instruction* instr) {
int32_t* ptr = reinterpret_cast<int32_t*>(addr);
return *ptr;
}
void Simulator::WriteW(intptr_t addr, uint32_t value, Instruction* instr) {
uint32_t* ptr = reinterpret_cast<uint32_t*>(addr);
*ptr = value;
return;
}
void Simulator::WriteW(intptr_t addr, int32_t value, Instruction* instr) {
int32_t* ptr = reinterpret_cast<int32_t*>(addr);
*ptr = value;
return;
}
uint16_t Simulator::ReadHU(intptr_t addr, Instruction* instr) {
uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
return *ptr;
}
int16_t Simulator::ReadH(intptr_t addr, Instruction* instr) {
int16_t* ptr = reinterpret_cast<int16_t*>(addr);
return *ptr;
}
void Simulator::WriteH(intptr_t addr, uint16_t value, Instruction* instr) {
uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
*ptr = value;
return;
}
void Simulator::WriteH(intptr_t addr, int16_t value, Instruction* instr) {
int16_t* ptr = reinterpret_cast<int16_t*>(addr);
*ptr = value;
return;
}
uint8_t Simulator::ReadBU(intptr_t addr) {
uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
return *ptr;
}
int8_t Simulator::ReadB(intptr_t addr) {
int8_t* ptr = reinterpret_cast<int8_t*>(addr);
return *ptr;
}
void Simulator::WriteB(intptr_t addr, uint8_t value) {
uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
*ptr = value;
}
void Simulator::WriteB(intptr_t addr, int8_t value) {
int8_t* ptr = reinterpret_cast<int8_t*>(addr);
*ptr = value;
}
int64_t Simulator::ReadDW(intptr_t addr) {
int64_t* ptr = reinterpret_cast<int64_t*>(addr);
return *ptr;
}
void Simulator::WriteDW(intptr_t addr, int64_t value) {
int64_t* ptr = reinterpret_cast<int64_t*>(addr);
*ptr = value;
return;
}
/**
* Reads a double value from memory at given address.
*/
double Simulator::ReadDouble(intptr_t addr) {
double* ptr = reinterpret_cast<double*>(addr);
return *ptr;
}
float Simulator::ReadFloat(intptr_t addr) {
float* ptr = reinterpret_cast<float*>(addr);
return *ptr;
}
// Returns the limit of the stack area to enable checking for stack overflows.
uintptr_t Simulator::StackLimit(uintptr_t c_limit) const {
// The simulator uses a separate JS stack. If we have exhausted the C stack,
// we also drop down the JS limit to reflect the exhaustion on the JS stack.
if (GetCurrentStackPosition() < c_limit) {
return reinterpret_cast<uintptr_t>(get_sp());
}
// Otherwise the limit is the JS stack. Leave a safety margin to prevent
// overrunning the stack when pushing values.
return reinterpret_cast<uintptr_t>(stack_) + stack_protection_size_;
}
// Unsupported instructions use Format to print an error and stop execution.
void Simulator::Format(Instruction* instr, const char* format) {
PrintF("Simulator found unsupported instruction:\n 0x%08" V8PRIxPTR ": %s\n",
reinterpret_cast<intptr_t>(instr), format);
UNIMPLEMENTED();
}
// Calculate C flag value for additions.
bool Simulator::CarryFrom(int32_t left, int32_t right, int32_t carry) {
uint32_t uleft = static_cast<uint32_t>(left);
uint32_t uright = static_cast<uint32_t>(right);
uint32_t urest = 0xFFFFFFFFU - uleft;
return (uright > urest) ||
(carry && (((uright + 1) > urest) || (uright > (urest - 1))));
}
// Calculate C flag value for subtractions.
bool Simulator::BorrowFrom(int32_t left, int32_t right) {
uint32_t uleft = static_cast<uint32_t>(left);
uint32_t uright = static_cast<uint32_t>(right);
return (uright > uleft);
}
// Calculate V flag value for additions and subtractions.
template <typename T1>
bool Simulator::OverflowFromSigned(T1 alu_out, T1 left, T1 right,
bool addition) {
bool overflow;
if (addition) {
// operands have the same sign
overflow = ((left >= 0 && right >= 0) || (left < 0 && right < 0))
// and operands and result have different sign
&& ((left < 0 && alu_out >= 0) || (left >= 0 && alu_out < 0));
} else {
// operands have different signs
overflow = ((left < 0 && right >= 0) || (left >= 0 && right < 0))
// and first operand and result have different signs
&& ((left < 0 && alu_out >= 0) || (left >= 0 && alu_out < 0));
}
return overflow;
}
static void decodeObjectPair(ObjectPair* pair, intptr_t* x, intptr_t* y) {
*x = static_cast<intptr_t>(pair->x);
*y = static_cast<intptr_t>(pair->y);
}
// Calls into the V8 runtime.
using SimulatorRuntimeCall = intptr_t (*)(intptr_t arg0, intptr_t arg1,
intptr_t arg2, intptr_t arg3,
intptr_t arg4, intptr_t arg5,
intptr_t arg6, intptr_t arg7,
intptr_t arg8, intptr_t arg9);
using SimulatorRuntimePairCall = ObjectPair (*)(intptr_t arg0, intptr_t arg1,
intptr_t arg2, intptr_t arg3,
intptr_t arg4, intptr_t arg5,
intptr_t arg6, intptr_t arg7,
intptr_t arg8, intptr_t arg9);
// These prototypes handle the four types of FP calls.
using SimulatorRuntimeCompareCall = int (*)(double darg0, double darg1);
using SimulatorRuntimeFPFPCall = double (*)(double darg0, double darg1);
using SimulatorRuntimeFPCall = double (*)(double darg0);
using SimulatorRuntimeFPIntCall = double (*)(double darg0, intptr_t arg0);
// This signature supports direct call in to API function native callback
// (refer to InvocationCallback in v8.h).
using SimulatorRuntimeDirectApiCall = void (*)(intptr_t arg0);
using SimulatorRuntimeProfilingApiCall = void (*)(intptr_t arg0, void* arg1);
// This signature supports direct call to accessor getter callback.
using SimulatorRuntimeDirectGetterCall = void (*)(intptr_t arg0, intptr_t arg1);
using SimulatorRuntimeProfilingGetterCall = void (*)(intptr_t arg0,
intptr_t arg1, void* arg2);
// Software interrupt instructions are used by the simulator to call into the
// C-based V8 runtime.
void Simulator::SoftwareInterrupt(Instruction* instr) {
int svc = instr->SvcValue();
switch (svc) {
case kCallRtRedirected: {
// Check if stack is aligned. Error if not aligned is reported below to
// include information on the function called.
bool stack_aligned =
(get_register(sp) & (::v8::internal::FLAG_sim_stack_alignment - 1)) ==
0;
Redirection* redirection = Redirection::FromInstruction(instr);
const int kArgCount = 10;
const int kRegisterArgCount = 5;
int arg0_regnum = 2;
intptr_t result_buffer = 0;
bool uses_result_buffer =
redirection->type() == ExternalReference::BUILTIN_CALL_PAIR &&
!ABI_RETURNS_OBJECTPAIR_IN_REGS;
if (uses_result_buffer) {
result_buffer = get_register(r2);
arg0_regnum++;
}
intptr_t arg[kArgCount];
// First 5 arguments in registers r2-r6.
for (int i = 0; i < kRegisterArgCount; i++) {
arg[i] = get_register(arg0_regnum + i);
}
// Remaining arguments on stack
intptr_t* stack_pointer = reinterpret_cast<intptr_t*>(get_register(sp));
for (int i = kRegisterArgCount; i < kArgCount; i++) {
arg[i] = stack_pointer[(kCalleeRegisterSaveAreaSize / kPointerSize) +
(i - kRegisterArgCount)];
}
STATIC_ASSERT(kArgCount == kRegisterArgCount + 5);
STATIC_ASSERT(kMaxCParameters == kArgCount);
bool fp_call =
(redirection->type() == ExternalReference::BUILTIN_FP_FP_CALL) ||
(redirection->type() == ExternalReference::BUILTIN_COMPARE_CALL) ||
(redirection->type() == ExternalReference::BUILTIN_FP_CALL) ||
(redirection->type() == ExternalReference::BUILTIN_FP_INT_CALL);
// Place the return address on the stack, making the call GC safe.
*reinterpret_cast<intptr_t*>(get_register(sp) +
kStackFrameRASlot * kPointerSize) =
get_register(r14);
intptr_t external =
reinterpret_cast<intptr_t>(redirection->external_function());
if (fp_call) {
double dval0, dval1; // one or two double parameters
intptr_t ival; // zero or one integer parameters
int iresult = 0; // integer return value
double dresult = 0; // double return value
GetFpArgs(&dval0, &dval1, &ival);
if (::v8::internal::FLAG_trace_sim || !stack_aligned) {
SimulatorRuntimeCall generic_target =
reinterpret_cast<SimulatorRuntimeCall>(external);
switch (redirection->type()) {
case ExternalReference::BUILTIN_FP_FP_CALL:
case ExternalReference::BUILTIN_COMPARE_CALL:
PrintF("Call to host function at %p with args %f, %f",
reinterpret_cast<void*>(FUNCTION_ADDR(generic_target)),
dval0, dval1);
break;
case ExternalReference::BUILTIN_FP_CALL:
PrintF("Call to host function at %p with arg %f",
reinterpret_cast<void*>(FUNCTION_ADDR(generic_target)),
dval0);
break;
case ExternalReference::BUILTIN_FP_INT_CALL:
PrintF("Call to host function at %p with args %f, %" V8PRIdPTR,
reinterpret_cast<void*>(FUNCTION_ADDR(generic_target)),
dval0, ival);
break;
default:
UNREACHABLE();
break;
}
if (!stack_aligned) {
PrintF(" with unaligned stack %08" V8PRIxPTR "\n",
static_cast<intptr_t>(get_register(sp)));
}
PrintF("\n");
}
CHECK(stack_aligned);
switch (redirection->type()) {
case ExternalReference::BUILTIN_COMPARE_CALL: {
SimulatorRuntimeCompareCall target =
reinterpret_cast<SimulatorRuntimeCompareCall>(external);
iresult = target(dval0, dval1);
set_register(r2, iresult);
break;
}
case ExternalReference::BUILTIN_FP_FP_CALL: {
SimulatorRuntimeFPFPCall target =
reinterpret_cast<SimulatorRuntimeFPFPCall>(external);
dresult = target(dval0, dval1);
SetFpResult(dresult);
break;
}
case ExternalReference::BUILTIN_FP_CALL: {
SimulatorRuntimeFPCall target =
reinterpret_cast<SimulatorRuntimeFPCall>(external);
dresult = target(dval0);
SetFpResult(dresult);
break;
}
case ExternalReference::BUILTIN_FP_INT_CALL: {
SimulatorRuntimeFPIntCall target =
reinterpret_cast<SimulatorRuntimeFPIntCall>(external);
dresult = target(dval0, ival);
SetFpResult(dresult);
break;
}
default:
UNREACHABLE();
break;
}
if (::v8::internal::FLAG_trace_sim || !stack_aligned) {
switch (redirection->type()) {
case ExternalReference::BUILTIN_COMPARE_CALL:
PrintF("Returned %08x\n", iresult);
break;
case ExternalReference::BUILTIN_FP_FP_CALL:
case ExternalReference::BUILTIN_FP_CALL:
case ExternalReference::BUILTIN_FP_INT_CALL:
PrintF("Returned %f\n", dresult);
break;
default:
UNREACHABLE();
break;
}
}
} else if (redirection->type() == ExternalReference::DIRECT_API_CALL) {
// See callers of MacroAssembler::CallApiFunctionAndReturn for
// explanation of register usage.
if (::v8::internal::FLAG_trace_sim || !stack_aligned) {
PrintF("Call to host function at %p args %08" V8PRIxPTR,
reinterpret_cast<void*>(external), arg[0]);
if (!stack_aligned) {
PrintF(" with unaligned stack %08" V8PRIxPTR "\n",
static_cast<intptr_t>(get_register(sp)));
}
PrintF("\n");
}
CHECK(stack_aligned);
SimulatorRuntimeDirectApiCall target =
reinterpret_cast<SimulatorRuntimeDirectApiCall>(external);
target(arg[0]);
} else if (redirection->type() == ExternalReference::PROFILING_API_CALL) {
// See callers of MacroAssembler::CallApiFunctionAndReturn for
// explanation of register usage.
if (::v8::internal::FLAG_trace_sim || !stack_aligned) {
PrintF("Call to host function at %p args %08" V8PRIxPTR
" %08" V8PRIxPTR,
reinterpret_cast<void*>(external), arg[0], arg[1]);
if (!stack_aligned) {
PrintF(" with unaligned stack %08" V8PRIxPTR "\n",
static_cast<intptr_t>(get_register(sp)));
}
PrintF("\n");
}
CHECK(stack_aligned);
SimulatorRuntimeProfilingApiCall target =
reinterpret_cast<SimulatorRuntimeProfilingApiCall>(external);
target(arg[0], Redirection::ReverseRedirection(arg[1]));
} else if (redirection->type() == ExternalReference::DIRECT_GETTER_CALL) {
// See callers of MacroAssembler::CallApiFunctionAndReturn for
// explanation of register usage.
if (::v8::internal::FLAG_trace_sim || !stack_aligned) {
PrintF("Call to host function at %p args %08" V8PRIxPTR
" %08" V8PRIxPTR,
reinterpret_cast<void*>(external), arg[0], arg[1]);
if (!stack_aligned) {
PrintF(" with unaligned stack %08" V8PRIxPTR "\n",
static_cast<intptr_t>(get_register(sp)));
}
PrintF("\n");
}
CHECK(stack_aligned);
SimulatorRuntimeDirectGetterCall target =
reinterpret_cast<SimulatorRuntimeDirectGetterCall>(external);
if (!ABI_PASSES_HANDLES_IN_REGS) {
arg[0] = *(reinterpret_cast<intptr_t*>(arg[0]));
}
target(arg[0], arg[1]);
} else if (redirection->type() ==
ExternalReference::PROFILING_GETTER_CALL) {
if (::v8::internal::FLAG_trace_sim || !stack_aligned) {
PrintF("Call to host function at %p args %08" V8PRIxPTR
" %08" V8PRIxPTR " %08" V8PRIxPTR,
reinterpret_cast<void*>(external), arg[0], arg[1], arg[2]);
if (!stack_aligned) {
PrintF(" with unaligned stack %08" V8PRIxPTR "\n",
static_cast<intptr_t>(get_register(sp)));
}
PrintF("\n");
}
CHECK(stack_aligned);
SimulatorRuntimeProfilingGetterCall target =
reinterpret_cast<SimulatorRuntimeProfilingGetterCall>(external);
if (!ABI_PASSES_HANDLES_IN_REGS) {
arg[0] = *(reinterpret_cast<intptr_t*>(arg[0]));
}
target(arg[0], arg[1], Redirection::ReverseRedirection(arg[2]));
} else {
// builtin call.
if (::v8::internal::FLAG_trace_sim || !stack_aligned) {
SimulatorRuntimeCall target =
reinterpret_cast<SimulatorRuntimeCall>(external);
PrintF(
"Call to host function at %p,\n"
"\t\t\t\targs %08" V8PRIxPTR ", %08" V8PRIxPTR ", %08" V8PRIxPTR
", %08" V8PRIxPTR ", %08" V8PRIxPTR ", %08" V8PRIxPTR
", %08" V8PRIxPTR ", %08" V8PRIxPTR ", %08" V8PRIxPTR
", %08" V8PRIxPTR,
reinterpret_cast<void*>(FUNCTION_ADDR(target)), arg[0], arg[1],
arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9]);
if (!stack_aligned) {
PrintF(" with unaligned stack %08" V8PRIxPTR "\n",
static_cast<intptr_t>(get_register(sp)));
}
PrintF("\n");
}
CHECK(stack_aligned);
if (redirection->type() == ExternalReference::BUILTIN_CALL_PAIR) {
SimulatorRuntimePairCall target =
reinterpret_cast<SimulatorRuntimePairCall>(external);
ObjectPair result = target(arg[0], arg[1], arg[2], arg[3], arg[4],
arg[5], arg[6], arg[7], arg[8], arg[9]);
intptr_t x;
intptr_t y;
decodeObjectPair(&result, &x, &y);
if (::v8::internal::FLAG_trace_sim) {
PrintF("Returned {%08" V8PRIxPTR ", %08" V8PRIxPTR "}\n", x, y);
}
if (ABI_RETURNS_OBJECTPAIR_IN_REGS) {
set_register(r2, x);
set_register(r3, y);
} else {
memcpy(reinterpret_cast<void*>(result_buffer), &result,
sizeof(ObjectPair));
set_register(r2, result_buffer);
}
} else {
DCHECK(redirection->type() == ExternalReference::BUILTIN_CALL);
SimulatorRuntimeCall target =
reinterpret_cast<SimulatorRuntimeCall>(external);
intptr_t result = target(arg[0], arg[1], arg[2], arg[3], arg[4],
arg[5], arg[6], arg[7], arg[8], arg[9]);
if (::v8::internal::FLAG_trace_sim) {
PrintF("Returned %08" V8PRIxPTR "\n", result);
}
set_register(r2, result);
}
// #if !V8_TARGET_ARCH_S390X
// DCHECK(redirection->type() ==
// ExternalReference::BUILTIN_CALL);
// SimulatorRuntimeCall target =
// reinterpret_cast<SimulatorRuntimeCall>(external);
// int64_t result = target(arg[0], arg[1], arg[2], arg[3],
// arg[4],
// arg[5]);
// int32_t lo_res = static_cast<int32_t>(result);
// int32_t hi_res = static_cast<int32_t>(result >> 32);
// #if !V8_TARGET_LITTLE_ENDIAN
// if (::v8::internal::FLAG_trace_sim) {
// PrintF("Returned %08x\n", hi_res);
// }
// set_register(r2, hi_res);
// set_register(r3, lo_res);
// #else
// if (::v8::internal::FLAG_trace_sim) {
// PrintF("Returned %08x\n", lo_res);
// }
// set_register(r2, lo_res);
// set_register(r3, hi_res);
// #endif
// #else
// if (redirection->type() == ExternalReference::BUILTIN_CALL) {
// SimulatorRuntimeCall target =
// reinterpret_cast<SimulatorRuntimeCall>(external);
// intptr_t result = target(arg[0], arg[1], arg[2], arg[3],
// arg[4],
// arg[5]);
// if (::v8::internal::FLAG_trace_sim) {
// PrintF("Returned %08" V8PRIxPTR "\n", result);
// }
// set_register(r2, result);
// } else {
// DCHECK(redirection->type() ==
// ExternalReference::BUILTIN_CALL_PAIR);
// SimulatorRuntimePairCall target =
// reinterpret_cast<SimulatorRuntimePairCall>(external);
// ObjectPair result = target(arg[0], arg[1], arg[2], arg[3],
// arg[4], arg[5]);
// if (::v8::internal::FLAG_trace_sim) {
// PrintF("Returned %08" V8PRIxPTR ", %08" V8PRIxPTR "\n",
// result.x, result.y);
// }
// #if ABI_RETURNS_OBJECTPAIR_IN_REGS
// set_register(r2, result.x);
// set_register(r3, result.y);
// #else
// memcpy(reinterpret_cast<void *>(result_buffer), &result,
// sizeof(ObjectPair));
// #endif
// }
// #endif
}
int64_t saved_lr = *reinterpret_cast<intptr_t*>(
get_register(sp) + kStackFrameRASlot * kPointerSize);
#if (!V8_TARGET_ARCH_S390X && V8_HOST_ARCH_S390)
// On zLinux-31, the saved_lr might be tagged with a high bit of 1.
// Cleanse it before proceeding with simulation.
saved_lr &= 0x7FFFFFFF;
#endif
set_pc(saved_lr);
break;
}
case kBreakpoint: {
S390Debugger dbg(this);
dbg.Debug();
break;
}
// stop uses all codes greater than 1 << 23.
default: {
if (svc >= (1 << 23)) {
uint32_t code = svc & kStopCodeMask;
if (isWatchedStop(code)) {
IncreaseStopCounter(code);
}
// Stop if it is enabled, otherwise go on jumping over the stop
// and the message address.
if (isEnabledStop(code)) {
S390Debugger dbg(this);
dbg.Stop(instr);
} else {
set_pc(get_pc() + sizeof(FourByteInstr) + kPointerSize);
}
} else {
// This is not a valid svc code.
UNREACHABLE();
break;
}
}
}
}
// Stop helper functions.
bool Simulator::isStopInstruction(Instruction* instr) {
return (instr->Bits(27, 24) == 0xF) && (instr->SvcValue() >= kStopCode);
}
bool Simulator::isWatchedStop(uint32_t code) {
DCHECK_LE(code, kMaxStopCode);
return code < kNumOfWatchedStops;
}
bool Simulator::isEnabledStop(uint32_t code) {
DCHECK_LE(code, kMaxStopCode);
// Unwatched stops are always enabled.
return !isWatchedStop(code) ||
!(watched_stops_[code].count & kStopDisabledBit);
}
void Simulator::EnableStop(uint32_t code) {
DCHECK(isWatchedStop(code));
if (!isEnabledStop(code)) {
watched_stops_[code].count &= ~kStopDisabledBit;
}
}
void Simulator::DisableStop(uint32_t code) {
DCHECK(isWatchedStop(code));
if (isEnabledStop(code)) {
watched_stops_[code].count |= kStopDisabledBit;
}
}
void Simulator::IncreaseStopCounter(uint32_t code) {
DCHECK_LE(code, kMaxStopCode);
DCHECK(isWatchedStop(code));
if ((watched_stops_[code].count & ~(1 << 31)) == 0x7FFFFFFF) {
PrintF(
"Stop counter for code %i has overflowed.\n"
"Enabling this code and reseting the counter to 0.\n",
code);
watched_stops_[code].count = 0;
EnableStop(code);
} else {
watched_stops_[code].count++;
}
}
// Print a stop status.
void Simulator::PrintStopInfo(uint32_t code) {
DCHECK_LE(code, kMaxStopCode);
if (!isWatchedStop(code)) {
PrintF("Stop not watched.");
} else {
const char* state = isEnabledStop(code) ? "Enabled" : "Disabled";
int32_t count = watched_stops_[code].count & ~kStopDisabledBit;
// Don't print the state of unused breakpoints.
if (count != 0) {
if (watched_stops_[code].desc) {
PrintF("stop %i - 0x%x: \t%s, \tcounter = %i, \t%s\n", code, code,
state, count, watched_stops_[code].desc);
} else {
PrintF("stop %i - 0x%x: \t%s, \tcounter = %i\n", code, code, state,
count);
}
}
}
}
// Method for checking overflow on signed addition:
// Test src1 and src2 have opposite sign,
// (1) No overflow if they have opposite sign
// (2) Test the result and one of the operands have opposite sign
// (a) No overflow if they don't have opposite sign
// (b) Overflow if opposite
#define CheckOverflowForIntAdd(src1, src2, type) \
OverflowFromSigned<type>(src1 + src2, src1, src2, true);
#define CheckOverflowForIntSub(src1, src2, type) \
OverflowFromSigned<type>(src1 - src2, src1, src2, false);
// Method for checking overflow on unsigned addition
#define CheckOverflowForUIntAdd(src1, src2) \
((src1) + (src2) < (src1) || (src1) + (src2) < (src2))
// Method for checking overflow on unsigned subtraction
#define CheckOverflowForUIntSub(src1, src2) ((src1) - (src2) > (src1))
// Method for checking overflow on multiplication
#define CheckOverflowForMul(src1, src2) (((src1) * (src2)) / (src2) != (src1))
// Method for checking overflow on shift right
#define CheckOverflowForShiftRight(src1, src2) \
(((src1) >> (src2)) << (src2) != (src1))
// Method for checking overflow on shift left
#define CheckOverflowForShiftLeft(src1, src2) \
(((src1) << (src2)) >> (src2) != (src1))
int16_t Simulator::ByteReverse(int16_t hword) {
#if defined(__GNUC__)
return __builtin_bswap16(hword);
#else
return (hword << 8) | ((hword >> 8) & 0x00FF);
#endif
}
int32_t Simulator::ByteReverse(int32_t word) {
#if defined(__GNUC__)
return __builtin_bswap32(word);
#else
int32_t result = word << 24;
result |= (word << 8) & 0x00FF0000;
result |= (word >> 8) & 0x0000FF00;
result |= (word >> 24) & 0x00000FF;
return result;
#endif
}
int64_t Simulator::ByteReverse(int64_t dword) {
#if defined(__GNUC__)
return __builtin_bswap64(dword);
#else
#error unsupport __builtin_bswap64
#endif
}
int Simulator::DecodeInstruction(Instruction* instr) {
Opcode op = instr->S390OpcodeValue();
DCHECK_NOT_NULL(EvalTable[op]);
return (this->*EvalTable[op])(instr);
}
// Executes the current instruction.
void Simulator::ExecuteInstruction(Instruction* instr, bool auto_incr_pc) {
icount_++;
if (v8::internal::FLAG_check_icache) {
CheckICache(i_cache(), instr);
}
pc_modified_ = false;
if (::v8::internal::FLAG_trace_sim) {
disasm::NameConverter converter;
disasm::Disassembler dasm(converter);
// use a reasonably large buffer
v8::internal::EmbeddedVector<char, 256> buffer;
dasm.InstructionDecode(buffer, reinterpret_cast<byte*>(instr));
PrintF("%05" PRId64 " %08" V8PRIxPTR " %s\n", icount_,
reinterpret_cast<intptr_t>(instr), buffer.begin());
// Flush stdout to prevent incomplete file output during abnormal exits
// This is caused by the output being buffered before being written to file
fflush(stdout);
}
// Try to simulate as S390 Instruction first.
int length = DecodeInstruction(instr);
if (!pc_modified_ && auto_incr_pc) {
DCHECK(length == instr->InstructionLength());
set_pc(reinterpret_cast<intptr_t>(instr) + length);
}
return;
}
void Simulator::DebugStart() {
S390Debugger dbg(this);
dbg.Debug();
}
void Simulator::Execute() {
// Get the PC to simulate. Cannot use the accessor here as we need the
// raw PC value and not the one used as input to arithmetic instructions.
intptr_t program_counter = get_pc();
if (::v8::internal::FLAG_stop_sim_at == 0) {
// Fast version of the dispatch loop without checking whether the simulator
// should be stopping at a particular executed instruction.
while (program_counter != end_sim_pc) {
Instruction* instr = reinterpret_cast<Instruction*>(program_counter);
ExecuteInstruction(instr);
program_counter = get_pc();
}
} else {
// FLAG_stop_sim_at is at the non-default value. Stop in the debugger when
// we reach the particular instruction count.
while (program_counter != end_sim_pc) {
Instruction* instr = reinterpret_cast<Instruction*>(program_counter);
if (icount_ == ::v8::internal::FLAG_stop_sim_at) {
S390Debugger dbg(this);
dbg.Debug();
} else {
ExecuteInstruction(instr);
}
program_counter = get_pc();
}
}
}
void Simulator::CallInternal(Address entry, int reg_arg_count) {
// Adjust JS-based stack limit to C-based stack limit.
isolate_->stack_guard()->AdjustStackLimitForSimulator();
// Prepare to execute the code at entry
if (ABI_USES_FUNCTION_DESCRIPTORS) {
// entry is the function descriptor
set_pc(*(reinterpret_cast<intptr_t*>(entry)));
} else {
// entry is the instruction address
set_pc(static_cast<intptr_t>(entry));
}
// Remember the values of non-volatile registers.
int64_t r6_val = get_register(r6);
int64_t r7_val = get_register(r7);
int64_t r8_val = get_register(r8);
int64_t r9_val = get_register(r9);
int64_t r10_val = get_register(r10);
int64_t r11_val = get_register(r11);
int64_t r12_val = get_register(r12);
int64_t r13_val = get_register(r13);
if (ABI_CALL_VIA_IP) {
// Put target address in ip (for JS prologue).
set_register(ip, get_pc());
}
// Put down marker for end of simulation. The simulator will stop simulation
// when the PC reaches this value. By saving the "end simulation" value into
// the LR the simulation stops when returning to this call point.
registers_[14] = end_sim_pc;
// Set up the non-volatile registers with a known value. To be able to check
// that they are preserved properly across JS execution.
uintptr_t callee_saved_value = icount_;
if (reg_arg_count < 5) {
set_register(r6, callee_saved_value + 6);
}
set_register(r7, callee_saved_value + 7);
set_register(r8, callee_saved_value + 8);
set_register(r9, callee_saved_value + 9);
set_register(r10, callee_saved_value + 10);
set_register(r11, callee_saved_value + 11);
set_register(r12, callee_saved_value + 12);
set_register(r13, callee_saved_value + 13);
// Start the simulation
Execute();
// Check that the non-volatile registers have been preserved.
#ifndef V8_TARGET_ARCH_S390X
if (reg_arg_count < 5) {
DCHECK_EQ(callee_saved_value + 6, get_low_register<uint32_t>(r6));
}
DCHECK_EQ(callee_saved_value + 7, get_low_register<uint32_t>(r7));
DCHECK_EQ(callee_saved_value + 8, get_low_register<uint32_t>(r8));
DCHECK_EQ(callee_saved_value + 9, get_low_register<uint32_t>(r9));
DCHECK_EQ(callee_saved_value + 10, get_low_register<uint32_t>(r10));
DCHECK_EQ(callee_saved_value + 11, get_low_register<uint32_t>(r11));
DCHECK_EQ(callee_saved_value + 12, get_low_register<uint32_t>(r12));
DCHECK_EQ(callee_saved_value + 13, get_low_register<uint32_t>(r13));
#else
if (reg_arg_count < 5) {
DCHECK_EQ(callee_saved_value + 6, get_register(r6));
}
DCHECK_EQ(callee_saved_value + 7, get_register(r7));
DCHECK_EQ(callee_saved_value + 8, get_register(r8));
DCHECK_EQ(callee_saved_value + 9, get_register(r9));
DCHECK_EQ(callee_saved_value + 10, get_register(r10));
DCHECK_EQ(callee_saved_value + 11, get_register(r11));
DCHECK_EQ(callee_saved_value + 12, get_register(r12));
DCHECK_EQ(callee_saved_value + 13, get_register(r13));
#endif
// Restore non-volatile registers with the original value.
set_register(r6, r6_val);
set_register(r7, r7_val);
set_register(r8, r8_val);
set_register(r9, r9_val);
set_register(r10, r10_val);
set_register(r11, r11_val);
set_register(r12, r12_val);
set_register(r13, r13_val);
}
intptr_t Simulator::CallImpl(Address entry, int argument_count,
const intptr_t* arguments) {
// Adjust JS-based stack limit to C-based stack limit.
isolate_->stack_guard()->AdjustStackLimitForSimulator();
// Remember the values of non-volatile registers.
int64_t r6_val = get_register(r6);
int64_t r7_val = get_register(r7);
int64_t r8_val = get_register(r8);
int64_t r9_val = get_register(r9);
int64_t r10_val = get_register(r10);
int64_t r11_val = get_register(r11);
int64_t r12_val = get_register(r12);
int64_t r13_val = get_register(r13);
// Set up arguments
// First 5 arguments passed in registers r2-r6.
int reg_arg_count = std::min(5, argument_count);
int stack_arg_count = argument_count - reg_arg_count;
for (int i = 0; i < reg_arg_count; i++) {
set_register(i + 2, arguments[i]);
}
// Remaining arguments passed on stack.
int64_t original_stack = get_register(sp);
// Compute position of stack on entry to generated code.
uintptr_t entry_stack =
(original_stack -
(kCalleeRegisterSaveAreaSize + stack_arg_count * sizeof(intptr_t)));
if (base::OS::ActivationFrameAlignment() != 0) {
entry_stack &= -base::OS::ActivationFrameAlignment();
}
// Store remaining arguments on stack, from low to high memory.
intptr_t* stack_argument =
reinterpret_cast<intptr_t*>(entry_stack + kCalleeRegisterSaveAreaSize);
memcpy(stack_argument, arguments + reg_arg_count,
stack_arg_count * sizeof(*arguments));
set_register(sp, entry_stack);
// Prepare to execute the code at entry
#if ABI_USES_FUNCTION_DESCRIPTORS
// entry is the function descriptor
set_pc(*(reinterpret_cast<intptr_t*>(entry)));
#else
// entry is the instruction address
set_pc(static_cast<intptr_t>(entry));
#endif
// Put target address in ip (for JS prologue).
set_register(r12, get_pc());
// Put down marker for end of simulation. The simulator will stop simulation
// when the PC reaches this value. By saving the "end simulation" value into
// the LR the simulation stops when returning to this call point.
registers_[14] = end_sim_pc;
// Set up the non-volatile registers with a known value. To be able to check
// that they are preserved properly across JS execution.
uintptr_t callee_saved_value = icount_;
if (reg_arg_count < 5) {
set_register(r6, callee_saved_value + 6);
}
set_register(r7, callee_saved_value + 7);
set_register(r8, callee_saved_value + 8);
set_register(r9, callee_saved_value + 9);
set_register(r10, callee_saved_value + 10);
set_register(r11, callee_saved_value + 11);
set_register(r12, callee_saved_value + 12);
set_register(r13, callee_saved_value + 13);
// Start the simulation
Execute();
// Check that the non-volatile registers have been preserved.
#ifndef V8_TARGET_ARCH_S390X
if (reg_arg_count < 5) {
DCHECK_EQ(callee_saved_value + 6, get_low_register<uint32_t>(r6));
}
DCHECK_EQ(callee_saved_value + 7, get_low_register<uint32_t>(r7));
DCHECK_EQ(callee_saved_value + 8, get_low_register<uint32_t>(r8));
DCHECK_EQ(callee_saved_value + 9, get_low_register<uint32_t>(r9));
DCHECK_EQ(callee_saved_value + 10, get_low_register<uint32_t>(r10));
DCHECK_EQ(callee_saved_value + 11, get_low_register<uint32_t>(r11));
DCHECK_EQ(callee_saved_value + 12, get_low_register<uint32_t>(r12));
DCHECK_EQ(callee_saved_value + 13, get_low_register<uint32_t>(r13));
#else
if (reg_arg_count < 5) {
DCHECK_EQ(callee_saved_value + 6, get_register(r6));
}
DCHECK_EQ(callee_saved_value + 7, get_register(r7));
DCHECK_EQ(callee_saved_value + 8, get_register(r8));
DCHECK_EQ(callee_saved_value + 9, get_register(r9));
DCHECK_EQ(callee_saved_value + 10, get_register(r10));
DCHECK_EQ(callee_saved_value + 11, get_register(r11));
DCHECK_EQ(callee_saved_value + 12, get_register(r12));
DCHECK_EQ(callee_saved_value + 13, get_register(r13));
#endif
// Restore non-volatile registers with the original value.
set_register(r6, r6_val);
set_register(r7, r7_val);
set_register(r8, r8_val);
set_register(r9, r9_val);
set_register(r10, r10_val);
set_register(r11, r11_val);
set_register(r12, r12_val);
set_register(r13, r13_val);
// Pop stack passed arguments.
#ifndef V8_TARGET_ARCH_S390X
DCHECK_EQ(entry_stack, get_low_register<uint32_t>(sp));
#else
DCHECK_EQ(entry_stack, get_register(sp));
#endif
set_register(sp, original_stack);
// Return value register
return get_register(r2);
}
void Simulator::CallFP(Address entry, double d0, double d1) {
set_d_register_from_double(0, d0);
set_d_register_from_double(1, d1);
CallInternal(entry);
}
int32_t Simulator::CallFPReturnsInt(Address entry, double d0, double d1) {
CallFP(entry, d0, d1);
int32_t result = get_register(r2);
return result;
}
double Simulator::CallFPReturnsDouble(Address entry, double d0, double d1) {
CallFP(entry, d0, d1);
return get_double_from_d_register(0);
}
uintptr_t Simulator::PushAddress(uintptr_t address) {
uintptr_t new_sp = get_register(sp) - sizeof(uintptr_t);
uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(new_sp);
*stack_slot = address;
set_register(sp, new_sp);
return new_sp;
}
uintptr_t Simulator::PopAddress() {
uintptr_t current_sp = get_register(sp);
uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(current_sp);
uintptr_t address = *stack_slot;
set_register(sp, current_sp + sizeof(uintptr_t));
return address;
}
#define EVALUATE(name) int Simulator::Evaluate_##name(Instruction* instr)
#define DCHECK_OPCODE(op) DCHECK(instr->S390OpcodeValue() == op)
#define AS(type) reinterpret_cast<type*>(instr)
#define DECODE_RIL_A_INSTRUCTION(r1, i2) \
int r1 = AS(RILInstruction)->R1Value(); \
uint32_t i2 = AS(RILInstruction)->I2UnsignedValue(); \
int length = 6;
#define DECODE_RIL_B_INSTRUCTION(r1, i2) \
int r1 = AS(RILInstruction)->R1Value(); \
int32_t i2 = AS(RILInstruction)->I2Value(); \
int length = 6;
#define DECODE_RIL_C_INSTRUCTION(m1, ri2) \
Condition m1 = static_cast<Condition>(AS(RILInstruction)->R1Value()); \
uint64_t ri2 = AS(RILInstruction)->I2Value(); \
int length = 6;
#define DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2) \
int r1 = AS(RXYInstruction)->R1Value(); \
int x2 = AS(RXYInstruction)->X2Value(); \
int b2 = AS(RXYInstruction)->B2Value(); \
int d2 = AS(RXYInstruction)->D2Value(); \
int length = 6;
#define DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val) \
int x2 = AS(RXInstruction)->X2Value(); \
int b2 = AS(RXInstruction)->B2Value(); \
int r1 = AS(RXInstruction)->R1Value(); \
intptr_t d2_val = AS(RXInstruction)->D2Value(); \
int length = 4;
#define DECODE_RS_A_INSTRUCTION(r1, r3, b2, d2) \
int r3 = AS(RSInstruction)->R3Value(); \
int b2 = AS(RSInstruction)->B2Value(); \
int r1 = AS(RSInstruction)->R1Value(); \
intptr_t d2 = AS(RSInstruction)->D2Value(); \
int length = 4;
#define DECODE_RS_A_INSTRUCTION_NO_R3(r1, b2, d2) \
int b2 = AS(RSInstruction)->B2Value(); \
int r1 = AS(RSInstruction)->R1Value(); \
int d2 = AS(RSInstruction)->D2Value(); \
int length = 4;
#define DECODE_RSI_INSTRUCTION(r1, r3, i2) \
int r1 = AS(RSIInstruction)->R1Value(); \
int r3 = AS(RSIInstruction)->R3Value(); \
int32_t i2 = AS(RSIInstruction)->I2Value(); \
int length = 4;
#define DECODE_SI_INSTRUCTION_I_UINT8(b1, d1_val, imm_val) \
int b1 = AS(SIInstruction)->B1Value(); \
intptr_t d1_val = AS(SIInstruction)->D1Value(); \
uint8_t imm_val = AS(SIInstruction)->I2Value(); \
int length = 4;
#define DECODE_SIL_INSTRUCTION(b1, d1, i2) \
int b1 = AS(SILInstruction)->B1Value(); \
intptr_t d1 = AS(SILInstruction)->D1Value(); \
int16_t i2 = AS(SILInstruction)->I2Value(); \
int length = 6;
#define DECODE_SIY_INSTRUCTION(b1, d1, i2) \
int b1 = AS(SIYInstruction)->B1Value(); \
intptr_t d1 = AS(SIYInstruction)->D1Value(); \
uint8_t i2 = AS(SIYInstruction)->I2Value(); \
int length = 6;
#define DECODE_RRE_INSTRUCTION(r1, r2) \
int r1 = AS(RREInstruction)->R1Value(); \
int r2 = AS(RREInstruction)->R2Value(); \
int length = 4;
#define DECODE_RRE_INSTRUCTION_M3(r1, r2, m3) \
int r1 = AS(RREInstruction)->R1Value(); \
int r2 = AS(RREInstruction)->R2Value(); \
int m3 = AS(RREInstruction)->M3Value(); \
int length = 4;
#define DECODE_RRE_INSTRUCTION_NO_R2(r1) \
int r1 = AS(RREInstruction)->R1Value(); \
int length = 4;
#define DECODE_RRD_INSTRUCTION(r1, r2, r3) \
int r1 = AS(RRDInstruction)->R1Value(); \
int r2 = AS(RRDInstruction)->R2Value(); \
int r3 = AS(RRDInstruction)->R3Value(); \
int length = 4;
#define DECODE_RRF_E_INSTRUCTION(r1, r2, m3, m4) \
int r1 = AS(RRFInstruction)->R1Value(); \
int r2 = AS(RRFInstruction)->R2Value(); \
int m3 = AS(RRFInstruction)->M3Value(); \
int m4 = AS(RRFInstruction)->M4Value(); \
int length = 4;
#define DECODE_RRF_A_INSTRUCTION(r1, r2, r3) \
int r1 = AS(RRFInstruction)->R1Value(); \
int r2 = AS(RRFInstruction)->R2Value(); \
int r3 = AS(RRFInstruction)->R3Value(); \
int length = 4;
#define DECODE_RRF_C_INSTRUCTION(r1, r2, m3) \
int r1 = AS(RRFInstruction)->R1Value(); \
int r2 = AS(RRFInstruction)->R2Value(); \
Condition m3 = static_cast<Condition>(AS(RRFInstruction)->M3Value()); \
int length = 4;
#define DECODE_RR_INSTRUCTION(r1, r2) \
int r1 = AS(RRInstruction)->R1Value(); \
int r2 = AS(RRInstruction)->R2Value(); \
int length = 2;
#define DECODE_RIE_D_INSTRUCTION(r1, r2, i2) \
int r1 = AS(RIEInstruction)->R1Value(); \
int r2 = AS(RIEInstruction)->R2Value(); \
int32_t i2 = AS(RIEInstruction)->I6Value(); \
int length = 6;
#define DECODE_RIE_E_INSTRUCTION(r1, r2, i2) \
int r1 = AS(RIEInstruction)->R1Value(); \
int r2 = AS(RIEInstruction)->R2Value(); \
int32_t i2 = AS(RIEInstruction)->I6Value(); \
int length = 6;
#define DECODE_RIE_F_INSTRUCTION(r1, r2, i3, i4, i5) \
int r1 = AS(RIEInstruction)->R1Value(); \
int r2 = AS(RIEInstruction)->R2Value(); \
uint32_t i3 = AS(RIEInstruction)->I3Value(); \
uint32_t i4 = AS(RIEInstruction)->I4Value(); \
uint32_t i5 = AS(RIEInstruction)->I5Value(); \
int length = 6;
#define DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2) \
int r1 = AS(RSYInstruction)->R1Value(); \
int r3 = AS(RSYInstruction)->R3Value(); \
int b2 = AS(RSYInstruction)->B2Value(); \
intptr_t d2 = AS(RSYInstruction)->D2Value(); \
int length = 6;
#define DECODE_RI_A_INSTRUCTION(instr, r1, i2) \
int32_t r1 = AS(RIInstruction)->R1Value(); \
int16_t i2 = AS(RIInstruction)->I2Value(); \
int length = 4;
#define DECODE_RI_B_INSTRUCTION(instr, r1, i2) \
int32_t r1 = AS(RILInstruction)->R1Value(); \
int16_t i2 = AS(RILInstruction)->I2Value(); \
int length = 4;
#define DECODE_RI_C_INSTRUCTION(instr, m1, i2) \
Condition m1 = static_cast<Condition>(AS(RIInstruction)->R1Value()); \
int16_t i2 = AS(RIInstruction)->I2Value(); \
int length = 4;
#define DECODE_RXE_INSTRUCTION(r1, b2, x2, d2) \
int r1 = AS(RXEInstruction)->R1Value(); \
int b2 = AS(RXEInstruction)->B2Value(); \
int x2 = AS(RXEInstruction)->X2Value(); \
int d2 = AS(RXEInstruction)->D2Value(); \
int length = 6;
#define DECODE_VRR_A_INSTRUCTION(r1, r2, m5, m4, m3) \
int r1 = AS(VRR_A_Instruction)->R1Value(); \
int r2 = AS(VRR_A_Instruction)->R2Value(); \
int m5 = AS(VRR_A_Instruction)->M5Value(); \
int m4 = AS(VRR_A_Instruction)->M4Value(); \
int m3 = AS(VRR_A_Instruction)->M3Value(); \
int length = 6;
#define DECODE_VRR_B_INSTRUCTION(r1, r2, r3, m5, m4) \
int r1 = AS(VRR_B_Instruction)->R1Value(); \
int r2 = AS(VRR_B_Instruction)->R2Value(); \
int r3 = AS(VRR_B_Instruction)->R3Value(); \
int m5 = AS(VRR_B_Instruction)->M5Value(); \
int m4 = AS(VRR_B_Instruction)->M4Value(); \
int length = 6;
#define DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4) \
int r1 = AS(VRR_C_Instruction)->R1Value(); \
int r2 = AS(VRR_C_Instruction)->R2Value(); \
int r3 = AS(VRR_C_Instruction)->R3Value(); \
int m6 = AS(VRR_C_Instruction)->M6Value(); \
int m5 = AS(VRR_C_Instruction)->M5Value(); \
int m4 = AS(VRR_C_Instruction)->M4Value(); \
int length = 6;
#define DECODE_VRR_E_INSTRUCTION(r1, r2, r3, r4, m6, m5) \
int r1 = AS(VRR_E_Instruction)->R1Value(); \
int r2 = AS(VRR_E_Instruction)->R2Value(); \
int r3 = AS(VRR_E_Instruction)->R3Value(); \
int r4 = AS(VRR_E_Instruction)->R4Value(); \
int m6 = AS(VRR_E_Instruction)->M6Value(); \
int m5 = AS(VRR_E_Instruction)->M5Value(); \
int length = 6;
#define DECODE_VRX_INSTRUCTION(r1, x2, b2, d2, m3) \
int r1 = AS(VRX_Instruction)->R1Value(); \
int x2 = AS(VRX_Instruction)->X2Value(); \
int b2 = AS(VRX_Instruction)->B2Value(); \
int d2 = AS(VRX_Instruction)->D2Value(); \
int m3 = AS(VRX_Instruction)->M3Value(); \
int length = 6;
#define DECODE_VRS_INSTRUCTION(r1, r3, b2, d2, m4) \
int r1 = AS(VRS_Instruction)->R1Value(); \
int r3 = AS(VRS_Instruction)->R3Value(); \
int b2 = AS(VRS_Instruction)->B2Value(); \
int d2 = AS(VRS_Instruction)->D2Value(); \
int m4 = AS(VRS_Instruction)->M4Value(); \
int length = 6;
#define DECODE_VRI_A_INSTRUCTION(r1, i2, m3) \
int r1 = AS(VRI_A_Instruction)->R1Value(); \
int16_t i2 = AS(VRI_A_Instruction)->I2Value(); \
int m3 = AS(VRI_A_Instruction)->M3Value(); \
int length = 6;
#define DECODE_VRI_C_INSTRUCTION(r1, r3, i2, m4) \
int r1 = AS(VRI_C_Instruction)->R1Value(); \
int r3 = AS(VRI_C_Instruction)->R3Value(); \
uint16_t i2 = AS(VRI_C_Instruction)->I2Value(); \
int m4 = AS(VRI_C_Instruction)->M4Value(); \
int length = 6;
#define GET_ADDRESS(index_reg, base_reg, offset) \
(((index_reg) == 0) ? 0 : get_register(index_reg)) + \
(((base_reg) == 0) ? 0 : get_register(base_reg)) + offset
int Simulator::Evaluate_Unknown(Instruction* instr) { UNREACHABLE(); }
EVALUATE(VST) {
DCHECK_OPCODE(VST);
DECODE_VRX_INSTRUCTION(r1, x2, b2, d2, m3);
USE(m3);
intptr_t addr = GET_ADDRESS(x2, b2, d2);
fpr_t* ptr = reinterpret_cast<fpr_t*>(addr);
*ptr = get_simd_register(r1);
return length;
}
EVALUATE(VL) {
DCHECK(VL);
DECODE_VRX_INSTRUCTION(r1, x2, b2, d2, m3);
USE(m3);
intptr_t addr = GET_ADDRESS(x2, b2, d2);
fpr_t* ptr = reinterpret_cast<fpr_t*>(addr);
DCHECK(m3 != 3 || (0x7 & addr) == 0);
DCHECK(m3 != 4 || (0xf & addr) == 0);
set_simd_register(r1, *ptr);
return length;
}
EVALUATE(VLGV) {
DCHECK_OPCODE(VLGV);
DECODE_VRS_INSTRUCTION(r1, r3, b2, d2, m4);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t index = b2_val + d2;
const int size_by_byte = 1 << m4;
int8_t* src = get_simd_register(r3).int8 + index * size_by_byte;
set_register(r1, 0);
memcpy(&get_register(r1), src, size_by_byte);
return length;
}
EVALUATE(VLVG) {
DCHECK_OPCODE(VLVG);
DECODE_VRS_INSTRUCTION(r1, r3, b2, d2, m4);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t index = b2_val + d2;
const int size_by_byte = 1 << m4;
int8_t* dst = get_simd_register(r1).int8 + index * size_by_byte;
memcpy(dst, &get_register(r3), size_by_byte);
return length;
}
EVALUATE(VREP) {
DCHECK_OPCODE(VREP);
DECODE_VRI_C_INSTRUCTION(r1, r3, i2, m4);
const int size_by_byte = 1 << m4;
DCHECK(i2 >= 0 && i2 < kSimd128Size / size_by_byte);
int8_t* src = get_simd_register(r3).int8;
int8_t* dst = get_simd_register(r1).int8;
for (int i = 0; i < kSimd128Size; i += size_by_byte) {
memcpy(dst + i, src + i2 * size_by_byte, size_by_byte);
}
return length;
}
EVALUATE(VLREP) {
DCHECK_OPCODE(VLREP);
DECODE_VRX_INSTRUCTION(r1, x2, b2, d2, m3);
intptr_t addr = GET_ADDRESS(x2, b2, d2);
const int size_by_byte = 1 << m3;
int8_t* dst = get_simd_register(r1).int8;
int8_t* src = reinterpret_cast<int8_t*>(addr);
set_simd_register(r1, fp_zero);
for (int i = 0; i < kSimd128Size; i += size_by_byte) {
memcpy(dst + i, src, size_by_byte);
}
return length;
}
EVALUATE(VREPI) {
DCHECK_OPCODE(VREPI);
DECODE_VRI_A_INSTRUCTION(r1, i2, m3);
const int size_by_byte = 1 << m3;
int8_t* dst = get_simd_register(r1).int8;
uint64_t immediate = static_cast<uint64_t>(i2);
set_simd_register(r1, fp_zero);
for (int i = 0; i < kSimd128Size; i += size_by_byte) {
memcpy(dst + i, &immediate, size_by_byte);
}
return length;
}
EVALUATE(VLR) {
DCHECK_OPCODE(VLR);
DECODE_VRR_A_INSTRUCTION(r1, r2, m5, m4, m3);
USE(m5);
USE(m4);
USE(m3);
set_simd_register(r1, get_simd_register(r2));
return length;
}
EVALUATE(VSTEF) {
DCHECK_OPCODE(VSTEF);
DECODE_VRX_INSTRUCTION(r1, x2, b2, d2, m3);
intptr_t addr = GET_ADDRESS(x2, b2, d2);
int32_t value = get_simd_register_by_lane<int32_t>(r1, m3);
WriteW(addr, value, instr);
return length;
}
EVALUATE(VLEF) {
DCHECK_OPCODE(VLEF);
DECODE_VRX_INSTRUCTION(r1, x2, b2, d2, m3);
intptr_t addr = GET_ADDRESS(x2, b2, d2);
int32_t value = ReadW(addr, instr);
set_simd_register_by_lane<int32_t>(r1, m3, value);
return length;
}
template <class T, class Operation>
inline static void VectorBinaryOp(void* dst, void* src1, void* src2,
Operation op) {
int8_t* src1_ptr = reinterpret_cast<int8_t*>(src1);
int8_t* src2_ptr = reinterpret_cast<int8_t*>(src2);
int8_t* dst_ptr = reinterpret_cast<int8_t*>(dst);
for (int i = 0; i < kSimd128Size; i += sizeof(T)) {
T& dst_val = *reinterpret_cast<T*>(dst_ptr + i);
T& src1_val = *reinterpret_cast<T*>(src1_ptr + i);
T& src2_val = *reinterpret_cast<T*>(src2_ptr + i);
dst_val = op(src1_val, src2_val);
memcpy(dst_ptr + i, &dst_val, sizeof(T));
}
}
#define VECTOR_BINARY_OP_FOR_TYPE(type, op) \
VectorBinaryOp<type>(&get_simd_register(r1), &get_simd_register(r2), \
&get_simd_register(r3), \
[](type a, type b) { return a op b; });
#define VECTOR_BINARY_OP(op) \
switch (m4) { \
case 0: \
VECTOR_BINARY_OP_FOR_TYPE(int8_t, op) \
break; \
case 1: \
VECTOR_BINARY_OP_FOR_TYPE(int16_t, op) \
break; \
case 2: \
VECTOR_BINARY_OP_FOR_TYPE(int32_t, op) \
break; \
case 3: \
VECTOR_BINARY_OP_FOR_TYPE(int64_t, op) \
break; \
default: \
UNREACHABLE(); \
break; \
}
EVALUATE(VA) {
DCHECK(VA);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m5);
USE(m6);
VECTOR_BINARY_OP(+)
return length;
}
EVALUATE(VS) {
DCHECK_OPCODE(VS);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m5);
USE(m6);
VECTOR_BINARY_OP(-)
return length;
}
EVALUATE(VML) {
DCHECK_OPCODE(VML);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m5);
USE(m6);
VECTOR_BINARY_OP(*)
return length;
}
template <class S, class D>
void VectorSum(void* dst, void* src1, void* src2) {
D value = 0;
for (size_t i = 0; i < kSimd128Size / sizeof(S); i++) {
value += *(reinterpret_cast<S*>(src1) + i);
if ((i + 1) % (sizeof(D) / sizeof(S)) == 0) {
value += *(reinterpret_cast<S*>(src2) + i);
memcpy(reinterpret_cast<D*>(dst) + i / (sizeof(D) / sizeof(S)), &value,
sizeof(D));
value = 0;
}
}
}
EVALUATE(VSUM) {
DCHECK_OPCODE(VSUM);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m6);
USE(m5);
fpr_t src1 = get_simd_register(r2);
fpr_t src2 = get_simd_register(r3);
switch (m4) {
case 0:
VectorSum<int8_t, int32_t>(&get_simd_register(r1), &src1, &src2);
break;
case 1:
VectorSum<int16_t, int32_t>(&get_simd_register(r1), &src1, &src2);
break;
default:
UNREACHABLE();
}
return length;
}
EVALUATE(VSUMG) {
DCHECK_OPCODE(VSUMG);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m6);
USE(m5);
fpr_t src1 = get_simd_register(r2);
fpr_t src2 = get_simd_register(r3);
switch (m4) {
case 1:
VectorSum<int16_t, int64_t>(&get_simd_register(r1), &src1, &src2);
break;
case 2:
VectorSum<int32_t, int64_t>(&get_simd_register(r1), &src1, &src2);
break;
default:
UNREACHABLE();
}
return length;
}
template <class S, class D>
void VectorPack(void* dst, void* src1, void* src2, bool saturate,
const D& max = 0, const D& min = 0) {
S* src = reinterpret_cast<S*>(src1);
int count = 0;
S value = 0;
for (size_t i = 0; i < kSimd128Size / sizeof(D); i++, count++) {
if (count == kSimd128Size / sizeof(S)) {
src = reinterpret_cast<S*>(src2);
count = 0;
}
memcpy(&value, src + count, sizeof(S));
if (saturate) {
if (value > max)
value = max;
else if (value < min)
value = min;
}
memcpy(reinterpret_cast<D*>(dst) + i, &value, sizeof(D));
}
}
EVALUATE(VPK) {
DCHECK_OPCODE(VPK);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m6);
USE(m5);
fpr_t src1 = get_simd_register(r2);
fpr_t src2 = get_simd_register(r3);
switch (m4) {
case 1:
VectorPack<int16_t, int8_t>(&get_simd_register(r1), &src1, &src2, false);
break;
case 2:
VectorPack<int32_t, int16_t>(&get_simd_register(r1), &src1, &src2, false);
break;
case 3:
VectorPack<int64_t, int32_t>(&get_simd_register(r1), &src1, &src2, false);
break;
default:
UNREACHABLE();
}
return length;
}
EVALUATE(VPKS) {
DCHECK_OPCODE(VPKS);
DECODE_VRR_B_INSTRUCTION(r1, r2, r3, m5, m4);
USE(m5);
USE(m4);
fpr_t src1 = get_simd_register(r2);
fpr_t src2 = get_simd_register(r3);
switch (m4) {
case 1:
VectorPack<int16_t, int8_t>(&get_simd_register(r1), &src1, &src2, true,
INT8_MAX, INT8_MIN);
break;
case 2:
VectorPack<int32_t, int16_t>(&get_simd_register(r1), &src1, &src2, true,
INT16_MAX, INT16_MIN);
break;
case 3:
VectorPack<int64_t, int32_t>(&get_simd_register(r1), &src1, &src2, true,
INT32_MAX, INT32_MIN);
break;
default:
UNREACHABLE();
}
return length;
}
EVALUATE(VPKLS) {
DCHECK_OPCODE(VPKLS);
DECODE_VRR_B_INSTRUCTION(r1, r2, r3, m5, m4);
USE(m5);
USE(m4);
fpr_t src1 = get_simd_register(r2);
fpr_t src2 = get_simd_register(r3);
switch (m4) {
case 1:
VectorPack<uint16_t, uint8_t>(&get_simd_register(r1), &src1, &src2, true,
UINT8_MAX, 0);
break;
case 2:
VectorPack<uint32_t, uint16_t>(&get_simd_register(r1), &src1, &src2, true,
UINT16_MAX, 0);
break;
case 3:
VectorPack<uint64_t, uint32_t>(&get_simd_register(r1), &src1, &src2, true,
UINT32_MAX, 0);
break;
default:
UNREACHABLE();
}
return length;
}
template <class S, class D>
void VectorUnpackHigh(void* dst, void* src) {
D value = 0;
for (size_t i = 0; i < kSimd128Size / sizeof(D); i++) {
value = *(reinterpret_cast<S*>(src) + i + (sizeof(S) / 2));
memcpy(reinterpret_cast<D*>(dst) + i, &value, sizeof(D));
}
}
EVALUATE(VUPH) {
DCHECK_OPCODE(VUPH);
DECODE_VRR_A_INSTRUCTION(r1, r2, m5, m4, m3);
USE(m5);
USE(m4);
switch (m3) {
case 0:
VectorUnpackHigh<int8_t, int16_t>(&get_simd_register(r1),
&get_simd_register(r2));
break;
case 1:
VectorUnpackHigh<int16_t, int32_t>(&get_simd_register(r1),
&get_simd_register(r2));
break;
case 2:
VectorUnpackHigh<int32_t, int64_t>(&get_simd_register(r1),
&get_simd_register(r2));
break;
default:
UNREACHABLE();
}
return length;
}
EVALUATE(VUPLH) {
DCHECK_OPCODE(VUPLH);
DECODE_VRR_A_INSTRUCTION(r1, r2, m5, m4, m3);
USE(m5);
USE(m4);
switch (m3) {
case 0:
VectorUnpackHigh<uint8_t, uint16_t>(&get_simd_register(r1),
&get_simd_register(r2));
break;
case 1:
VectorUnpackHigh<uint16_t, uint32_t>(&get_simd_register(r1),
&get_simd_register(r2));
break;
case 2:
VectorUnpackHigh<uint32_t, uint64_t>(&get_simd_register(r1),
&get_simd_register(r2));
break;
default:
UNREACHABLE();
}
return length;
}
template <class S, class D>
void VectorUnpackLow(void* dst, void* src) {
D value = 0;
for (size_t i = kSimd128Size / sizeof(D); i > 0; i--) {
value = *(reinterpret_cast<S*>(src) + i - 1);
memcpy(reinterpret_cast<D*>(dst) + i - 1, &value, sizeof(D));
}
}
EVALUATE(VUPL) {
DCHECK_OPCODE(VUPL);
DECODE_VRR_A_INSTRUCTION(r1, r2, m5, m4, m3);
USE(m5);
USE(m4);
switch (m3) {
case 0:
VectorUnpackLow<int8_t, int16_t>(&get_simd_register(r1),
&get_simd_register(r2));
break;
case 1:
VectorUnpackLow<int16_t, int32_t>(&get_simd_register(r1),
&get_simd_register(r2));
break;
case 2:
VectorUnpackLow<int32_t, int64_t>(&get_simd_register(r1),
&get_simd_register(r2));
break;
default:
UNREACHABLE();
}
return length;
}
EVALUATE(VUPLL) {
DCHECK_OPCODE(VUPLL);
DECODE_VRR_A_INSTRUCTION(r1, r2, m5, m4, m3);
USE(m5);
USE(m4);
switch (m3) {
case 0:
VectorUnpackLow<uint8_t, uint16_t>(&get_simd_register(r1),
&get_simd_register(r2));
break;
case 1:
VectorUnpackLow<uint16_t, uint32_t>(&get_simd_register(r1),
&get_simd_register(r2));
break;
case 2:
VectorUnpackLow<uint32_t, uint64_t>(&get_simd_register(r1),
&get_simd_register(r2));
break;
default:
UNREACHABLE();
}
return length;
}
#define VECTOR_MAX_MIN_FOR_TYPE(type, op) \
VectorBinaryOp<type>(&get_simd_register(r1), &get_simd_register(r2), \
&get_simd_register(r3), \
[](type a, type b) { return (a op b) ? a : b; });
#define VECTOR_MAX_MIN(op, sign) \
switch (m4) { \
case 0: \
VECTOR_MAX_MIN_FOR_TYPE(sign##int8_t, op) \
break; \
case 1: \
VECTOR_MAX_MIN_FOR_TYPE(sign##int16_t, op) \
break; \
case 2: \
VECTOR_MAX_MIN_FOR_TYPE(sign##int32_t, op) \
break; \
case 3: \
VECTOR_MAX_MIN_FOR_TYPE(sign##int64_t, op) \
break; \
default: \
UNREACHABLE(); \
break; \
}
EVALUATE(VMX) {
DCHECK_OPCODE(VMX);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m5);
USE(m6);
VECTOR_MAX_MIN(>, )
return length;
}
EVALUATE(VMXL) {
DCHECK_OPCODE(VMXL);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m5);
USE(m6);
VECTOR_MAX_MIN(>, u)
return length;
}
EVALUATE(VMN) {
DCHECK_OPCODE(VMN);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m5);
USE(m6);
VECTOR_MAX_MIN(<, )
return length;
}
EVALUATE(VMNL) {
DCHECK_OPCODE(VMNL);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m5);
USE(m6);
VECTOR_MAX_MIN(<, u);
return length;
}
#define VECTOR_COMPARE_FOR_TYPE(type, op) \
VectorBinaryOp<type>(&get_simd_register(r1), &get_simd_register(r2), \
&get_simd_register(r3), \
[](type a, type b) { return (a op b) ? -1 : 0; });
#define VECTOR_COMPARE(op, sign) \
switch (m4) { \
case 0: \
VECTOR_COMPARE_FOR_TYPE(sign##int8_t, op) \
break; \
case 1: \
VECTOR_COMPARE_FOR_TYPE(sign##int16_t, op) \
break; \
case 2: \
VECTOR_COMPARE_FOR_TYPE(sign##int32_t, op) \
break; \
case 3: \
VECTOR_COMPARE_FOR_TYPE(sign##int64_t, op) \
break; \
default: \
UNREACHABLE(); \
break; \
}
EVALUATE(VCEQ) {
DCHECK_OPCODE(VCEQ);
DECODE_VRR_B_INSTRUCTION(r1, r2, r3, m5, m4);
USE(m5);
DCHECK_EQ(m5, 0);
VECTOR_COMPARE(==, )
return length;
}
EVALUATE(VCH) {
DCHECK_OPCODE(VCH);
DECODE_VRR_B_INSTRUCTION(r1, r2, r3, m5, m4);
USE(m5);
DCHECK_EQ(m5, 0);
VECTOR_COMPARE(>, )
return length;
}
EVALUATE(VCHL) {
DCHECK_OPCODE(VCHL);
DECODE_VRR_B_INSTRUCTION(r1, r2, r3, m5, m4);
USE(m5);
DCHECK_EQ(m5, 0);
VECTOR_COMPARE(>, u)
return length;
}
EVALUATE(VO) {
DCHECK_OPCODE(VO);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m5);
USE(m6);
USE(m4);
VECTOR_BINARY_OP_FOR_TYPE(int64_t, |)
return length;
}
EVALUATE(VN) {
DCHECK_OPCODE(VN);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m5);
USE(m6);
USE(m4);
VECTOR_BINARY_OP_FOR_TYPE(int64_t, &)
return length;
}
EVALUATE(VX) {
DCHECK_OPCODE(VX);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m4);
USE(m5);
USE(m6);
VECTOR_BINARY_OP_FOR_TYPE(int64_t, ^)
return length;
}
template <class T>
void VectorLoadComplement(void* dst, void* src) {
int8_t* src_ptr = reinterpret_cast<int8_t*>(src);
int8_t* dst_ptr = reinterpret_cast<int8_t*>(dst);
for (int i = 0; i < kSimd128Size; i += sizeof(T)) {
T& src_val = *reinterpret_cast<T*>(src_ptr + i);
T& dst_val = *reinterpret_cast<T*>(dst_ptr + i);
dst_val = -(uint64_t)src_val;
memcpy(dst_ptr + i, &dst_val, sizeof(T));
}
}
EVALUATE(VLC) {
DCHECK_OPCODE(VLC);
DECODE_VRR_A_INSTRUCTION(r1, r2, m5, m4, m3);
USE(m5);
USE(m4);
switch (m3) {
case 0:
VectorLoadComplement<int8_t>(&get_simd_register(r1),
&get_simd_register(r2));
break;
case 1:
VectorLoadComplement<int16_t>(&get_simd_register(r1),
&get_simd_register(r2));
break;
case 2:
VectorLoadComplement<int32_t>(&get_simd_register(r1),
&get_simd_register(r2));
break;
case 3:
VectorLoadComplement<int64_t>(&get_simd_register(r1),
&get_simd_register(r2));
break;
default:
UNREACHABLE();
}
return length;
}
EVALUATE(VSEL) {
DCHECK_OPCODE(VSEL);
DECODE_VRR_E_INSTRUCTION(r1, r2, r3, r4, m6, m5);
USE(m5);
USE(m6);
fpr_t scratch = get_simd_register(r2);
fpr_t mask = get_simd_register(r4);
scratch.int64[0] ^= get_simd_register_by_lane<int64_t>(r3, 0);
scratch.int64[1] ^= get_simd_register_by_lane<int64_t>(r3, 1);
mask.int64[0] &= scratch.int64[0];
mask.int64[1] &= scratch.int64[1];
mask.int64[0] ^= get_simd_register_by_lane<int64_t>(r3, 0);
mask.int64[1] ^= get_simd_register_by_lane<int64_t>(r3, 1);
set_simd_register(r1, mask);
return length;
}
template <class T, class Operation>
void VectorShift(void* dst, void* src, unsigned int shift, Operation op) {
int8_t* src_ptr = reinterpret_cast<int8_t*>(src);
int8_t* dst_ptr = reinterpret_cast<int8_t*>(dst);
for (int i = 0; i < kSimd128Size; i += sizeof(T)) {
T& dst_val = *reinterpret_cast<T*>(dst_ptr + i);
T& src_val = *reinterpret_cast<T*>(src_ptr + i);
dst_val = op(src_val, shift);
memcpy(dst_ptr + i, &dst_val, sizeof(T));
}
}
#define VECTOR_SHIFT_FOR_TYPE(type, op, shift) \
VectorShift<type>(&get_simd_register(r1), &get_simd_register(r3), shift, \
[](type a, unsigned int shift) { return a op shift; });
#define VECTOR_SHIFT(op, sign) \
switch (m4) { \
case 0: \
VECTOR_SHIFT_FOR_TYPE(sign##int8_t, op, shift) \
break; \
case 1: \
VECTOR_SHIFT_FOR_TYPE(sign##int16_t, op, shift) \
break; \
case 2: \
VECTOR_SHIFT_FOR_TYPE(sign##int32_t, op, shift) \
break; \
case 3: \
VECTOR_SHIFT_FOR_TYPE(sign##int64_t, op, shift) \
break; \
default: \
UNREACHABLE(); \
break; \
}
EVALUATE(VESL) {
DCHECK_OPCODE(VESL);
DECODE_VRS_INSTRUCTION(r1, r3, b2, d2, m4);
unsigned int shift = get_register(b2) + d2;
VECTOR_SHIFT(<<, )
return length;
}
EVALUATE(VESRA) {
DCHECK_OPCODE(VESRA);
DECODE_VRS_INSTRUCTION(r1, r3, b2, d2, m4);
unsigned int shift = get_register(b2) + d2;
VECTOR_SHIFT(>>, )
return length;
}
EVALUATE(VESRL) {
DCHECK_OPCODE(VESRL);
DECODE_VRS_INSTRUCTION(r1, r3, b2, d2, m4);
unsigned int shift = get_register(b2) + d2;
VECTOR_SHIFT(>>, u)
return length;
}
EVALUATE(VTM) {
DCHECK_OPCODE(VTM);
DECODE_VRR_A_INSTRUCTION(r1, r2, m5, m4, m3);
USE(m5);
USE(m4);
USE(m3);
int64_t src1 = get_simd_register_by_lane<int64_t>(r1, 0);
int64_t src2 = get_simd_register_by_lane<int64_t>(r1, 1);
int64_t mask1 = get_simd_register_by_lane<int64_t>(r2, 0);
int64_t mask2 = get_simd_register_by_lane<int64_t>(r2, 1);
if ((src1 & mask1) == 0 && (src2 & mask2) == 0) {
condition_reg_ = 0x8;
return length;
}
if ((src1 & mask1) == mask1 && (src2 & mask2) == mask2) {
condition_reg_ = 0x1;
return length;
}
condition_reg_ = 0x4;
return length;
}
#define VECTOR_FP_BINARY_OP(op) \
switch (m4) { \
case 2: \
DCHECK(CpuFeatures::IsSupported(VECTOR_ENHANCE_FACILITY_1)); \
if (m5 == 8) { \
float src1 = get_simd_register_by_lane<float>(r2, 0); \
float src2 = get_simd_register_by_lane<float>(r3, 0); \
set_simd_register_by_lane<float>(r1, 0, src1 op src2); \
} else { \
DCHECK_EQ(m5, 0); \
VECTOR_BINARY_OP_FOR_TYPE(float, op) \
} \
break; \
case 3: \
if (m5 == 8) { \
double src1 = get_simd_register_by_lane<double>(r2, 0); \
double src2 = get_simd_register_by_lane<double>(r3, 0); \
set_simd_register_by_lane<double>(r1, 0, src1 op src2); \
} else { \
DCHECK_EQ(m5, 0); \
VECTOR_BINARY_OP_FOR_TYPE(double, op) \
} \
break; \
default: \
UNREACHABLE(); \
break; \
}
EVALUATE(VFA) {
DCHECK_OPCODE(VFA);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m6);
VECTOR_FP_BINARY_OP(+)
return length;
}
EVALUATE(VFS) {
DCHECK_OPCODE(VFS);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m6);
VECTOR_FP_BINARY_OP(-)
return length;
}
EVALUATE(VFM) {
DCHECK_OPCODE(VFM);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m6);
VECTOR_FP_BINARY_OP(*)
return length;
}
EVALUATE(VFD) {
DCHECK_OPCODE(VFD);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m6);
VECTOR_FP_BINARY_OP(/)
return length;
}
template <class T, class Operation>
void VectorFPMaxMin(void* dst, void* src1, void* src2, Operation op) {
T* dst_ptr = reinterpret_cast<T*>(dst);
T* src1_ptr = reinterpret_cast<T*>(src1);
T* src2_ptr = reinterpret_cast<T*>(src2);
for (size_t i = 0; i < kSimd128Size / sizeof(T); i++) {
T src1_val = *(src1_ptr + i);
T src2_val = *(src2_ptr + i);
T value = op(src1_val, src2_val);
// using Java's Max Min functions
if (isnan(src1_val) || isnan(src2_val)) {
value = NAN;
}
memcpy(dst_ptr + i, &value, sizeof(T));
}
}
#define VECTOR_FP_MAX_MIN_FOR_TYPE(type, op) \
VectorFPMaxMin<type>(&get_simd_register(r1), &get_simd_register(r2), \
&get_simd_register(r3), \
[](type a, type b) { return (a op b) ? a : b; });
#define VECTOR_FP_MAX_MIN(op) \
switch (m4) { \
case 2: \
if (m5 == 8) { \
float src1 = get_simd_register_by_lane<float>(r2, 0); \
float src2 = get_simd_register_by_lane<float>(r3, 0); \
set_simd_register_by_lane<float>(r1, 0, (src1 op src2) ? src1 : src2); \
} else { \
DCHECK_EQ(m5, 0); \
DCHECK_EQ(m6, 1); \
VECTOR_FP_MAX_MIN_FOR_TYPE(float, op) \
} \
break; \
case 3: \
if (m5 == 8) { \
double src1 = get_simd_register_by_lane<double>(r2, 0); \
double src2 = get_simd_register_by_lane<double>(r3, 0); \
set_simd_register_by_lane<double>(r1, 0, \
(src1 op src2) ? src1 : src2); \
} else { \
DCHECK_EQ(m5, 0); \
DCHECK_EQ(m6, 1); \
VECTOR_FP_MAX_MIN_FOR_TYPE(double, op) \
} \
break; \
default: \
UNREACHABLE(); \
break; \
}
EVALUATE(VFMIN) {
DCHECK(CpuFeatures::IsSupported(VECTOR_ENHANCE_FACILITY_1));
DCHECK_OPCODE(VFMIN);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m6);
VECTOR_FP_MAX_MIN(<) // NOLINT
return length;
}
EVALUATE(VFMAX) {
DCHECK(CpuFeatures::IsSupported(VECTOR_ENHANCE_FACILITY_1));
DCHECK_OPCODE(VFMAX);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m6);
VECTOR_FP_MAX_MIN(>) // NOLINT
return length;
}
template <class S, class D, class Operation>
void VectorFPCompare(void* dst, void* src1, void* src2, Operation op) {
D* dst_ptr = reinterpret_cast<D*>(dst);
S* src1_ptr = reinterpret_cast<S*>(src1);
S* src2_ptr = reinterpret_cast<S*>(src2);
for (size_t i = 0; i < kSimd128Size / sizeof(D); i++) {
S src1_val = *(src1_ptr + i);
S src2_val = *(src2_ptr + i);
D value = op(src1_val, src2_val);
memcpy(dst_ptr + i, &value, sizeof(D));
}
}
#define VECTOR_FP_COMPARE_FOR_TYPE(S, D, op) \
VectorFPCompare<S, D>(&get_simd_register(r1), &get_simd_register(r2), \
&get_simd_register(r3), \
[](S a, S b) { return (a op b) ? -1 : 0; });
#define VECTOR_FP_COMPARE(op) \
switch (m4) { \
case 2: \
DCHECK(CpuFeatures::IsSupported(VECTOR_ENHANCE_FACILITY_1)); \
if (m5 == 8) { \
float src1 = get_simd_register_by_lane<float>(r2, 0); \
float src2 = get_simd_register_by_lane<float>(r3, 0); \
set_simd_register_by_lane<int32_t>(r1, 0, (src1 op src2) ? -1 : 0); \
} else { \
DCHECK_EQ(m5, 0); \
VECTOR_FP_COMPARE_FOR_TYPE(float, int32_t, op) \
} \
break; \
case 3: \
if (m5 == 8) { \
double src1 = get_simd_register_by_lane<double>(r2, 0); \
double src2 = get_simd_register_by_lane<double>(r3, 0); \
set_simd_register_by_lane<int64_t>(r1, 0, (src1 op src2) ? -1 : 0); \
} else { \
DCHECK_EQ(m5, 0); \
VECTOR_FP_COMPARE_FOR_TYPE(double, int64_t, op) \
} \
break; \
default: \
UNREACHABLE(); \
break; \
}
EVALUATE(VFCE) {
DCHECK_OPCODE(VFCE);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m6);
VECTOR_FP_COMPARE(==)
return length;
}
EVALUATE(VFCHE) {
DCHECK_OPCODE(VFCHE);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m6);
VECTOR_FP_COMPARE(>=)
return length;
}
EVALUATE(VFCH) {
DCHECK_OPCODE(VFCH);
DECODE_VRR_C_INSTRUCTION(r1, r2, r3, m6, m5, m4);
USE(m6);
VECTOR_FP_COMPARE(>) // NOLINT
return length;
}
template <class T>
void VectorSignOp(void* dst, void* src, int m4, int m5) {
T* src_ptr = reinterpret_cast<T*>(src);
T* dst_ptr = reinterpret_cast<T*>(dst);
switch (m5) {
case 0:
if (m4 == 8) {
T value = -(*src_ptr);
memcpy(dst_ptr, &value, sizeof(T));
} else {
for (size_t i = 0; i < kSimd128Size / sizeof(T); i++) {
T value = -(*(src_ptr + i));
memcpy(dst_ptr + i, &value, sizeof(T));
}
}
break;
case 1:
if (m4 == 8) {
T value = -abs(*src_ptr);
memcpy(dst_ptr, &value, sizeof(T));
} else {
for (size_t i = 0; i < kSimd128Size / sizeof(T); i++) {
T value = -abs(*(src_ptr + i));
memcpy(dst_ptr + i, &value, sizeof(T));
}
}
break;
case 2:
if (m4 == 8) {
T value = abs(*src_ptr);
memcpy(dst_ptr, &value, sizeof(T));
} else {
for (size_t i = 0; i < kSimd128Size / sizeof(T); i++) {
T value = abs(*(src_ptr + i));
memcpy(dst_ptr + i, &value, sizeof(T));
}
}
break;
default:
UNREACHABLE();
}
}
EVALUATE(VFPSO) {
DCHECK_OPCODE(VFPSO);
DECODE_VRR_A_INSTRUCTION(r1, r2, m5, m4, m3);
USE(m5);
USE(m4);
USE(m3);
switch (m3) {
case 2:
DCHECK(CpuFeatures::IsSupported(VECTOR_ENHANCE_FACILITY_1));
VectorSignOp<float>(&get_simd_register(r1), &get_simd_register(r2), m4,
m5);
break;
case 3:
VectorSignOp<double>(&get_simd_register(r1), &get_simd_register(r2), m4,
m5);
break;
default:
UNREACHABLE();
}
return length;
}
template <class T>
void VectorFPSqrt(void* dst, void* src) {
T* dst_ptr = reinterpret_cast<T*>(dst);
T* src_ptr = reinterpret_cast<T*>(src);
for (size_t i = 0; i < kSimd128Size / sizeof(T); i++) {
T value = sqrt(*(src_ptr + i));
memcpy(dst_ptr + i, &value, sizeof(T));
}
}
EVALUATE(VFSQ) {
DCHECK_OPCODE(VFSQ);
DECODE_VRR_A_INSTRUCTION(r1, r2, m5, m4, m3);
USE(m5);
switch (m3) {
case 2:
DCHECK(CpuFeatures::IsSupported(VECTOR_ENHANCE_FACILITY_1));
if (m4 == 8) {
float src = get_simd_register_by_lane<float>(r2, 0);
set_simd_register_by_lane<float>(r1, 0, sqrt(src));
} else {
VectorFPSqrt<float>(&get_simd_register(r1), &get_simd_register(r2));
}
break;
case 3:
if (m4 == 8) {
double src = get_simd_register_by_lane<double>(r2, 0);
set_simd_register_by_lane<double>(r1, 0, sqrt(src));
} else {
VectorFPSqrt<double>(&get_simd_register(r1), &get_simd_register(r2));
}
break;
default:
UNREACHABLE();
}
return length;
}
EVALUATE(VFI) {
DCHECK_OPCODE(VFI);
DECODE_VRR_A_INSTRUCTION(r1, r2, m5, m4, m3);
USE(m4);
USE(m5);
DCHECK_EQ(m5, 5);
switch (m3) {
case 2:
DCHECK(CpuFeatures::IsSupported(VECTOR_ENHANCE_FACILITY_1));
for (int i = 0; i < 4; i++) {
float value = get_simd_register_by_lane<float>(r2, i);
set_simd_register_by_lane<float>(r1, i, trunc(value));
}
break;
case 3:
for (int i = 0; i < 2; i++) {
double value = get_simd_register_by_lane<double>(r2, i);
set_simd_register_by_lane<double>(r1, i, trunc(value));
}
break;
default:
UNREACHABLE();
}
return length;
}
EVALUATE(DUMY) {
DCHECK_OPCODE(DUMY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
USE(r1);
USE(x2);
USE(b2);
USE(d2);
// dummy instruction does nothing.
return length;
}
EVALUATE(CLR) {
DCHECK_OPCODE(CLR);
DECODE_RR_INSTRUCTION(r1, r2);
uint32_t r1_val = get_low_register<uint32_t>(r1);
uint32_t r2_val = get_low_register<uint32_t>(r2);
SetS390ConditionCode<uint32_t>(r1_val, r2_val);
return length;
}
EVALUATE(LR) {
DCHECK_OPCODE(LR);
DECODE_RR_INSTRUCTION(r1, r2);
set_low_register(r1, get_low_register<int32_t>(r2));
return length;
}
EVALUATE(AR) {
DCHECK_OPCODE(AR);
DECODE_RR_INSTRUCTION(r1, r2);
int32_t r1_val = get_low_register<int32_t>(r1);
int32_t r2_val = get_low_register<int32_t>(r2);
bool isOF = CheckOverflowForIntAdd(r1_val, r2_val, int32_t);
r1_val += r2_val;
SetS390ConditionCode<int32_t>(r1_val, 0);
SetS390OverflowCode(isOF);
set_low_register(r1, r1_val);
return length;
}
EVALUATE(L) {
DCHECK_OPCODE(L);
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t addr = b2_val + x2_val + d2_val;
int32_t mem_val = ReadW(addr, instr);
set_low_register(r1, mem_val);
return length;
}
EVALUATE(BRC) {
DCHECK_OPCODE(BRC);
DECODE_RI_C_INSTRUCTION(instr, m1, i2);
if (TestConditionCode(m1)) {
intptr_t offset = 2 * i2;
set_pc(get_pc() + offset);
}
return length;
}
EVALUATE(AHI) {
DCHECK_OPCODE(AHI);
DECODE_RI_A_INSTRUCTION(instr, r1, i2);
int32_t r1_val = get_low_register<int32_t>(r1);
bool isOF = CheckOverflowForIntAdd(r1_val, i2, int32_t);
r1_val += i2;
set_low_register(r1, r1_val);
SetS390ConditionCode<int32_t>(r1_val, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(AGHI) {
DCHECK_OPCODE(AGHI);
DECODE_RI_A_INSTRUCTION(instr, r1, i2);
int64_t r1_val = get_register(r1);
bool isOF = false;
isOF = CheckOverflowForIntAdd(r1_val, i2, int64_t);
r1_val += i2;
set_register(r1, r1_val);
SetS390ConditionCode<int64_t>(r1_val, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(BRCL) {
DCHECK_OPCODE(BRCL);
DECODE_RIL_C_INSTRUCTION(m1, ri2);
if (TestConditionCode(m1)) {
intptr_t offset = 2 * ri2;
set_pc(get_pc() + offset);
}
return length;
}
EVALUATE(IIHF) {
DCHECK_OPCODE(IIHF);
DECODE_RIL_A_INSTRUCTION(r1, imm);
set_high_register(r1, imm);
return length;
}
EVALUATE(IILF) {
DCHECK_OPCODE(IILF);
DECODE_RIL_A_INSTRUCTION(r1, imm);
set_low_register(r1, imm);
return length;
}
EVALUATE(LGR) {
DCHECK_OPCODE(LGR);
DECODE_RRE_INSTRUCTION(r1, r2);
set_register(r1, get_register(r2));
return length;
}
EVALUATE(LG) {
DCHECK_OPCODE(LG);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
intptr_t addr = GET_ADDRESS(x2, b2, d2);
int64_t mem_val = ReadDW(addr);
set_register(r1, mem_val);
return length;
}
EVALUATE(AGR) {
DCHECK_OPCODE(AGR);
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r1_val = get_register(r1);
int64_t r2_val = get_register(r2);
bool isOF = CheckOverflowForIntAdd(r1_val, r2_val, int64_t);
r1_val += r2_val;
set_register(r1, r1_val);
SetS390ConditionCode<int64_t>(r1_val, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(LGFR) {
DCHECK_OPCODE(LGFR);
DECODE_RRE_INSTRUCTION(r1, r2);
int32_t r2_val = get_low_register<int32_t>(r2);
int64_t result = static_cast<int64_t>(r2_val);
set_register(r1, result);
return length;
}
EVALUATE(LBR) {
DCHECK_OPCODE(LBR);
DECODE_RRE_INSTRUCTION(r1, r2);
int32_t r2_val = get_low_register<int32_t>(r2);
r2_val <<= 24;
r2_val >>= 24;
set_low_register(r1, r2_val);
return length;
}
EVALUATE(LGBR) {
DCHECK_OPCODE(LGBR);
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r2_val = get_low_register<int64_t>(r2);
r2_val <<= 56;
r2_val >>= 56;
set_register(r1, r2_val);
return length;
}
EVALUATE(LHR) {
DCHECK_OPCODE(LHR);
DECODE_RRE_INSTRUCTION(r1, r2);
int32_t r2_val = get_low_register<int32_t>(r2);
r2_val <<= 16;
r2_val >>= 16;
set_low_register(r1, r2_val);
return length;
}
EVALUATE(LGHR) {
DCHECK_OPCODE(LGHR);
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r2_val = get_low_register<int64_t>(r2);
r2_val <<= 48;
r2_val >>= 48;
set_register(r1, r2_val);
return length;
}
EVALUATE(LGF) {
DCHECK_OPCODE(LGF);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
intptr_t addr = GET_ADDRESS(x2, b2, d2);
int64_t mem_val = static_cast<int64_t>(ReadW(addr, instr));
set_register(r1, mem_val);
return length;
}
EVALUATE(ST) {
DCHECK_OPCODE(ST);
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t addr = b2_val + x2_val + d2_val;
WriteW(addr, r1_val, instr);
return length;
}
EVALUATE(STG) {
DCHECK_OPCODE(STG);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
intptr_t addr = GET_ADDRESS(x2, b2, d2);
uint64_t value = get_register(r1);
WriteDW(addr, value);
return length;
}
EVALUATE(STY) {
DCHECK_OPCODE(STY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
intptr_t addr = GET_ADDRESS(x2, b2, d2);
uint32_t value = get_low_register<uint32_t>(r1);
WriteW(addr, value, instr);
return length;
}
EVALUATE(LY) {
DCHECK_OPCODE(LY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
intptr_t addr = GET_ADDRESS(x2, b2, d2);
uint32_t mem_val = ReadWU(addr, instr);
set_low_register(r1, mem_val);
return length;
}
EVALUATE(LLGC) {
DCHECK_OPCODE(LLGC);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
uint8_t mem_val = ReadBU(GET_ADDRESS(x2, b2, d2));
set_register(r1, static_cast<uint64_t>(mem_val));
return length;
}
EVALUATE(LLC) {
DCHECK_OPCODE(LLC);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
uint8_t mem_val = ReadBU(GET_ADDRESS(x2, b2, d2));
set_low_register(r1, static_cast<uint32_t>(mem_val));
return length;
}
EVALUATE(RLL) {
DCHECK_OPCODE(RLL);
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2);
// only takes rightmost 6 bits
int shiftBits = GET_ADDRESS(0, b2, d2) & 0x3F;
// unsigned
uint32_t r3_val = get_low_register<uint32_t>(r3);
uint32_t alu_out = 0;
uint32_t rotateBits = r3_val >> (32 - shiftBits);
alu_out = (r3_val << shiftBits) | (rotateBits);
set_low_register(r1, alu_out);
return length;
}
EVALUATE(RISBG) {
DCHECK_OPCODE(RISBG);
DECODE_RIE_F_INSTRUCTION(r1, r2, i3, i4, i5);
// Starting Bit Position is Bits 2-7 of I3 field
uint32_t start_bit = i3 & 0x3F;
// Ending Bit Position is Bits 2-7 of I4 field
uint32_t end_bit = i4 & 0x3F;
// Shift Amount is Bits 2-7 of I5 field
uint32_t shift_amount = i5 & 0x3F;
// Zero out Remaining (unslected) bits if Bit 0 of I4 is 1.
bool zero_remaining = (0 != (i4 & 0x80));
uint64_t src_val = get_register(r2);
// Rotate Left by Shift Amount first
uint64_t rotated_val =
(src_val << shift_amount) | (src_val >> (64 - shift_amount));
int32_t width = end_bit - start_bit + 1;
uint64_t selection_mask = 0;
if (width < 64) {
selection_mask = (static_cast<uint64_t>(1) << width) - 1;
} else {
selection_mask = static_cast<uint64_t>(static_cast<int64_t>(-1));
}
selection_mask = selection_mask << (63 - end_bit);
uint64_t selected_val = rotated_val & selection_mask;
if (!zero_remaining) {
// Merged the unselected bits from the original value
selected_val = (get_register(r1) & ~selection_mask) | selected_val;
}
// Condition code is set by treating result as 64-bit signed int
SetS390ConditionCode<int64_t>(selected_val, 0);
set_register(r1, selected_val);
return length;
}
EVALUATE(AHIK) {
DCHECK_OPCODE(AHIK);
DECODE_RIE_D_INSTRUCTION(r1, r2, i2);
int32_t r2_val = get_low_register<int32_t>(r2);
int32_t imm = static_cast<int32_t>(i2);
bool isOF = CheckOverflowForIntAdd(r2_val, imm, int32_t);
set_low_register(r1, r2_val + imm);
SetS390ConditionCode<int32_t>(r2_val + imm, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(AGHIK) {
// 64-bit Add
DCHECK_OPCODE(AGHIK);
DECODE_RIE_D_INSTRUCTION(r1, r2, i2);
int64_t r2_val = get_register(r2);
int64_t imm = static_cast<int64_t>(i2);
bool isOF = CheckOverflowForIntAdd(r2_val, imm, int64_t);
set_register(r1, r2_val + imm);
SetS390ConditionCode<int64_t>(r2_val + imm, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(BKPT) {
DCHECK_OPCODE(BKPT);
set_pc(get_pc() + 2);
S390Debugger dbg(this);
dbg.Debug();
int length = 2;
return length;
}
EVALUATE(SPM) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(BALR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(BCTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(BCR) {
DCHECK_OPCODE(BCR);
DECODE_RR_INSTRUCTION(r1, r2);
if (TestConditionCode(Condition(r1))) {
intptr_t r2_val = get_register(r2);
#if (!V8_TARGET_ARCH_S390X && V8_HOST_ARCH_S390)
// On 31-bit, the top most bit may be 0 or 1, but is ignored by the
// hardware. Cleanse the top bit before jumping to it, unless it's one
// of the special PCs
if (r2_val != bad_lr && r2_val != end_sim_pc) r2_val &= 0x7FFFFFFF;
#endif
set_pc(r2_val);
}
return length;
}
EVALUATE(SVC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(BSM) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(BASSM) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(BASR) {
DCHECK_OPCODE(BASR);
DECODE_RR_INSTRUCTION(r1, r2);
intptr_t link_addr = get_pc() + 2;
// If R2 is zero, the BASR does not branch.
int64_t r2_val = (r2 == 0) ? link_addr : get_register(r2);
#if (!V8_TARGET_ARCH_S390X && V8_HOST_ARCH_S390)
// On 31-bit, the top most bit may be 0 or 1, which can cause issues
// for stackwalker. The top bit should either be cleanse before being
// pushed onto the stack, or during stack walking when dereferenced.
// For simulator, we'll take the worst case scenario and always tag
// the high bit, to flush out more problems.
link_addr |= 0x80000000;
#endif
set_register(r1, link_addr);
set_pc(r2_val);
return length;
}
EVALUATE(MVCL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CLCL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LPR) {
DCHECK_OPCODE(LPR);
// Load Positive (32)
DECODE_RR_INSTRUCTION(r1, r2);
int32_t r2_val = get_low_register<int32_t>(r2);
// If negative, then negate it.
r2_val = (r2_val < 0) ? -r2_val : r2_val;
set_low_register(r1, r2_val);
SetS390ConditionCode<int32_t>(r2_val, 0);
if (r2_val == (static_cast<int32_t>(1) << 31)) {
SetS390OverflowCode(true);
}
return length;
}
EVALUATE(LNR) {
DCHECK_OPCODE(LNR);
// Load Negative (32)
DECODE_RR_INSTRUCTION(r1, r2);
int32_t r2_val = get_low_register<int32_t>(r2);
r2_val = (r2_val >= 0) ? -r2_val : r2_val; // If pos, then negate it.
set_low_register(r1, r2_val);
condition_reg_ = (r2_val == 0) ? CC_EQ : CC_LT; // CC0 - result is zero
// CC1 - result is negative
return length;
}
EVALUATE(LTR) {
DCHECK_OPCODE(LTR);
DECODE_RR_INSTRUCTION(r1, r2);
int32_t r2_val = get_low_register<int32_t>(r2);
SetS390ConditionCode<int32_t>(r2_val, 0);
set_low_register(r1, r2_val);
return length;
}
EVALUATE(LCR) {
DCHECK_OPCODE(LCR);
DECODE_RR_INSTRUCTION(r1, r2);
int32_t r2_val = get_low_register<int32_t>(r2);
int32_t result = 0;
bool isOF = false;
isOF = __builtin_ssub_overflow(0, r2_val, &result);
set_low_register(r1, result);
SetS390ConditionCode<int32_t>(r2_val, 0);
// Checks for overflow where r2_val = -2147483648.
// Cannot do int comparison due to GCC 4.8 bug on x86.
// Detect INT_MIN alternatively, as it is the only value where both
// original and result are negative due to overflow.
if (isOF) {
SetS390OverflowCode(true);
}
return length;
}
EVALUATE(NR) {
DCHECK_OPCODE(NR);
DECODE_RR_INSTRUCTION(r1, r2);
int32_t r1_val = get_low_register<int32_t>(r1);
int32_t r2_val = get_low_register<int32_t>(r2);
r1_val &= r2_val;
SetS390BitWiseConditionCode<uint32_t>(r1_val);
set_low_register(r1, r1_val);
return length;
}
EVALUATE(OR) {
DCHECK_OPCODE(OR);
DECODE_RR_INSTRUCTION(r1, r2);
int32_t r1_val = get_low_register<int32_t>(r1);
int32_t r2_val = get_low_register<int32_t>(r2);
r1_val |= r2_val;
SetS390BitWiseConditionCode<uint32_t>(r1_val);
set_low_register(r1, r1_val);
return length;
}
EVALUATE(XR) {
DCHECK_OPCODE(XR);
DECODE_RR_INSTRUCTION(r1, r2);
int32_t r1_val = get_low_register<int32_t>(r1);
int32_t r2_val = get_low_register<int32_t>(r2);
r1_val ^= r2_val;
SetS390BitWiseConditionCode<uint32_t>(r1_val);
set_low_register(r1, r1_val);
return length;
}
EVALUATE(CR) {
DCHECK_OPCODE(CR);
DECODE_RR_INSTRUCTION(r1, r2);
int32_t r1_val = get_low_register<int32_t>(r1);
int32_t r2_val = get_low_register<int32_t>(r2);
SetS390ConditionCode<int32_t>(r1_val, r2_val);
return length;
}
EVALUATE(SR) {
DCHECK_OPCODE(SR);
DECODE_RR_INSTRUCTION(r1, r2);
int32_t r1_val = get_low_register<int32_t>(r1);
int32_t r2_val = get_low_register<int32_t>(r2);
bool isOF = false;
isOF = CheckOverflowForIntSub(r1_val, r2_val, int32_t);
r1_val -= r2_val;
SetS390ConditionCode<int32_t>(r1_val, 0);
SetS390OverflowCode(isOF);
set_low_register(r1, r1_val);
return length;
}
EVALUATE(MR) {
DCHECK_OPCODE(MR);
DECODE_RR_INSTRUCTION(r1, r2);
int32_t r1_val = get_low_register<int32_t>(r1);
int32_t r2_val = get_low_register<int32_t>(r2);
DCHECK_EQ(r1 % 2, 0);
r1_val = get_low_register<int32_t>(r1 + 1);
int64_t product = static_cast<int64_t>(r1_val) * static_cast<int64_t>(r2_val);
int32_t high_bits = product >> 32;
r1_val = high_bits;
int32_t low_bits = product & 0x00000000FFFFFFFF;
set_low_register(r1, high_bits);
set_low_register(r1 + 1, low_bits);
return length;
}
EVALUATE(DR) {
DCHECK_OPCODE(DR);
DECODE_RR_INSTRUCTION(r1, r2);
int32_t r1_val = get_low_register<int32_t>(r1);
int32_t r2_val = get_low_register<int32_t>(r2);
// reg-reg pair should be even-odd pair, assert r1 is an even register
DCHECK_EQ(r1 % 2, 0);
// leftmost 32 bits of the dividend are in r1
// rightmost 32 bits of the dividend are in r1+1
// get the signed value from r1
int64_t dividend = static_cast<int64_t>(r1_val) << 32;
// get unsigned value from r1+1
// avoid addition with sign-extended r1+1 value
dividend += get_low_register<uint32_t>(r1 + 1);
int32_t remainder = dividend % r2_val;
int32_t quotient = dividend / r2_val;
r1_val = remainder;
set_low_register(r1, remainder);
set_low_register(r1 + 1, quotient);
set_low_register(r1, r1_val);
return length;
}
EVALUATE(ALR) {
DCHECK_OPCODE(ALR);
DECODE_RR_INSTRUCTION(r1, r2);
uint32_t r1_val = get_low_register<uint32_t>(r1);
uint32_t r2_val = get_low_register<uint32_t>(r2);
uint32_t alu_out = 0;
bool isOF = false;
alu_out = r1_val + r2_val;
isOF = CheckOverflowForUIntAdd(r1_val, r2_val);
set_low_register(r1, alu_out);
SetS390ConditionCodeCarry<uint32_t>(alu_out, isOF);
return length;
}
EVALUATE(SLR) {
DCHECK_OPCODE(SLR);
DECODE_RR_INSTRUCTION(r1, r2);
uint32_t r1_val = get_low_register<uint32_t>(r1);
uint32_t r2_val = get_low_register<uint32_t>(r2);
uint32_t alu_out = 0;
bool isOF = false;
alu_out = r1_val - r2_val;
isOF = CheckOverflowForUIntSub(r1_val, r2_val);
set_low_register(r1, alu_out);
SetS390ConditionCodeCarry<uint32_t>(alu_out, isOF);
return length;
}
EVALUATE(LDR) {
DCHECK_OPCODE(LDR);
DECODE_RR_INSTRUCTION(r1, r2);
int64_t r2_val = get_d_register(r2);
set_d_register(r1, r2_val);
return length;
}
EVALUATE(CDR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LER) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STH) {
DCHECK_OPCODE(STH);
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int16_t r1_val = get_low_register<int32_t>(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t mem_addr = b2_val + x2_val + d2_val;
WriteH(mem_addr, r1_val, instr);
return length;
}
EVALUATE(LA) {
DCHECK_OPCODE(LA);
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t addr = b2_val + x2_val + d2_val;
set_register(r1, addr);
return length;
}
EVALUATE(STC) {
DCHECK_OPCODE(STC);
// Store Character/Byte
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
uint8_t r1_val = get_low_register<int32_t>(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t mem_addr = b2_val + x2_val + d2_val;
WriteB(mem_addr, r1_val);
return length;
}
EVALUATE(IC_z) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(EX) {
DCHECK_OPCODE(EX);
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int32_t r1_val = get_low_register<int32_t>(r1);
SixByteInstr the_instr = Instruction::InstructionBits(
reinterpret_cast<const byte*>(b2_val + x2_val + d2_val));
int inst_length = Instruction::InstructionLength(
reinterpret_cast<const byte*>(b2_val + x2_val + d2_val));
char new_instr_buf[8];
char* addr = reinterpret_cast<char*>(&new_instr_buf[0]);
the_instr |= static_cast<SixByteInstr>(r1_val & 0xFF)
<< (8 * inst_length - 16);
Instruction::SetInstructionBits<SixByteInstr>(
reinterpret_cast<byte*>(addr), static_cast<SixByteInstr>(the_instr));
ExecuteInstruction(reinterpret_cast<Instruction*>(addr), false);
return length;
}
EVALUATE(BAL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(BCT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(BC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LH) {
DCHECK_OPCODE(LH);
// Load Halfword
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t mem_addr = x2_val + b2_val + d2_val;
int32_t result = static_cast<int32_t>(ReadH(mem_addr, instr));
set_low_register(r1, result);
return length;
}
EVALUATE(CH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(AH) {
DCHECK_OPCODE(AH);
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t addr = b2_val + x2_val + d2_val;
int32_t mem_val = static_cast<int32_t>(ReadH(addr, instr));
int32_t alu_out = 0;
bool isOF = false;
isOF = CheckOverflowForIntAdd(r1_val, mem_val, int32_t);
alu_out = r1_val + mem_val;
set_low_register(r1, alu_out);
SetS390ConditionCode<int32_t>(alu_out, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(SH) {
DCHECK_OPCODE(SH);
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t addr = b2_val + x2_val + d2_val;
int32_t mem_val = static_cast<int32_t>(ReadH(addr, instr));
int32_t alu_out = 0;
bool isOF = false;
isOF = CheckOverflowForIntSub(r1_val, mem_val, int32_t);
alu_out = r1_val - mem_val;
SetS390ConditionCode<int32_t>(alu_out, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(MH) {
DCHECK_OPCODE(MH);
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t addr = b2_val + x2_val + d2_val;
int32_t mem_val = static_cast<int32_t>(ReadH(addr, instr));
int32_t alu_out = 0;
alu_out = r1_val * mem_val;
set_low_register(r1, alu_out);
return length;
}
EVALUATE(BAS) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CVD) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CVB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LAE) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(N) {
DCHECK_OPCODE(N);
// 32-bit Reg-Mem instructions
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int32_t mem_val = ReadW(b2_val + x2_val + d2_val, instr);
int32_t alu_out = 0;
alu_out = r1_val & mem_val;
SetS390BitWiseConditionCode<uint32_t>(alu_out);
set_low_register(r1, alu_out);
return length;
}
EVALUATE(CL) {
DCHECK_OPCODE(CL);
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t addr = b2_val + x2_val + d2_val;
int32_t mem_val = ReadW(addr, instr);
SetS390ConditionCode<uint32_t>(r1_val, mem_val);
return length;
}
EVALUATE(O) {
DCHECK_OPCODE(O);
// 32-bit Reg-Mem instructions
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int32_t mem_val = ReadW(b2_val + x2_val + d2_val, instr);
int32_t alu_out = 0;
alu_out = r1_val | mem_val;
SetS390BitWiseConditionCode<uint32_t>(alu_out);
set_low_register(r1, alu_out);
return length;
}
EVALUATE(X) {
DCHECK_OPCODE(X);
// 32-bit Reg-Mem instructions
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int32_t mem_val = ReadW(b2_val + x2_val + d2_val, instr);
int32_t alu_out = 0;
alu_out = r1_val ^ mem_val;
SetS390BitWiseConditionCode<uint32_t>(alu_out);
set_low_register(r1, alu_out);
return length;
}
EVALUATE(C) {
DCHECK_OPCODE(C);
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t addr = b2_val + x2_val + d2_val;
int32_t mem_val = ReadW(addr, instr);
SetS390ConditionCode<int32_t>(r1_val, mem_val);
return length;
}
EVALUATE(A) {
DCHECK_OPCODE(A);
// 32-bit Reg-Mem instructions
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int32_t mem_val = ReadW(b2_val + x2_val + d2_val, instr);
int32_t alu_out = 0;
bool isOF = false;
isOF = CheckOverflowForIntAdd(r1_val, mem_val, int32_t);
alu_out = r1_val + mem_val;
SetS390ConditionCode<int32_t>(alu_out, 0);
SetS390OverflowCode(isOF);
set_low_register(r1, alu_out);
return length;
}
EVALUATE(S) {
DCHECK_OPCODE(S);
// 32-bit Reg-Mem instructions
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int32_t mem_val = ReadW(b2_val + x2_val + d2_val, instr);
int32_t alu_out = 0;
bool isOF = false;
isOF = CheckOverflowForIntSub(r1_val, mem_val, int32_t);
alu_out = r1_val - mem_val;
SetS390ConditionCode<int32_t>(alu_out, 0);
SetS390OverflowCode(isOF);
set_low_register(r1, alu_out);
return length;
}
EVALUATE(M) {
DCHECK_OPCODE(M);
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t addr = b2_val + x2_val + d2_val;
DCHECK_EQ(r1 % 2, 0);
int32_t mem_val = ReadW(addr, instr);
int32_t r1_val = get_low_register<int32_t>(r1 + 1);
int64_t product =
static_cast<int64_t>(r1_val) * static_cast<int64_t>(mem_val);
int32_t high_bits = product >> 32;
r1_val = high_bits;
int32_t low_bits = product & 0x00000000FFFFFFFF;
set_low_register(r1, high_bits);
set_low_register(r1 + 1, low_bits);
return length;
}
EVALUATE(D) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(AL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STD) {
DCHECK_OPCODE(STD);
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t addr = b2_val + x2_val + d2_val;
int64_t frs_val = get_d_register(r1);
WriteDW(addr, frs_val);
return length;
}
EVALUATE(LD) {
DCHECK_OPCODE(LD);
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t addr = b2_val + x2_val + d2_val;
int64_t dbl_val = *reinterpret_cast<int64_t*>(addr);
set_d_register(r1, dbl_val);
return length;
}
EVALUATE(CD) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STE) {
DCHECK_OPCODE(STE);
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t addr = b2_val + x2_val + d2_val;
int64_t frs_val = get_d_register(r1) >> 32;
WriteW(addr, static_cast<int32_t>(frs_val), instr);
return length;
}
EVALUATE(MS) {
DCHECK_OPCODE(MS);
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int32_t mem_val = ReadW(b2_val + x2_val + d2_val, instr);
int32_t r1_val = get_low_register<int32_t>(r1);
set_low_register(r1, r1_val * mem_val);
return length;
}
EVALUATE(LE) {
DCHECK_OPCODE(LE);
DECODE_RX_A_INSTRUCTION(x2, b2, r1, d2_val);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t addr = b2_val + x2_val + d2_val;
float float_val = *reinterpret_cast<float*>(addr);
set_d_register_from_float32(r1, float_val);
return length;
}
EVALUATE(BRXH) {
DCHECK_OPCODE(BRXH);
DECODE_RSI_INSTRUCTION(r1, r3, i2);
int32_t r1_val = (r1 == 0) ? 0 : get_low_register<int32_t>(r1);
int32_t r3_val = (r3 == 0) ? 0 : get_low_register<int32_t>(r3);
intptr_t branch_address = get_pc() + (2 * i2);
r1_val += r3_val;
int32_t compare_val =
r3 % 2 == 0 ? get_low_register<int32_t>(r3 + 1) : r3_val;
if (r1_val > compare_val) {
set_pc(branch_address);
}
set_low_register(r1, r1_val);
return length;
}
EVALUATE(BRXLE) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(BXH) {
DCHECK_OPCODE(BXH);
DECODE_RS_A_INSTRUCTION(r1, r3, b2, d2);
// r1_val is the first operand, r3_val is the increment
int32_t r1_val = (r1 == 0) ? 0 : get_register(r1);
int32_t r3_val = (r3 == 0) ? 0 : get_register(r3);
intptr_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t branch_address = b2_val + d2;
// increment r1_val
r1_val += r3_val;
// if the increment is even, then it designates a pair of registers
// and the contents of the even and odd registers of the pair are used as
// the increment and compare value respectively. If the increment is odd,
// the increment itself is used as both the increment and compare value
int32_t compare_val = r3 % 2 == 0 ? get_register(r3 + 1) : r3_val;
if (r1_val > compare_val) {
// branch to address if r1_val is greater than compare value
set_pc(branch_address);
}
// update contents of register in r1 with the new incremented value
set_register(r1, r1_val);
return length;
}
EVALUATE(BXLE) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SRL) {
DCHECK_OPCODE(SRL);
DECODE_RS_A_INSTRUCTION_NO_R3(r1, b2, d2);
// only takes rightmost 6bits
int64_t b2_val = b2 == 0 ? 0 : get_register(b2);
int shiftBits = (b2_val + d2) & 0x3F;
uint32_t r1_val = get_low_register<uint32_t>(r1);
uint32_t alu_out = 0;
alu_out = r1_val >> shiftBits;
set_low_register(r1, alu_out);
return length;
}
EVALUATE(SLL) {
DCHECK_OPCODE(SLL);
DECODE_RS_A_INSTRUCTION_NO_R3(r1, b2, d2)
// only takes rightmost 6bits
int64_t b2_val = b2 == 0 ? 0 : get_register(b2);
int shiftBits = (b2_val + d2) & 0x3F;
uint32_t r1_val = get_low_register<uint32_t>(r1);
uint32_t alu_out = 0;
alu_out = r1_val << shiftBits;
set_low_register(r1, alu_out);
return length;
}
EVALUATE(SRA) {
DCHECK_OPCODE(SRA);
DECODE_RS_A_INSTRUCTION_NO_R3(r1, b2, d2);
// only takes rightmost 6bits
int64_t b2_val = b2 == 0 ? 0 : get_register(b2);
int shiftBits = (b2_val + d2) & 0x3F;
int32_t r1_val = get_low_register<int32_t>(r1);
int32_t alu_out = 0;
bool isOF = false;
alu_out = r1_val >> shiftBits;
set_low_register(r1, alu_out);
SetS390ConditionCode<int32_t>(alu_out, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(SLA) {
DCHECK_OPCODE(SLA);
DECODE_RS_A_INSTRUCTION_NO_R3(r1, b2, d2);
// only takes rightmost 6bits
int64_t b2_val = b2 == 0 ? 0 : get_register(b2);
int shiftBits = (b2_val + d2) & 0x3F;
int32_t r1_val = get_low_register<int32_t>(r1);
int32_t alu_out = 0;
bool isOF = false;
isOF = CheckOverflowForShiftLeft(r1_val, shiftBits);
alu_out = r1_val << shiftBits;
set_low_register(r1, alu_out);
SetS390ConditionCode<int32_t>(alu_out, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(SRDL) {
DCHECK_OPCODE(SRDL);
DECODE_RS_A_INSTRUCTION_NO_R3(r1, b2, d2);
DCHECK_EQ(r1 % 2, 0); // must be a reg pair
// only takes rightmost 6bits
int64_t b2_val = b2 == 0 ? 0 : get_register(b2);
int shiftBits = (b2_val + d2) & 0x3F;
uint64_t opnd1 = static_cast<uint64_t>(get_low_register<uint32_t>(r1)) << 32;
uint64_t opnd2 = static_cast<uint64_t>(get_low_register<uint32_t>(r1 + 1));
uint64_t r1_val = opnd1 | opnd2;
uint64_t alu_out = r1_val >> shiftBits;
set_low_register(r1, alu_out >> 32);
set_low_register(r1 + 1, alu_out & 0x00000000FFFFFFFF);
SetS390ConditionCode<int32_t>(alu_out, 0);
return length;
}
EVALUATE(SLDL) {
DCHECK_OPCODE(SLDL);
DECODE_RS_A_INSTRUCTION_NO_R3(r1, b2, d2);
// only takes rightmost 6bits
int64_t b2_val = b2 == 0 ? 0 : get_register(b2);
int shiftBits = (b2_val + d2) & 0x3F;
DCHECK_EQ(r1 % 2, 0);
uint32_t r1_val = get_low_register<uint32_t>(r1);
uint32_t r1_next_val = get_low_register<uint32_t>(r1 + 1);
uint64_t alu_out = (static_cast<uint64_t>(r1_val) << 32) |
(static_cast<uint64_t>(r1_next_val));
alu_out <<= shiftBits;
set_low_register(r1 + 1, static_cast<uint32_t>(alu_out));
set_low_register(r1, static_cast<uint32_t>(alu_out >> 32));
return length;
}
EVALUATE(SRDA) {
DCHECK_OPCODE(SRDA);
DECODE_RS_A_INSTRUCTION_NO_R3(r1, b2, d2);
DCHECK_EQ(r1 % 2, 0); // must be a reg pair
// only takes rightmost 6bits
int64_t b2_val = b2 == 0 ? 0 : get_register(b2);
int shiftBits = (b2_val + d2) & 0x3F;
int64_t opnd1 = static_cast<int64_t>(get_low_register<int32_t>(r1)) << 32;
int64_t opnd2 = static_cast<uint64_t>(get_low_register<uint32_t>(r1 + 1));
int64_t r1_val = opnd1 + opnd2;
int64_t alu_out = r1_val >> shiftBits;
set_low_register(r1, alu_out >> 32);
set_low_register(r1 + 1, alu_out & 0x00000000FFFFFFFF);
SetS390ConditionCode<int32_t>(alu_out, 0);
return length;
}
EVALUATE(SLDA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STM) {
DCHECK_OPCODE(STM);
DECODE_RS_A_INSTRUCTION(r1, r3, rb, d2);
// Store Multiple 32-bits.
int offset = d2;
// Regs roll around if r3 is less than r1.
// Artificially increase r3 by 16 so we can calculate
// the number of regs stored properly.
if (r3 < r1) r3 += 16;
int32_t rb_val = (rb == 0) ? 0 : get_low_register<int32_t>(rb);
// Store each register in ascending order.
for (int i = 0; i <= r3 - r1; i++) {
int32_t value = get_low_register<int32_t>((r1 + i) % 16);
WriteW(rb_val + offset + 4 * i, value, instr);
}
return length;
}
EVALUATE(MVI) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TS) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(NI) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CLI) {
DCHECK_OPCODE(CLI);
// Compare Immediate (Mem - Imm) (8)
DECODE_SI_INSTRUCTION_I_UINT8(b1, d1_val, imm_val)
int64_t b1_val = (b1 == 0) ? 0 : get_register(b1);
intptr_t addr = b1_val + d1_val;
uint8_t mem_val = ReadB(addr);
SetS390ConditionCode<uint8_t>(mem_val, imm_val);
return length;
}
EVALUATE(OI) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(XI) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LM) {
DCHECK_OPCODE(LM);
DECODE_RS_A_INSTRUCTION(r1, r3, rb, d2);
// Store Multiple 32-bits.
int offset = d2;
// Regs roll around if r3 is less than r1.
// Artificially increase r3 by 16 so we can calculate
// the number of regs stored properly.
if (r3 < r1) r3 += 16;
int32_t rb_val = (rb == 0) ? 0 : get_low_register<int32_t>(rb);
// Store each register in ascending order.
for (int i = 0; i <= r3 - r1; i++) {
int32_t value = ReadW(rb_val + offset + 4 * i, instr);
set_low_register((r1 + i) % 16, value);
}
return length;
}
EVALUATE(MVCLE) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CLCLE) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CDS) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STCM) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ICM) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(BPRP) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(BPP) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TRTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MVN) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MVC) {
DCHECK_OPCODE(MVC);
// Move Character
SSInstruction* ssInstr = reinterpret_cast<SSInstruction*>(instr);
int b1 = ssInstr->B1Value();
intptr_t d1 = ssInstr->D1Value();
int b2 = ssInstr->B2Value();
intptr_t d2 = ssInstr->D2Value();
int length = ssInstr->Length();
int64_t b1_val = (b1 == 0) ? 0 : get_register(b1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t src_addr = b2_val + d2;
intptr_t dst_addr = b1_val + d1;
// remember that the length is the actual length - 1
for (int i = 0; i < length + 1; ++i) {
WriteB(dst_addr++, ReadB(src_addr++));
}
length = 6;
return length;
}
EVALUATE(MVZ) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(NC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CLC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(OC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(XC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MVCP) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TRT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ED) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(EDMK) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(PKU) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(UNPKU) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MVCIN) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(PKA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(UNPKA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(PLO) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LMD) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SRP) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MVO) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(PACK) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(UNPK) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ZAP) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(AP) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SP) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MP) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(DP) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(UPT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(PFPO) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(IIHH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(IIHL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(IILH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(IILL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(NIHH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(NIHL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(NILH) {
DCHECK_OPCODE(NILH);
DECODE_RI_A_INSTRUCTION(instr, r1, i);
int32_t r1_val = get_low_register<int32_t>(r1);
// CC is set based on the 16 bits that are AND'd
SetS390BitWiseConditionCode<uint16_t>((r1_val >> 16) & i);
i = (i << 16) | 0x0000FFFF;
set_low_register(r1, r1_val & i);
return length;
}
EVALUATE(NILL) {
DCHECK_OPCODE(NILL);
DECODE_RI_A_INSTRUCTION(instr, r1, i);
int32_t r1_val = get_low_register<int32_t>(r1);
// CC is set based on the 16 bits that are AND'd
SetS390BitWiseConditionCode<uint16_t>(r1_val & i);
i |= 0xFFFF0000;
set_low_register(r1, r1_val & i);
return length;
}
EVALUATE(OIHH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(OIHL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(OILH) {
DCHECK_OPCODE(OILH);
DECODE_RI_A_INSTRUCTION(instr, r1, i);
int32_t r1_val = get_low_register<int32_t>(r1);
// CC is set based on the 16 bits that are AND'd
SetS390BitWiseConditionCode<uint16_t>((r1_val >> 16) | i);
i = i << 16;
set_low_register(r1, r1_val | i);
return length;
}
EVALUATE(OILL) {
DCHECK_OPCODE(OILL);
DECODE_RI_A_INSTRUCTION(instr, r1, i);
int32_t r1_val = get_low_register<int32_t>(r1);
// CC is set based on the 16 bits that are AND'd
SetS390BitWiseConditionCode<uint16_t>(r1_val | i);
set_low_register(r1, r1_val | i);
return length;
}
EVALUATE(LLIHH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LLIHL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LLILH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LLILL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
inline static int TestUnderMask(uint16_t val, uint16_t mask,
bool is_tm_or_tmy) {
// Test if all selected bits are zeros or mask is zero
if (0 == (mask & val)) {
return 0x8;
}
// Test if all selected bits are one or mask is 0
if (mask == (mask & val)) {
return 0x1;
}
// Now we know selected bits mixed zeros and ones
// Test if it is TM or TMY since they have
// different CC result from TMLL/TMLH/TMHH/TMHL
if (is_tm_or_tmy) {
return 0x4;
}
// Now we know the instruction is TMLL/TMLH/TMHH/TMHL
// Test if the leftmost bit is zero or one
#if defined(__GNUC__)
int leadingZeros = __builtin_clz(mask);
mask = 0x80000000u >> leadingZeros;
if (mask & val) {
// leftmost bit is one
return 0x2;
} else {
// leftmost bit is zero
return 0x4;
}
#else
for (int i = 15; i >= 0; i--) {
if (mask & (1 << i)) {
if (val & (1 << i)) {
// leftmost bit is one
return 0x2;
} else {
// leftmost bit is zero
return 0x4;
}
}
}
#endif
UNREACHABLE();
}
EVALUATE(TMLH) {
DCHECK_OPCODE(TMLH);
DECODE_RI_A_INSTRUCTION(instr, r1, i2);
uint32_t value = get_low_register<uint32_t>(r1) >> 16;
uint32_t mask = i2 & 0x0000FFFF;
bool is_tm_or_tmy = 0;
condition_reg_ = TestUnderMask(value, mask, is_tm_or_tmy);
return length; // DONE
}
EVALUATE(TMLL) {
DCHECK_OPCODE(TMLL);
DECODE_RI_A_INSTRUCTION(instr, r1, i2);
uint32_t value = get_low_register<uint32_t>(r1) & 0x0000FFFF;
uint32_t mask = i2 & 0x0000FFFF;
bool is_tm_or_tmy = 0;
condition_reg_ = TestUnderMask(value, mask, is_tm_or_tmy);
return length; // DONE
}
EVALUATE(TMHH) {
DCHECK_OPCODE(TMHH);
DECODE_RI_A_INSTRUCTION(instr, r1, i2);
uint32_t value = get_high_register<uint32_t>(r1) >> 16;
uint32_t mask = i2 & 0x0000FFFF;
bool is_tm_or_tmy = 0;
condition_reg_ = TestUnderMask(value, mask, is_tm_or_tmy);
return length;
}
EVALUATE(TMHL) {
DCHECK_OPCODE(TMHL);
DECODE_RI_A_INSTRUCTION(instr, r1, i2);
uint32_t value = get_high_register<uint32_t>(r1) & 0x0000FFFF;
uint32_t mask = i2 & 0x0000FFFF;
bool is_tm_or_tmy = 0;
condition_reg_ = TestUnderMask(value, mask, is_tm_or_tmy);
return length;
}
EVALUATE(BRAS) {
DCHECK_OPCODE(BRAS);
// Branch Relative and Save
DECODE_RI_B_INSTRUCTION(instr, r1, d2)
intptr_t pc = get_pc();
// Set PC of next instruction to register
set_register(r1, pc + sizeof(FourByteInstr));
// Update PC to branch target
set_pc(pc + d2 * 2);
return length;
}
EVALUATE(BRCT) {
DCHECK_OPCODE(BRCT);
// Branch On Count (32/64).
DECODE_RI_A_INSTRUCTION(instr, r1, i2);
int64_t value = get_low_register<int32_t>(r1);
set_low_register(r1, --value);
// Branch if value != 0
if (value != 0) {
intptr_t offset = i2 * 2;
set_pc(get_pc() + offset);
}
return length;
}
EVALUATE(BRCTG) {
DCHECK_OPCODE(BRCTG);
// Branch On Count (32/64).
DECODE_RI_A_INSTRUCTION(instr, r1, i2);
int64_t value = get_register(r1);
set_register(r1, --value);
// Branch if value != 0
if (value != 0) {
intptr_t offset = i2 * 2;
set_pc(get_pc() + offset);
}
return length;
}
EVALUATE(LHI) {
DCHECK_OPCODE(LHI);
DECODE_RI_A_INSTRUCTION(instr, r1, i);
set_low_register(r1, i);
return length;
}
EVALUATE(LGHI) {
DCHECK_OPCODE(LGHI);
DECODE_RI_A_INSTRUCTION(instr, r1, i2);
int64_t i = static_cast<int64_t>(i2);
set_register(r1, i);
return length;
}
EVALUATE(MHI) {
DCHECK_OPCODE(MHI);
DECODE_RI_A_INSTRUCTION(instr, r1, i);
int32_t r1_val = get_low_register<int32_t>(r1);
bool isOF = false;
isOF = CheckOverflowForMul(r1_val, i);
r1_val *= i;
set_low_register(r1, r1_val);
SetS390ConditionCode<int32_t>(r1_val, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(MGHI) {
DCHECK_OPCODE(MGHI);
DECODE_RI_A_INSTRUCTION(instr, r1, i2);
int64_t i = static_cast<int64_t>(i2);
int64_t r1_val = get_register(r1);
bool isOF = false;
isOF = CheckOverflowForMul(r1_val, i);
r1_val *= i;
set_register(r1, r1_val);
SetS390ConditionCode<int32_t>(r1_val, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(CHI) {
DCHECK_OPCODE(CHI);
DECODE_RI_A_INSTRUCTION(instr, r1, i);
int32_t r1_val = get_low_register<int32_t>(r1);
SetS390ConditionCode<int32_t>(r1_val, i);
return length;
}
EVALUATE(CGHI) {
DCHECK_OPCODE(CGHI);
DECODE_RI_A_INSTRUCTION(instr, r1, i2);
int64_t i = static_cast<int64_t>(i2);
int64_t r1_val = get_register(r1);
SetS390ConditionCode<int64_t>(r1_val, i);
return length;
}
EVALUATE(LARL) {
DCHECK_OPCODE(LARL);
DECODE_RIL_B_INSTRUCTION(r1, i2);
intptr_t offset = i2 * 2;
set_register(r1, get_pc() + offset);
return length;
}
EVALUATE(LGFI) {
DCHECK_OPCODE(LGFI);
DECODE_RIL_A_INSTRUCTION(r1, imm);
set_register(r1, static_cast<int64_t>(static_cast<int32_t>(imm)));
return length;
}
EVALUATE(BRASL) {
DCHECK_OPCODE(BRASL);
// Branch and Save Relative Long
DECODE_RIL_B_INSTRUCTION(r1, i2);
intptr_t d2 = i2;
intptr_t pc = get_pc();
set_register(r1, pc + 6); // save next instruction to register
set_pc(pc + d2 * 2); // update register
return length;
}
EVALUATE(XIHF) {
DCHECK_OPCODE(XIHF);
DECODE_RIL_A_INSTRUCTION(r1, imm);
uint32_t alu_out = 0;
alu_out = get_high_register<uint32_t>(r1);
alu_out = alu_out ^ imm;
set_high_register(r1, alu_out);
SetS390BitWiseConditionCode<uint32_t>(alu_out);
return length;
}
EVALUATE(XILF) {
DCHECK_OPCODE(XILF);
DECODE_RIL_A_INSTRUCTION(r1, imm);
uint32_t alu_out = 0;
alu_out = get_low_register<uint32_t>(r1);
alu_out = alu_out ^ imm;
set_low_register(r1, alu_out);
SetS390BitWiseConditionCode<uint32_t>(alu_out);
return length;
}
EVALUATE(NIHF) {
DCHECK_OPCODE(NIHF);
// Bitwise Op on upper 32-bits
DECODE_RIL_A_INSTRUCTION(r1, imm);
uint32_t alu_out = get_high_register<uint32_t>(r1);
alu_out &= imm;
SetS390BitWiseConditionCode<uint32_t>(alu_out);
set_high_register(r1, alu_out);
return length;
}
EVALUATE(NILF) {
DCHECK_OPCODE(NILF);
// Bitwise Op on lower 32-bits
DECODE_RIL_A_INSTRUCTION(r1, imm);
uint32_t alu_out = get_low_register<uint32_t>(r1);
alu_out &= imm;
SetS390BitWiseConditionCode<uint32_t>(alu_out);
set_low_register(r1, alu_out);
return length;
}
EVALUATE(OIHF) {
DCHECK_OPCODE(OIHF);
// Bitwise Op on upper 32-bits
DECODE_RIL_B_INSTRUCTION(r1, imm);
uint32_t alu_out = get_high_register<uint32_t>(r1);
alu_out |= imm;
SetS390BitWiseConditionCode<uint32_t>(alu_out);
set_high_register(r1, alu_out);
return length;
}
EVALUATE(OILF) {
DCHECK_OPCODE(OILF);
// Bitwise Op on lower 32-bits
DECODE_RIL_B_INSTRUCTION(r1, imm);
uint32_t alu_out = get_low_register<uint32_t>(r1);
alu_out |= imm;
SetS390BitWiseConditionCode<uint32_t>(alu_out);
set_low_register(r1, alu_out);
return length;
}
EVALUATE(LLIHF) {
DCHECK_OPCODE(LLIHF);
// Load Logical Immediate into high word
DECODE_RIL_A_INSTRUCTION(r1, i2);
uint64_t imm = static_cast<uint64_t>(i2);
set_register(r1, imm << 32);
return length;
}
EVALUATE(LLILF) {
DCHECK_OPCODE(LLILF);
// Load Logical into lower 32-bits (zero extend upper 32-bits)
DECODE_RIL_A_INSTRUCTION(r1, i2);
uint64_t imm = static_cast<uint64_t>(i2);
set_register(r1, imm);
return length;
}
EVALUATE(MSGFI) {
DCHECK_OPCODE(MSGFI);
DECODE_RIL_B_INSTRUCTION(r1, i2);
int64_t alu_out = get_register(r1);
alu_out = alu_out * i2;
set_register(r1, alu_out);
return length;
}
EVALUATE(MSFI) {
DCHECK_OPCODE(MSFI);
DECODE_RIL_B_INSTRUCTION(r1, i2);
int32_t alu_out = get_low_register<int32_t>(r1);
alu_out = alu_out * i2;
set_low_register(r1, alu_out);
return length;
}
EVALUATE(SLGFI) {
DCHECK_OPCODE(SLGFI);
#ifndef V8_TARGET_ARCH_S390X
// should only be called on 64bit
DCHECK(false);
#endif
DECODE_RIL_A_INSTRUCTION(r1, i2);
uint64_t r1_val = (uint64_t)(get_register(r1));
uint64_t alu_out;
alu_out = r1_val - i2;
set_register(r1, (intptr_t)alu_out);
SetS390ConditionCode<uint64_t>(alu_out, 0);
return length;
}
EVALUATE(SLFI) {
DCHECK_OPCODE(SLFI);
DECODE_RIL_A_INSTRUCTION(r1, imm);
uint32_t alu_out = get_low_register<uint32_t>(r1);
alu_out -= imm;
SetS390ConditionCode<uint32_t>(alu_out, 0);
set_low_register(r1, alu_out);
return length;
}
EVALUATE(AGFI) {
DCHECK_OPCODE(AGFI);
// Clobbering Add Word Immediate
DECODE_RIL_B_INSTRUCTION(r1, i2_val);
bool isOF = false;
// 64-bit Add (Register + 32-bit Imm)
int64_t r1_val = get_register(r1);
int64_t i2 = static_cast<int64_t>(i2_val);
isOF = CheckOverflowForIntAdd(r1_val, i2, int64_t);
int64_t alu_out = r1_val + i2;
set_register(r1, alu_out);
SetS390ConditionCode<int64_t>(alu_out, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(AFI) {
DCHECK_OPCODE(AFI);
// Clobbering Add Word Immediate
DECODE_RIL_B_INSTRUCTION(r1, i2);
bool isOF = false;
// 32-bit Add (Register + 32-bit Immediate)
int32_t r1_val = get_low_register<int32_t>(r1);
isOF = CheckOverflowForIntAdd(r1_val, i2, int32_t);
int32_t alu_out = r1_val + i2;
set_low_register(r1, alu_out);
SetS390ConditionCode<int32_t>(alu_out, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(ALGFI) {
DCHECK_OPCODE(ALGFI);
#ifndef V8_TARGET_ARCH_S390X
// should only be called on 64bit
DCHECK(false);
#endif
DECODE_RIL_A_INSTRUCTION(r1, i2);
uint64_t r1_val = (uint64_t)(get_register(r1));
uint64_t alu_out;
alu_out = r1_val + i2;
set_register(r1, (intptr_t)alu_out);
SetS390ConditionCode<uint64_t>(alu_out, 0);
return length;
}
EVALUATE(ALFI) {
DCHECK_OPCODE(ALFI);
DECODE_RIL_A_INSTRUCTION(r1, imm);
uint32_t alu_out = get_low_register<uint32_t>(r1);
alu_out += imm;
SetS390ConditionCode<uint32_t>(alu_out, 0);
set_low_register(r1, alu_out);
return length;
}
EVALUATE(CGFI) {
DCHECK_OPCODE(CGFI);
// Compare with Immediate (64)
DECODE_RIL_B_INSTRUCTION(r1, i2);
int64_t imm = static_cast<int64_t>(i2);
SetS390ConditionCode<int64_t>(get_register(r1), imm);
return length;
}
EVALUATE(CFI) {
DCHECK_OPCODE(CFI);
// Compare with Immediate (32)
DECODE_RIL_B_INSTRUCTION(r1, imm);
SetS390ConditionCode<int32_t>(get_low_register<int32_t>(r1), imm);
return length;
}
EVALUATE(CLGFI) {
DCHECK_OPCODE(CLGFI);
// Compare Logical with Immediate (64)
DECODE_RIL_A_INSTRUCTION(r1, i2);
uint64_t imm = static_cast<uint64_t>(i2);
SetS390ConditionCode<uint64_t>(get_register(r1), imm);
return length;
}
EVALUATE(CLFI) {
DCHECK_OPCODE(CLFI);
// Compare Logical with Immediate (32)
DECODE_RIL_A_INSTRUCTION(r1, imm);
SetS390ConditionCode<uint32_t>(get_low_register<uint32_t>(r1), imm);
return length;
}
EVALUATE(LLHRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LGHRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LHRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LLGHRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STHRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LGRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STGRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LGFRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LLGFRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(EXRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(PFDRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGHRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CHRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGFRL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ECTG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CSST) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LPD) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LPDG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(BRCTH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(AIH) {
DCHECK_OPCODE(AIH);
DECODE_RIL_A_INSTRUCTION(r1, i2);
int32_t r1_val = get_high_register<int32_t>(r1);
bool isOF = CheckOverflowForIntAdd(r1_val, static_cast<int32_t>(i2), int32_t);
r1_val += static_cast<int32_t>(i2);
set_high_register(r1, r1_val);
SetS390ConditionCode<int32_t>(r1_val, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(ALSIH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ALSIHN) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CIH) {
DCHECK_OPCODE(CIH);
DECODE_RIL_A_INSTRUCTION(r1, imm);
int32_t r1_val = get_high_register<int32_t>(r1);
SetS390ConditionCode<int32_t>(r1_val, static_cast<int32_t>(imm));
return length;
}
EVALUATE(CLIH) {
DCHECK_OPCODE(CLIH);
// Compare Logical with Immediate (32)
DECODE_RIL_A_INSTRUCTION(r1, imm);
SetS390ConditionCode<uint32_t>(get_high_register<uint32_t>(r1), imm);
return length;
}
EVALUATE(STCK) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CFC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(IPM) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(HSCH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MSCH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SSCH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STSCH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TSCH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TPI) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SAL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(RSCH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STCRW) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STCPS) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(RCHP) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SCHM) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CKSM) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SAR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(EAR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MSR) {
DCHECK_OPCODE(MSR);
DECODE_RRE_INSTRUCTION(r1, r2);
int32_t r1_val = get_low_register<int32_t>(r1);
int32_t r2_val = get_low_register<int32_t>(r2);
set_low_register(r1, r1_val * r2_val);
return length;
}
EVALUATE(MSRKC) {
DCHECK_OPCODE(MSRKC);
DECODE_RRF_A_INSTRUCTION(r1, r2, r3);
int32_t r2_val = get_low_register<int32_t>(r2);
int32_t r3_val = get_low_register<int32_t>(r3);
int64_t result64 =
static_cast<int64_t>(r2_val) * static_cast<int64_t>(r3_val);
int32_t result32 = static_cast<int32_t>(result64);
bool isOF = (static_cast<int64_t>(result32) != result64);
SetS390ConditionCode<int32_t>(result32, 0);
SetS390OverflowCode(isOF);
set_low_register(r1, result32);
return length;
}
EVALUATE(MVST) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CUSE) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SRST) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(XSCH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STCKE) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STCKF) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SRNM) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STFPC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LFPC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TRE) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STFLE) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SRNMB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SRNMT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LFAS) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(PPA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ETND) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TEND) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(NIAI) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TABORT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TRAP4) {
DCHECK_OPCODE(TRAP4);
int length = 4;
// whack the space of the caller allocated stack
int64_t sp_addr = get_register(sp);
for (int i = 0; i < kCalleeRegisterSaveAreaSize / kPointerSize; ++i) {
// we dont want to whack the RA (r14)
if (i != 14) (reinterpret_cast<intptr_t*>(sp_addr))[i] = 0xDEADBABE;
}
SoftwareInterrupt(instr);
return length;
}
EVALUATE(LPEBR) {
DCHECK_OPCODE(LPEBR);
DECODE_RRE_INSTRUCTION(r1, r2);
float fr1_val = get_float32_from_d_register(r1);
float fr2_val = get_float32_from_d_register(r2);
fr1_val = std::fabs(fr2_val);
set_d_register_from_float32(r1, fr1_val);
if (fr2_val != fr2_val) { // input is NaN
condition_reg_ = CC_OF;
} else if (fr2_val == 0) {
condition_reg_ = CC_EQ;
} else {
condition_reg_ = CC_GT;
}
return length;
}
EVALUATE(LNEBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LTEBR) {
DCHECK_OPCODE(LTEBR);
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r2_val = get_d_register(r2);
float fr2_val = get_float32_from_d_register(r2);
SetS390ConditionCode<float>(fr2_val, 0.0);
set_d_register(r1, r2_val);
return length;
}
EVALUATE(LCEBR) {
DCHECK_OPCODE(LCEBR);
DECODE_RRE_INSTRUCTION(r1, r2);
float fr1_val = get_float32_from_d_register(r1);
float fr2_val = get_float32_from_d_register(r2);
fr1_val = -fr2_val;
set_d_register_from_float32(r1, fr1_val);
if (fr2_val != fr2_val) { // input is NaN
condition_reg_ = CC_OF;
} else if (fr2_val == 0) {
condition_reg_ = CC_EQ;
} else if (fr2_val < 0) {
condition_reg_ = CC_LT;
} else if (fr2_val > 0) {
condition_reg_ = CC_GT;
}
return length;
}
EVALUATE(LDEBR) {
DCHECK_OPCODE(LDEBR);
DECODE_RRE_INSTRUCTION(r1, r2);
float fp_val = get_float32_from_d_register(r2);
double db_val = static_cast<double>(fp_val);
set_d_register_from_double(r1, db_val);
return length;
}
EVALUATE(LXDBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LXEBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MXDBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(KEBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CEBR) {
DCHECK_OPCODE(CEBR);
DECODE_RRE_INSTRUCTION(r1, r2);
float fr1_val = get_float32_from_d_register(r1);
float fr2_val = get_float32_from_d_register(r2);
if (isNaN(fr1_val) || isNaN(fr2_val)) {
condition_reg_ = CC_OF;
} else {
SetS390ConditionCode<float>(fr1_val, fr2_val);
}
return length;
}
EVALUATE(AEBR) {
DCHECK_OPCODE(AEBR);
DECODE_RRE_INSTRUCTION(r1, r2);
float fr1_val = get_float32_from_d_register(r1);
float fr2_val = get_float32_from_d_register(r2);
fr1_val += fr2_val;
set_d_register_from_float32(r1, fr1_val);
SetS390ConditionCode<float>(fr1_val, 0);
return length;
}
EVALUATE(SEBR) {
DCHECK_OPCODE(SEBR);
DECODE_RRE_INSTRUCTION(r1, r2);
float fr1_val = get_float32_from_d_register(r1);
float fr2_val = get_float32_from_d_register(r2);
fr1_val -= fr2_val;
set_d_register_from_float32(r1, fr1_val);
SetS390ConditionCode<float>(fr1_val, 0);
return length;
}
EVALUATE(MDEBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(DEBR) {
DCHECK_OPCODE(DEBR);
DECODE_RRE_INSTRUCTION(r1, r2);
float fr1_val = get_float32_from_d_register(r1);
float fr2_val = get_float32_from_d_register(r2);
fr1_val /= fr2_val;
set_d_register_from_float32(r1, fr1_val);
return length;
}
EVALUATE(MAEBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MSEBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LPDBR) {
DCHECK_OPCODE(LPDBR);
DECODE_RRE_INSTRUCTION(r1, r2);
double r1_val = get_double_from_d_register(r1);
double r2_val = get_double_from_d_register(r2);
r1_val = std::fabs(r2_val);
set_d_register_from_double(r1, r1_val);
if (r2_val != r2_val) { // input is NaN
condition_reg_ = CC_OF;
} else if (r2_val == 0) {
condition_reg_ = CC_EQ;
} else {
condition_reg_ = CC_GT;
}
return length;
}
EVALUATE(LNDBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LTDBR) {
DCHECK_OPCODE(LTDBR);
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r2_val = get_d_register(r2);
SetS390ConditionCode<double>(bit_cast<double, int64_t>(r2_val), 0.0);
set_d_register(r1, r2_val);
return length;
}
EVALUATE(LCDBR) {
DCHECK_OPCODE(LCDBR);
DECODE_RRE_INSTRUCTION(r1, r2);
double r1_val = get_double_from_d_register(r1);
double r2_val = get_double_from_d_register(r2);
r1_val = -r2_val;
set_d_register_from_double(r1, r1_val);
if (r2_val != r2_val) { // input is NaN
condition_reg_ = CC_OF;
} else if (r2_val == 0) {
condition_reg_ = CC_EQ;
} else if (r2_val < 0) {
condition_reg_ = CC_LT;
} else if (r2_val > 0) {
condition_reg_ = CC_GT;
}
return length;
}
EVALUATE(SQEBR) {
DCHECK_OPCODE(SQEBR);
DECODE_RRE_INSTRUCTION(r1, r2);
float fr1_val = get_float32_from_d_register(r1);
float fr2_val = get_float32_from_d_register(r2);
fr1_val = std::sqrt(fr2_val);
set_d_register_from_float32(r1, fr1_val);
return length;
}
EVALUATE(SQDBR) {
DCHECK_OPCODE(SQDBR);
DECODE_RRE_INSTRUCTION(r1, r2);
double r1_val = get_double_from_d_register(r1);
double r2_val = get_double_from_d_register(r2);
r1_val = std::sqrt(r2_val);
set_d_register_from_double(r1, r1_val);
return length;
}
EVALUATE(SQXBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MEEBR) {
DCHECK_OPCODE(MEEBR);
DECODE_RRE_INSTRUCTION(r1, r2);
float fr1_val = get_float32_from_d_register(r1);
float fr2_val = get_float32_from_d_register(r2);
fr1_val *= fr2_val;
set_d_register_from_float32(r1, fr1_val);
return length;
}
EVALUATE(KDBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CDBR) {
DCHECK_OPCODE(CDBR);
DECODE_RRE_INSTRUCTION(r1, r2);
double r1_val = get_double_from_d_register(r1);
double r2_val = get_double_from_d_register(r2);
if (isNaN(r1_val) || isNaN(r2_val)) {
condition_reg_ = CC_OF;
} else {
SetS390ConditionCode<double>(r1_val, r2_val);
}
return length;
}
EVALUATE(ADBR) {
DCHECK_OPCODE(ADBR);
DECODE_RRE_INSTRUCTION(r1, r2);
double r1_val = get_double_from_d_register(r1);
double r2_val = get_double_from_d_register(r2);
r1_val += r2_val;
set_d_register_from_double(r1, r1_val);
SetS390ConditionCode<double>(r1_val, 0);
return length;
}
EVALUATE(SDBR) {
DCHECK_OPCODE(SDBR);
DECODE_RRE_INSTRUCTION(r1, r2);
double r1_val = get_double_from_d_register(r1);
double r2_val = get_double_from_d_register(r2);
r1_val -= r2_val;
set_d_register_from_double(r1, r1_val);
SetS390ConditionCode<double>(r1_val, 0);
return length;
}
EVALUATE(MDBR) {
DCHECK_OPCODE(MDBR);
DECODE_RRE_INSTRUCTION(r1, r2);
double r1_val = get_double_from_d_register(r1);
double r2_val = get_double_from_d_register(r2);
r1_val *= r2_val;
set_d_register_from_double(r1, r1_val);
return length;
}
EVALUATE(DDBR) {
DCHECK_OPCODE(DDBR);
DECODE_RRE_INSTRUCTION(r1, r2);
double r1_val = get_double_from_d_register(r1);
double r2_val = get_double_from_d_register(r2);
r1_val /= r2_val;
set_d_register_from_double(r1, r1_val);
return length;
}
EVALUATE(MADBR) {
DCHECK_OPCODE(MADBR);
DECODE_RRD_INSTRUCTION(r1, r2, r3);
double r1_val = get_double_from_d_register(r1);
double r2_val = get_double_from_d_register(r2);
double r3_val = get_double_from_d_register(r3);
r1_val += r2_val * r3_val;
set_d_register_from_double(r1, r1_val);
SetS390ConditionCode<double>(r1_val, 0);
return length;
}
EVALUATE(MSDBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LPXBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LNXBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LTXBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LCXBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LEDBRA) {
DCHECK_OPCODE(LEDBRA);
DECODE_RRE_INSTRUCTION(r1, r2);
double r2_val = get_double_from_d_register(r2);
set_d_register_from_float32(r1, static_cast<float>(r2_val));
return length;
}
EVALUATE(LDXBRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LEXBRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(FIXBRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(KXBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CXBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(AXBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SXBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MXBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(DXBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TBEDR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TBDR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(DIEBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(FIEBRA) {
DCHECK_OPCODE(FIEBRA);
DECODE_RRF_E_INSTRUCTION(r1, r2, m3, m4);
float r2_val = get_float32_from_d_register(r2);
CHECK_EQ(m4, 0);
switch (m3) {
case Assembler::FIDBRA_ROUND_TO_NEAREST_AWAY_FROM_0:
set_d_register_from_float32(r1, round(r2_val));
break;
case Assembler::FIDBRA_ROUND_TOWARD_0:
set_d_register_from_float32(r1, trunc(r2_val));
break;
case Assembler::FIDBRA_ROUND_TOWARD_POS_INF:
set_d_register_from_float32(r1, std::ceil(r2_val));
break;
case Assembler::FIDBRA_ROUND_TOWARD_NEG_INF:
set_d_register_from_float32(r1, std::floor(r2_val));
break;
default:
UNIMPLEMENTED();
break;
}
return length;
}
EVALUATE(THDER) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(THDR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(DIDBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(FIDBRA) {
DCHECK_OPCODE(FIDBRA);
DECODE_RRF_E_INSTRUCTION(r1, r2, m3, m4);
double r2_val = get_double_from_d_register(r2);
CHECK_EQ(m4, 0);
switch (m3) {
case Assembler::FIDBRA_ROUND_TO_NEAREST_AWAY_FROM_0:
set_d_register_from_double(r1, round(r2_val));
break;
case Assembler::FIDBRA_ROUND_TOWARD_0:
set_d_register_from_double(r1, trunc(r2_val));
break;
case Assembler::FIDBRA_ROUND_TOWARD_POS_INF:
set_d_register_from_double(r1, std::ceil(r2_val));
break;
case Assembler::FIDBRA_ROUND_TOWARD_NEG_INF:
set_d_register_from_double(r1, std::floor(r2_val));
break;
default:
UNIMPLEMENTED();
break;
}
return length;
}
EVALUATE(LXR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LPDFR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LNDFR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LCDFR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LZER) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LZDR) {
DCHECK_OPCODE(LZDR);
DECODE_RRE_INSTRUCTION_NO_R2(r1);
set_d_register_from_double(r1, 0.0);
return length;
}
EVALUATE(LZXR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SFPC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SFASR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(EFPC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CELFBR) {
DCHECK_OPCODE(CELFBR);
DECODE_RRE_INSTRUCTION(r1, r2);
uint32_t r2_val = get_low_register<uint32_t>(r2);
float r1_val = static_cast<float>(r2_val);
set_d_register_from_float32(r1, r1_val);
return length;
}
EVALUATE(CDLFBR) {
DCHECK_OPCODE(CDLFBR);
DECODE_RRE_INSTRUCTION(r1, r2);
uint32_t r2_val = get_low_register<uint32_t>(r2);
double r1_val = static_cast<double>(r2_val);
set_d_register_from_double(r1, r1_val);
return length;
}
EVALUATE(CXLFBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CEFBRA) {
DCHECK_OPCODE(CEFBRA);
DECODE_RRE_INSTRUCTION(r1, r2);
int32_t fr2_val = get_low_register<int32_t>(r2);
float fr1_val = static_cast<float>(fr2_val);
set_d_register_from_float32(r1, fr1_val);
return length;
}
EVALUATE(CDFBRA) {
DCHECK_OPCODE(CDFBRA);
DECODE_RRE_INSTRUCTION(r1, r2);
int32_t r2_val = get_low_register<int32_t>(r2);
double r1_val = static_cast<double>(r2_val);
set_d_register_from_double(r1, r1_val);
return length;
}
EVALUATE(CXFBRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CFEBRA) {
DCHECK_OPCODE(CFEBRA);
DECODE_RRE_INSTRUCTION_M3(r1, r2, mask_val);
float r2_fval = get_float32_from_d_register(r2);
int32_t r1_val = 0;
SetS390RoundConditionCode(r2_fval, INT32_MAX, INT32_MIN);
switch (mask_val) {
case CURRENT_ROUNDING_MODE:
case ROUND_TO_PREPARE_FOR_SHORTER_PRECISION: {
r1_val = static_cast<int32_t>(r2_fval);
break;
}
case ROUND_TO_NEAREST_WITH_TIES_AWAY_FROM_0: {
float ceil_val = std::ceil(r2_fval);
float floor_val = std::floor(r2_fval);
float sub_val1 = std::fabs(r2_fval - floor_val);
float sub_val2 = std::fabs(r2_fval - ceil_val);
if (sub_val1 > sub_val2) {
r1_val = static_cast<int32_t>(ceil_val);
} else if (sub_val1 < sub_val2) {
r1_val = static_cast<int32_t>(floor_val);
} else { // round away from zero:
if (r2_fval > 0.0) {
r1_val = static_cast<int32_t>(ceil_val);
} else {
r1_val = static_cast<int32_t>(floor_val);
}
}
break;
}
case ROUND_TO_NEAREST_WITH_TIES_TO_EVEN: {
float ceil_val = std::ceil(r2_fval);
float floor_val = std::floor(r2_fval);
float sub_val1 = std::fabs(r2_fval - floor_val);
float sub_val2 = std::fabs(r2_fval - ceil_val);
if (sub_val1 > sub_val2) {
r1_val = static_cast<int32_t>(ceil_val);
} else if (sub_val1 < sub_val2) {
r1_val = static_cast<int32_t>(floor_val);
} else { // check which one is even:
int32_t c_v = static_cast<int32_t>(ceil_val);
int32_t f_v = static_cast<int32_t>(floor_val);
if (f_v % 2 == 0)
r1_val = f_v;
else
r1_val = c_v;
}
break;
}
case ROUND_TOWARD_0: {
// check for overflow, cast r2_fval to 64bit integer
// then check value within the range of INT_MIN and INT_MAX
// and set condition code accordingly
int64_t temp = static_cast<int64_t>(r2_fval);
if (temp < INT_MIN || temp > INT_MAX) {
condition_reg_ = CC_OF;
}
r1_val = static_cast<int32_t>(r2_fval);
break;
}
case ROUND_TOWARD_PLUS_INFINITE: {
r1_val = static_cast<int32_t>(std::ceil(r2_fval));
break;
}
case ROUND_TOWARD_MINUS_INFINITE: {
// check for overflow, cast r2_fval to 64bit integer
// then check value within the range of INT_MIN and INT_MAX
// and set condition code accordingly
int64_t temp = static_cast<int64_t>(std::floor(r2_fval));
if (temp < INT_MIN || temp > INT_MAX) {
condition_reg_ = CC_OF;
}
r1_val = static_cast<int32_t>(std::floor(r2_fval));
break;
}
default:
UNREACHABLE();
}
set_low_register(r1, r1_val);
return length;
}
EVALUATE(CFDBRA) {
DCHECK_OPCODE(CFDBRA);
DECODE_RRE_INSTRUCTION_M3(r1, r2, mask_val);
double r2_val = get_double_from_d_register(r2);
int32_t r1_val = 0;
SetS390RoundConditionCode(r2_val, INT32_MAX, INT32_MIN);
switch (mask_val) {
case CURRENT_ROUNDING_MODE:
case ROUND_TO_PREPARE_FOR_SHORTER_PRECISION: {
r1_val = static_cast<int32_t>(r2_val);
break;
}
case ROUND_TO_NEAREST_WITH_TIES_AWAY_FROM_0: {
double ceil_val = std::ceil(r2_val);
double floor_val = std::floor(r2_val);
double sub_val1 = std::fabs(r2_val - floor_val);
double sub_val2 = std::fabs(r2_val - ceil_val);
if (sub_val1 > sub_val2) {
r1_val = static_cast<int32_t>(ceil_val);
} else if (sub_val1 < sub_val2) {
r1_val = static_cast<int32_t>(floor_val);
} else { // round away from zero:
if (r2_val > 0.0) {
r1_val = static_cast<int32_t>(ceil_val);
} else {
r1_val = static_cast<int32_t>(floor_val);
}
}
break;
}
case ROUND_TO_NEAREST_WITH_TIES_TO_EVEN: {
double ceil_val = std::ceil(r2_val);
double floor_val = std::floor(r2_val);
double sub_val1 = std::fabs(r2_val - floor_val);
double sub_val2 = std::fabs(r2_val - ceil_val);
if (sub_val1 > sub_val2) {
r1_val = static_cast<int32_t>(ceil_val);
} else if (sub_val1 < sub_val2) {
r1_val = static_cast<int32_t>(floor_val);
} else { // check which one is even:
int32_t c_v = static_cast<int32_t>(ceil_val);
int32_t f_v = static_cast<int32_t>(floor_val);
if (f_v % 2 == 0)
r1_val = f_v;
else
r1_val = c_v;
}
break;
}
case ROUND_TOWARD_0: {
// check for overflow, cast r2_val to 64bit integer
// then check value within the range of INT_MIN and INT_MAX
// and set condition code accordingly
int64_t temp = static_cast<int64_t>(r2_val);
if (temp < INT_MIN || temp > INT_MAX) {
condition_reg_ = CC_OF;
}
r1_val = static_cast<int32_t>(r2_val);
break;
}
case ROUND_TOWARD_PLUS_INFINITE: {
r1_val = static_cast<int32_t>(std::ceil(r2_val));
break;
}
case ROUND_TOWARD_MINUS_INFINITE: {
// check for overflow, cast r2_val to 64bit integer
// then check value within the range of INT_MIN and INT_MAX
// and set condition code accordingly
int64_t temp = static_cast<int64_t>(std::floor(r2_val));
if (temp < INT_MIN || temp > INT_MAX) {
condition_reg_ = CC_OF;
}
r1_val = static_cast<int32_t>(std::floor(r2_val));
break;
}
default:
UNREACHABLE();
}
set_low_register(r1, r1_val);
return length;
}
EVALUATE(CFXBRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CLFEBR) {
DCHECK_OPCODE(CLFEBR);
DECODE_RRE_INSTRUCTION(r1, r2);
float r2_val = get_float32_from_d_register(r2);
uint32_t r1_val = static_cast<uint32_t>(r2_val);
set_low_register(r1, r1_val);
SetS390ConvertConditionCode<double>(r2_val, r1_val, UINT32_MAX);
return length;
}
EVALUATE(CLFDBR) {
DCHECK_OPCODE(CLFDBR);
DECODE_RRE_INSTRUCTION(r1, r2);
double a = get_double_from_d_register(r2);
double n = std::round(a);
uint32_t r1_val = static_cast<uint32_t>(n);
set_low_register(r1, r1_val);
if (std::isfinite(a) && a < 0.0) {
DCHECK(n <= 0.0 && std::isfinite(n));
condition_reg_ = (n < 0.0) ? 0x1 : 0x4;
} else if (a == 0.0) {
condition_reg_ = 0x8;
} else if (std::isfinite(a) && a > 0.0) {
DCHECK(n >= 0.0 && std::isfinite(n));
condition_reg_ = (n <= static_cast<double>(UINT32_MAX)) ? 0x2 : 0x1;
} else {
condition_reg_ = 0x1;
}
return length;
}
EVALUATE(CLFXBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CELGBR) {
DCHECK_OPCODE(CELGBR);
DECODE_RRE_INSTRUCTION(r1, r2);
uint64_t r2_val = get_register(r2);
float r1_val = static_cast<float>(r2_val);
set_d_register_from_float32(r1, r1_val);
return length;
}
EVALUATE(CDLGBR) {
DCHECK_OPCODE(CDLGBR);
DECODE_RRE_INSTRUCTION(r1, r2);
uint64_t r2_val = get_register(r2);
double r1_val = static_cast<double>(r2_val);
set_d_register_from_double(r1, r1_val);
return length;
}
EVALUATE(CXLGBR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CEGBRA) {
DCHECK_OPCODE(CEGBRA);
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t fr2_val = get_register(r2);
float fr1_val = static_cast<float>(fr2_val);
set_d_register_from_float32(r1, fr1_val);
return length;
}
EVALUATE(CDGBRA) {
DCHECK_OPCODE(CDGBRA);
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r2_val = get_register(r2);
double r1_val = static_cast<double>(r2_val);
set_d_register_from_double(r1, r1_val);
return length;
}
EVALUATE(CXGBRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGEBRA) {
DCHECK_OPCODE(CGEBRA);
DECODE_RRE_INSTRUCTION_M3(r1, r2, mask_val);
float r2_fval = get_float32_from_d_register(r2);
int64_t r1_val = 0;
SetS390RoundConditionCode(r2_fval, INT64_MAX, INT64_MIN);
switch (mask_val) {
case CURRENT_ROUNDING_MODE:
case ROUND_TO_NEAREST_WITH_TIES_AWAY_FROM_0:
case ROUND_TO_PREPARE_FOR_SHORTER_PRECISION: {
UNIMPLEMENTED();
break;
}
case ROUND_TO_NEAREST_WITH_TIES_TO_EVEN: {
float ceil_val = std::ceil(r2_fval);
float floor_val = std::floor(r2_fval);
if (std::abs(r2_fval - floor_val) > std::abs(r2_fval - ceil_val)) {
r1_val = static_cast<int64_t>(ceil_val);
} else if (std::abs(r2_fval - floor_val) < std::abs(r2_fval - ceil_val)) {
r1_val = static_cast<int64_t>(floor_val);
} else { // check which one is even:
int64_t c_v = static_cast<int64_t>(ceil_val);
int64_t f_v = static_cast<int64_t>(floor_val);
if (f_v % 2 == 0)
r1_val = f_v;
else
r1_val = c_v;
}
break;
}
case ROUND_TOWARD_0: {
r1_val = static_cast<int64_t>(r2_fval);
break;
}
case ROUND_TOWARD_PLUS_INFINITE: {
r1_val = static_cast<int64_t>(std::ceil(r2_fval));
break;
}
case ROUND_TOWARD_MINUS_INFINITE: {
r1_val = static_cast<int64_t>(std::floor(r2_fval));
break;
}
default:
UNREACHABLE();
}
set_register(r1, r1_val);
return length;
}
EVALUATE(CGDBRA) {
DCHECK_OPCODE(CGDBRA);
DECODE_RRE_INSTRUCTION_M3(r1, r2, mask_val);
double r2_val = get_double_from_d_register(r2);
int64_t r1_val = 0;
SetS390RoundConditionCode(r2_val, INT64_MAX, INT64_MIN);
switch (mask_val) {
case CURRENT_ROUNDING_MODE:
case ROUND_TO_NEAREST_WITH_TIES_AWAY_FROM_0:
case ROUND_TO_PREPARE_FOR_SHORTER_PRECISION: {
UNIMPLEMENTED();
break;
}
case ROUND_TO_NEAREST_WITH_TIES_TO_EVEN: {
double ceil_val = std::ceil(r2_val);
double floor_val = std::floor(r2_val);
if (std::abs(r2_val - floor_val) > std::abs(r2_val - ceil_val)) {
r1_val = static_cast<int64_t>(ceil_val);
} else if (std::abs(r2_val - floor_val) < std::abs(r2_val - ceil_val)) {
r1_val = static_cast<int64_t>(floor_val);
} else { // check which one is even:
int64_t c_v = static_cast<int64_t>(ceil_val);
int64_t f_v = static_cast<int64_t>(floor_val);
if (f_v % 2 == 0)
r1_val = f_v;
else
r1_val = c_v;
}
break;
}
case ROUND_TOWARD_0: {
r1_val = static_cast<int64_t>(r2_val);
break;
}
case ROUND_TOWARD_PLUS_INFINITE: {
r1_val = static_cast<int64_t>(std::ceil(r2_val));
break;
}
case ROUND_TOWARD_MINUS_INFINITE: {
r1_val = static_cast<int64_t>(std::floor(r2_val));
break;
}
default:
UNREACHABLE();
}
set_register(r1, r1_val);
return length;
}
EVALUATE(CGXBRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CLGEBR) {
DCHECK_OPCODE(CLGEBR);
DECODE_RRE_INSTRUCTION(r1, r2);
float r2_val = get_float32_from_d_register(r2);
uint64_t r1_val = static_cast<uint64_t>(r2_val);
set_register(r1, r1_val);
SetS390ConvertConditionCode<double>(r2_val, r1_val, UINT64_MAX);
return length;
}
EVALUATE(CLGDBR) {
DCHECK_OPCODE(CLGDBR);
DECODE_RRE_INSTRUCTION(r1, r2);
double r2_val = get_double_from_d_register(r2);
uint64_t r1_val = static_cast<uint64_t>(r2_val);
set_register(r1, r1_val);
SetS390ConvertConditionCode<double>(r2_val, r1_val, UINT64_MAX);
return length;
}
EVALUATE(CFER) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CFDR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CFXR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LDGR) {
DCHECK_OPCODE(LDGR);
// Load FPR from GPR (L <- 64)
DECODE_RRE_INSTRUCTION(r1, r2);
uint64_t int_val = get_register(r2);
// double double_val = bit_cast<double, uint64_t>(int_val);
// set_d_register_from_double(rreInst->R1Value(), double_val);
set_d_register(r1, int_val);
return length;
}
EVALUATE(CGER) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGDR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGXR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LGDR) {
DCHECK_OPCODE(LGDR);
DECODE_RRE_INSTRUCTION(r1, r2);
// Load GPR from FPR (64 <- L)
int64_t double_val = get_d_register(r2);
set_register(r1, double_val);
return length;
}
EVALUATE(MDTRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(DDTRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ADTRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SDTRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LDETR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LEDTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LTDTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(FIDTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MXTRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(DXTRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(AXTRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SXTRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LXDTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LDXTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LTXTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(FIXTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(KDTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGDTRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CUDTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CDTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(EEDTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ESDTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(KXTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGXTRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CUXTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CSXTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CXTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(EEXTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ESXTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CDGTRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CDUTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CDSTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CEDTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(QADTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(IEDTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(RRDTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CXGTRA) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CXUTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CXSTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CEXTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(QAXTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(IEXTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(RRXTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LPGR) {
DCHECK_OPCODE(LPGR);
// Load Positive (32)
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r2_val = get_register(r2);
r2_val = (r2_val < 0) ? -r2_val : r2_val; // If negative, then negate it.
set_register(r1, r2_val);
SetS390ConditionCode<int64_t>(r2_val, 0);
if (r2_val == (static_cast<int64_t>(1) << 63)) {
SetS390OverflowCode(true);
}
return length;
}
EVALUATE(LNGR) {
DCHECK_OPCODE(LNGR);
// Load Negative (64)
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r2_val = get_register(r2);
r2_val = (r2_val >= 0) ? -r2_val : r2_val; // If pos, then negate it.
set_register(r1, r2_val);
condition_reg_ = (r2_val == 0) ? CC_EQ : CC_LT; // CC0 - result is zero
// CC1 - result is negative
return length;
}
EVALUATE(LTGR) {
DCHECK_OPCODE(LTGR);
// Load Register (64)
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r2_val = get_register(r2);
SetS390ConditionCode<int64_t>(r2_val, 0);
set_register(r1, get_register(r2));
return length;
}
EVALUATE(LCGR) {
DCHECK_OPCODE(LCGR);
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r2_val = get_register(r2);
int64_t result = 0;
bool isOF = false;
#ifdef V8_TARGET_ARCH_S390X
isOF = __builtin_ssubl_overflow(0L, r2_val, &result);
#else
isOF = __builtin_ssubll_overflow(0L, r2_val, &result);
#endif
set_register(r1, result);
SetS390ConditionCode<int64_t>(result, 0);
if (isOF) {
SetS390OverflowCode(true);
}
return length;
}
EVALUATE(SGR) {
DCHECK_OPCODE(SGR);
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r1_val = get_register(r1);
int64_t r2_val = get_register(r2);
bool isOF = false;
isOF = CheckOverflowForIntSub(r1_val, r2_val, int64_t);
r1_val -= r2_val;
SetS390ConditionCode<int64_t>(r1_val, 0);
SetS390OverflowCode(isOF);
set_register(r1, r1_val);
return length;
}
EVALUATE(ALGR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SLGR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MSGR) {
DCHECK_OPCODE(MSGR);
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r1_val = get_register(r1);
int64_t r2_val = get_register(r2);
set_register(r1, r1_val * r2_val);
return length;
}
EVALUATE(MSGRKC) {
DCHECK_OPCODE(MSGRKC);
DECODE_RRF_A_INSTRUCTION(r1, r2, r3);
int64_t r2_val = get_register(r2);
int64_t r3_val = get_register(r3);
volatile int64_t result64 = r2_val * r3_val;
bool isOF = ((r2_val == -1 && result64 == (static_cast<int64_t>(1L) << 63)) ||
(r2_val != 0 && result64 / r2_val != r3_val));
SetS390ConditionCode<int64_t>(result64, 0);
SetS390OverflowCode(isOF);
set_register(r1, result64);
return length;
}
EVALUATE(DSGR) {
DCHECK_OPCODE(DSGR);
DECODE_RRE_INSTRUCTION(r1, r2);
DCHECK_EQ(r1 % 2, 0);
int64_t dividend = get_register(r1 + 1);
int64_t divisor = get_register(r2);
set_register(r1, dividend % divisor);
set_register(r1 + 1, dividend / divisor);
return length;
}
EVALUATE(LRVGR) {
DCHECK_OPCODE(LRVGR);
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r2_val = get_register(r2);
int64_t r1_val = ByteReverse(r2_val);
set_register(r1, r1_val);
return length;
}
EVALUATE(LPGFR) {
DCHECK_OPCODE(LPGFR);
// Load Positive (32)
DECODE_RRE_INSTRUCTION(r1, r2);
int32_t r2_val = get_low_register<int32_t>(r2);
// If negative, then negate it.
int64_t r1_val = static_cast<int64_t>((r2_val < 0) ? -r2_val : r2_val);
set_register(r1, r1_val);
SetS390ConditionCode<int64_t>(r1_val, 0);
return length;
}
EVALUATE(LNGFR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LTGFR) {
DCHECK_OPCODE(LTGFR);
DECODE_RRE_INSTRUCTION(r1, r2);
// Load and Test Register (64 <- 32) (Sign Extends 32-bit val)
// Load Register (64 <- 32) (Sign Extends 32-bit val)
int32_t r2_val = get_low_register<int32_t>(r2);
int64_t result = static_cast<int64_t>(r2_val);
set_register(r1, result);
SetS390ConditionCode<int64_t>(result, 0);
return length;
}
EVALUATE(LCGFR) {
DCHECK_OPCODE(LCGFR);
DECODE_RRE_INSTRUCTION(r1, r2);
// Load and Test Register (64 <- 32) (Sign Extends 32-bit val)
// Load Register (64 <- 32) (Sign Extends 32-bit val)
int32_t r2_val = get_low_register<int32_t>(r2);
int64_t result = static_cast<int64_t>(r2_val);
set_register(r1, result);
return length;
}
EVALUATE(LLGFR) {
DCHECK_OPCODE(LLGFR);
DECODE_RRE_INSTRUCTION(r1, r2);
int32_t r2_val = get_low_register<int32_t>(r2);
uint64_t r2_finalval = (static_cast<uint64_t>(r2_val) & 0x00000000FFFFFFFF);
set_register(r1, r2_finalval);
return length;
}
EVALUATE(LLGTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(AGFR) {
DCHECK_OPCODE(AGFR);
DECODE_RRE_INSTRUCTION(r1, r2);
// Add Register (64 <- 32) (Sign Extends 32-bit val)
int64_t r1_val = get_register(r1);
int64_t r2_val = static_cast<int64_t>(get_low_register<int32_t>(r2));
bool isOF = CheckOverflowForIntAdd(r1_val, r2_val, int64_t);
r1_val += r2_val;
SetS390ConditionCode<int64_t>(r1_val, 0);
SetS390OverflowCode(isOF);
set_register(r1, r1_val);
return length;
}
EVALUATE(SGFR) {
DCHECK_OPCODE(SGFR);
DECODE_RRE_INSTRUCTION(r1, r2);
// Sub Reg (64 <- 32)
int64_t r1_val = get_register(r1);
int64_t r2_val = static_cast<int64_t>(get_low_register<int32_t>(r2));
bool isOF = false;
isOF = CheckOverflowForIntSub(r1_val, r2_val, int64_t);
r1_val -= r2_val;
SetS390ConditionCode<int64_t>(r1_val, 0);
SetS390OverflowCode(isOF);
set_register(r1, r1_val);
return length;
}
EVALUATE(ALGFR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SLGFR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MSGFR) {
DCHECK_OPCODE(MSGFR);
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r1_val = get_register(r1);
int64_t r2_val = static_cast<int64_t>(get_low_register<int32_t>(r2));
int64_t product = r1_val * r2_val;
set_register(r1, product);
return length;
}
EVALUATE(DSGFR) {
DCHECK_OPCODE(DSGFR);
DECODE_RRE_INSTRUCTION(r1, r2);
DCHECK_EQ(r1 % 2, 0);
int64_t r1_val = get_register(r1 + 1);
int64_t r2_val = static_cast<int64_t>(get_low_register<int32_t>(r2));
int64_t quotient = r1_val / r2_val;
int64_t remainder = r1_val % r2_val;
set_register(r1, remainder);
set_register(r1 + 1, quotient);
return length;
}
EVALUATE(KMAC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LRVR) {
DCHECK_OPCODE(LRVR);
DECODE_RRE_INSTRUCTION(r1, r2);
int32_t r2_val = get_low_register<int32_t>(r2);
int32_t r1_val = ByteReverse(r2_val);
set_low_register(r1, r1_val);
return length;
}
EVALUATE(CGR) {
DCHECK_OPCODE(CGR);
DECODE_RRE_INSTRUCTION(r1, r2);
// Compare (64)
int64_t r1_val = get_register(r1);
int64_t r2_val = get_register(r2);
SetS390ConditionCode<int64_t>(r1_val, r2_val);
return length;
}
EVALUATE(CLGR) {
DCHECK_OPCODE(CLGR);
DECODE_RRE_INSTRUCTION(r1, r2);
// Compare Logical (64)
uint64_t r1_val = static_cast<uint64_t>(get_register(r1));
uint64_t r2_val = static_cast<uint64_t>(get_register(r2));
SetS390ConditionCode<uint64_t>(r1_val, r2_val);
return length;
}
EVALUATE(KMF) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(KMO) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(PCC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(KMCTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(KM) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(KMC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGFR) {
DCHECK_OPCODE(CGFR);
DECODE_RRE_INSTRUCTION(r1, r2);
// Compare (64)
int64_t r1_val = get_register(r1);
int64_t r2_val = static_cast<int64_t>(get_low_register<int32_t>(r2));
SetS390ConditionCode<int64_t>(r1_val, r2_val);
return length;
}
EVALUATE(KIMD) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(KLMD) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CFDTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CLGDTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CLFDTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(BCTGR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CFXTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CLFXTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CDFTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CDLGTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CDLFTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CXFTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CXLGTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CXLFTR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGRT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(NGR) {
DCHECK_OPCODE(NGR);
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r1_val = get_register(r1);
int64_t r2_val = get_register(r2);
r1_val &= r2_val;
SetS390BitWiseConditionCode<uint64_t>(r1_val);
set_register(r1, r1_val);
return length;
}
EVALUATE(OGR) {
DCHECK_OPCODE(OGR);
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r1_val = get_register(r1);
int64_t r2_val = get_register(r2);
r1_val |= r2_val;
SetS390BitWiseConditionCode<uint64_t>(r1_val);
set_register(r1, r1_val);
return length;
}
EVALUATE(XGR) {
DCHECK_OPCODE(XGR);
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r1_val = get_register(r1);
int64_t r2_val = get_register(r2);
r1_val ^= r2_val;
SetS390BitWiseConditionCode<uint64_t>(r1_val);
set_register(r1, r1_val);
return length;
}
EVALUATE(FLOGR) {
DCHECK_OPCODE(FLOGR);
DECODE_RRE_INSTRUCTION(r1, r2);
DCHECK_EQ(r1 % 2, 0);
int64_t r2_val = get_register(r2);
int i = 0;
for (; i < 64; i++) {
if (r2_val < 0) break;
r2_val <<= 1;
}
r2_val = get_register(r2);
int64_t mask = ~(1 << (63 - i));
set_register(r1, i);
set_register(r1 + 1, r2_val & mask);
return length;
}
EVALUATE(LLGCR) {
DCHECK_OPCODE(LLGCR);
DECODE_RRE_INSTRUCTION(r1, r2);
uint64_t r2_val = get_low_register<uint64_t>(r2);
r2_val <<= 56;
r2_val >>= 56;
set_register(r1, r2_val);
return length;
}
EVALUATE(LLGHR) {
DCHECK_OPCODE(LLGHR);
DECODE_RRE_INSTRUCTION(r1, r2);
uint64_t r2_val = get_low_register<uint64_t>(r2);
r2_val <<= 48;
r2_val >>= 48;
set_register(r1, r2_val);
return length;
}
EVALUATE(MLGR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(DLGR) {
DCHECK_OPCODE(DLGR);
#ifdef V8_TARGET_ARCH_S390X
DECODE_RRE_INSTRUCTION(r1, r2);
uint64_t r1_val = get_register(r1);
uint64_t r2_val = get_register(r2);
DCHECK_EQ(r1 % 2, 0);
unsigned __int128 dividend = static_cast<unsigned __int128>(r1_val) << 64;
dividend += get_register(r1 + 1);
uint64_t remainder = dividend % r2_val;
uint64_t quotient = dividend / r2_val;
set_register(r1, remainder);
set_register(r1 + 1, quotient);
return length;
#else
// 32 bit arch doesn't support __int128 type
USE(instr);
UNREACHABLE();
#endif
}
EVALUATE(ALCGR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SLBGR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(EPSW) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TRTT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TRTO) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TROT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TROO) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LLCR) {
DCHECK_OPCODE(LLCR);
DECODE_RRE_INSTRUCTION(r1, r2);
uint32_t r2_val = get_low_register<uint32_t>(r2);
r2_val <<= 24;
r2_val >>= 24;
set_low_register(r1, r2_val);
return length;
}
EVALUATE(LLHR) {
DCHECK_OPCODE(LLHR);
DECODE_RRE_INSTRUCTION(r1, r2);
uint32_t r2_val = get_low_register<uint32_t>(r2);
r2_val <<= 16;
r2_val >>= 16;
set_low_register(r1, r2_val);
return length;
}
EVALUATE(MLR) {
DCHECK_OPCODE(MLR);
DECODE_RRE_INSTRUCTION(r1, r2);
DCHECK_EQ(r1 % 2, 0);
uint32_t r1_val = get_low_register<uint32_t>(r1 + 1);
uint32_t r2_val = get_low_register<uint32_t>(r2);
uint64_t product =
static_cast<uint64_t>(r1_val) * static_cast<uint64_t>(r2_val);
int32_t high_bits = product >> 32;
int32_t low_bits = product & 0x00000000FFFFFFFF;
set_low_register(r1, high_bits);
set_low_register(r1 + 1, low_bits);
return length;
}
EVALUATE(DLR) {
DCHECK_OPCODE(DLR);
DECODE_RRE_INSTRUCTION(r1, r2);
uint32_t r1_val = get_low_register<uint32_t>(r1);
uint32_t r2_val = get_low_register<uint32_t>(r2);
DCHECK_EQ(r1 % 2, 0);
uint64_t dividend = static_cast<uint64_t>(r1_val) << 32;
dividend += get_low_register<uint32_t>(r1 + 1);
uint32_t remainder = dividend % r2_val;
uint32_t quotient = dividend / r2_val;
r1_val = remainder;
set_low_register(r1, remainder);
set_low_register(r1 + 1, quotient);
return length;
}
EVALUATE(ALCR) {
DCHECK_OPCODE(ALCR);
DECODE_RRE_INSTRUCTION(r1, r2);
uint32_t r1_val = get_low_register<uint32_t>(r1);
uint32_t r2_val = get_low_register<uint32_t>(r2);
uint32_t alu_out = 0;
bool isOF = false;
alu_out = r1_val + r2_val;
bool isOF_original = CheckOverflowForUIntAdd(r1_val, r2_val);
if (TestConditionCode((Condition)2) || TestConditionCode((Condition)3)) {
alu_out = alu_out + 1;
isOF = isOF_original || CheckOverflowForUIntAdd(alu_out, 1);
} else {
isOF = isOF_original;
}
set_low_register(r1, alu_out);
SetS390ConditionCodeCarry<uint32_t>(alu_out, isOF);
return length;
}
EVALUATE(SLBR) {
DCHECK_OPCODE(SLBR);
DECODE_RRE_INSTRUCTION(r1, r2);
uint32_t r1_val = get_low_register<uint32_t>(r1);
uint32_t r2_val = get_low_register<uint32_t>(r2);
uint32_t alu_out = 0;
bool isOF = false;
alu_out = r1_val - r2_val;
bool isOF_original = CheckOverflowForUIntSub(r1_val, r2_val);
if (TestConditionCode((Condition)2) || TestConditionCode((Condition)3)) {
alu_out = alu_out - 1;
isOF = isOF_original || CheckOverflowForUIntSub(alu_out, 1);
} else {
isOF = isOF_original;
}
set_low_register(r1, alu_out);
SetS390ConditionCodeCarry<uint32_t>(alu_out, isOF);
return length;
}
EVALUATE(CU14) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CU24) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CU41) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CU42) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TRTRE) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SRSTU) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TRTE) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(AHHHR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SHHHR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ALHHHR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SLHHHR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CHHR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(AHHLR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SHHLR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ALHHLR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SLHHLR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CHLR) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(POPCNT_Z) {
DCHECK_OPCODE(POPCNT_Z);
DECODE_RRE_INSTRUCTION(r1, r2);
int64_t r2_val = get_register(r2);
int64_t r1_val = 0;
uint8_t* r2_val_ptr = reinterpret_cast<uint8_t*>(&r2_val);
uint8_t* r1_val_ptr = reinterpret_cast<uint8_t*>(&r1_val);
for (int i = 0; i < 8; i++) {
uint32_t x = static_cast<uint32_t>(r2_val_ptr[i]);
#if defined(__GNUC__)
r1_val_ptr[i] = __builtin_popcount(x);
#else
#error unsupport __builtin_popcount
#endif
}
set_register(r1, static_cast<uint64_t>(r1_val));
return length;
}
EVALUATE(LOCGR) {
DCHECK_OPCODE(LOCGR);
DECODE_RRF_C_INSTRUCTION(r1, r2, m3);
if (TestConditionCode(m3)) {
set_register(r1, get_register(r2));
}
return length;
}
EVALUATE(NGRK) {
DCHECK_OPCODE(NGRK);
DECODE_RRF_A_INSTRUCTION(r1, r2, r3);
// 64-bit Non-clobbering arithmetics / bitwise ops.
int64_t r2_val = get_register(r2);
int64_t r3_val = get_register(r3);
uint64_t bitwise_result = 0;
bitwise_result = r2_val & r3_val;
SetS390BitWiseConditionCode<uint64_t>(bitwise_result);
set_register(r1, bitwise_result);
return length;
}
EVALUATE(OGRK) {
DCHECK_OPCODE(OGRK);
DECODE_RRF_A_INSTRUCTION(r1, r2, r3);
// 64-bit Non-clobbering arithmetics / bitwise ops.
int64_t r2_val = get_register(r2);
int64_t r3_val = get_register(r3);
uint64_t bitwise_result = 0;
bitwise_result = r2_val | r3_val;
SetS390BitWiseConditionCode<uint64_t>(bitwise_result);
set_register(r1, bitwise_result);
return length;
}
EVALUATE(XGRK) {
DCHECK_OPCODE(XGRK);
DECODE_RRF_A_INSTRUCTION(r1, r2, r3);
// 64-bit Non-clobbering arithmetics / bitwise ops.
int64_t r2_val = get_register(r2);
int64_t r3_val = get_register(r3);
uint64_t bitwise_result = 0;
bitwise_result = r2_val ^ r3_val;
SetS390BitWiseConditionCode<uint64_t>(bitwise_result);
set_register(r1, bitwise_result);
return length;
}
EVALUATE(AGRK) {
DCHECK_OPCODE(AGRK);
DECODE_RRF_A_INSTRUCTION(r1, r2, r3);
// 64-bit Non-clobbering arithmetics / bitwise ops.
int64_t r2_val = get_register(r2);
int64_t r3_val = get_register(r3);
bool isOF = CheckOverflowForIntAdd(r2_val, r3_val, int64_t);
SetS390ConditionCode<int64_t>(r2_val + r3_val, 0);
SetS390OverflowCode(isOF);
set_register(r1, r2_val + r3_val);
return length;
}
EVALUATE(SGRK) {
DCHECK_OPCODE(SGRK);
DECODE_RRF_A_INSTRUCTION(r1, r2, r3);
// 64-bit Non-clobbering arithmetics / bitwise ops.
int64_t r2_val = get_register(r2);
int64_t r3_val = get_register(r3);
bool isOF = CheckOverflowForIntSub(r2_val, r3_val, int64_t);
SetS390ConditionCode<int64_t>(r2_val - r3_val, 0);
SetS390OverflowCode(isOF);
set_register(r1, r2_val - r3_val);
return length;
}
EVALUATE(ALGRK) {
DCHECK_OPCODE(ALGRK);
DECODE_RRF_A_INSTRUCTION(r1, r2, r3);
// 64-bit Non-clobbering unsigned arithmetics
uint64_t r2_val = get_register(r2);
uint64_t r3_val = get_register(r3);
bool isOF = CheckOverflowForUIntAdd(r2_val, r3_val);
SetS390ConditionCode<uint64_t>(r2_val + r3_val, 0);
SetS390OverflowCode(isOF);
set_register(r1, r2_val + r3_val);
return length;
}
EVALUATE(SLGRK) {
DCHECK_OPCODE(SLGRK);
DECODE_RRF_A_INSTRUCTION(r1, r2, r3);
// 64-bit Non-clobbering unsigned arithmetics
uint64_t r2_val = get_register(r2);
uint64_t r3_val = get_register(r3);
bool isOF = CheckOverflowForUIntSub(r2_val, r3_val);
SetS390ConditionCode<uint64_t>(r2_val - r3_val, 0);
SetS390OverflowCode(isOF);
set_register(r1, r2_val - r3_val);
return length;
}
EVALUATE(LOCR) {
DCHECK_OPCODE(LOCR);
DECODE_RRF_C_INSTRUCTION(r1, r2, m3);
if (TestConditionCode(m3)) {
set_low_register(r1, get_low_register<int32_t>(r2));
}
return length;
}
EVALUATE(NRK) {
DCHECK_OPCODE(NRK);
DECODE_RRF_A_INSTRUCTION(r1, r2, r3);
// 32-bit Non-clobbering arithmetics / bitwise ops
int32_t r2_val = get_low_register<int32_t>(r2);
int32_t r3_val = get_low_register<int32_t>(r3);
// Assume bitwise operation here
uint32_t bitwise_result = 0;
bitwise_result = r2_val & r3_val;
SetS390BitWiseConditionCode<uint32_t>(bitwise_result);
set_low_register(r1, bitwise_result);
return length;
}
EVALUATE(ORK) {
DCHECK_OPCODE(ORK);
DECODE_RRF_A_INSTRUCTION(r1, r2, r3);
// 32-bit Non-clobbering arithmetics / bitwise ops
int32_t r2_val = get_low_register<int32_t>(r2);
int32_t r3_val = get_low_register<int32_t>(r3);
// Assume bitwise operation here
uint32_t bitwise_result = 0;
bitwise_result = r2_val | r3_val;
SetS390BitWiseConditionCode<uint32_t>(bitwise_result);
set_low_register(r1, bitwise_result);
return length;
}
EVALUATE(XRK) {
DCHECK_OPCODE(XRK);
DECODE_RRF_A_INSTRUCTION(r1, r2, r3);
// 32-bit Non-clobbering arithmetics / bitwise ops
int32_t r2_val = get_low_register<int32_t>(r2);
int32_t r3_val = get_low_register<int32_t>(r3);
// Assume bitwise operation here
uint32_t bitwise_result = 0;
bitwise_result = r2_val ^ r3_val;
SetS390BitWiseConditionCode<uint32_t>(bitwise_result);
set_low_register(r1, bitwise_result);
return length;
}
EVALUATE(ARK) {
DCHECK_OPCODE(ARK);
DECODE_RRF_A_INSTRUCTION(r1, r2, r3);
// 32-bit Non-clobbering arithmetics / bitwise ops
int32_t r2_val = get_low_register<int32_t>(r2);
int32_t r3_val = get_low_register<int32_t>(r3);
bool isOF = CheckOverflowForIntAdd(r2_val, r3_val, int32_t);
SetS390ConditionCode<int32_t>(r2_val + r3_val, 0);
SetS390OverflowCode(isOF);
set_low_register(r1, r2_val + r3_val);
return length;
}
EVALUATE(SRK) {
DCHECK_OPCODE(SRK);
DECODE_RRF_A_INSTRUCTION(r1, r2, r3);
// 32-bit Non-clobbering arithmetics / bitwise ops
int32_t r2_val = get_low_register<int32_t>(r2);
int32_t r3_val = get_low_register<int32_t>(r3);
bool isOF = CheckOverflowForIntSub(r2_val, r3_val, int32_t);
SetS390ConditionCode<int32_t>(r2_val - r3_val, 0);
SetS390OverflowCode(isOF);
set_low_register(r1, r2_val - r3_val);
return length;
}
EVALUATE(ALRK) {
DCHECK_OPCODE(ALRK);
DECODE_RRF_A_INSTRUCTION(r1, r2, r3);
// 32-bit Non-clobbering unsigned arithmetics
uint32_t r2_val = get_low_register<uint32_t>(r2);
uint32_t r3_val = get_low_register<uint32_t>(r3);
bool isOF = CheckOverflowForUIntAdd(r2_val, r3_val);
SetS390ConditionCode<uint32_t>(r2_val + r3_val, 0);
SetS390OverflowCode(isOF);
set_low_register(r1, r2_val + r3_val);
return length;
}
EVALUATE(SLRK) {
DCHECK_OPCODE(SLRK);
DECODE_RRF_A_INSTRUCTION(r1, r2, r3);
// 32-bit Non-clobbering unsigned arithmetics
uint32_t r2_val = get_low_register<uint32_t>(r2);
uint32_t r3_val = get_low_register<uint32_t>(r3);
bool isOF = CheckOverflowForUIntSub(r2_val, r3_val);
SetS390ConditionCode<uint32_t>(r2_val - r3_val, 0);
SetS390OverflowCode(isOF);
set_low_register(r1, r2_val - r3_val);
return length;
}
EVALUATE(LTG) {
DCHECK_OPCODE(LTG);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t addr = x2_val + b2_val + d2;
int64_t value = ReadDW(addr);
set_register(r1, value);
SetS390ConditionCode<int64_t>(value, 0);
return length;
}
EVALUATE(CVBY) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(AG) {
DCHECK_OPCODE(AG);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t alu_out = get_register(r1);
int64_t mem_val = ReadDW(b2_val + x2_val + d2);
bool isOF = CheckOverflowForIntAdd(alu_out, mem_val, int64_t);
alu_out += mem_val;
SetS390ConditionCode<int64_t>(alu_out, 0);
SetS390OverflowCode(isOF);
set_register(r1, alu_out);
return length;
}
EVALUATE(SG) {
DCHECK_OPCODE(SG);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t alu_out = get_register(r1);
int64_t mem_val = ReadDW(b2_val + x2_val + d2);
bool isOF = CheckOverflowForIntSub(alu_out, mem_val, int64_t);
alu_out -= mem_val;
SetS390ConditionCode<int32_t>(alu_out, 0);
SetS390OverflowCode(isOF);
set_register(r1, alu_out);
return length;
}
EVALUATE(ALG) {
DCHECK_OPCODE(ALG);
#ifndef V8_TARGET_ARCH_S390X
DCHECK(false);
#endif
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
uint64_t r1_val = get_register(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
uint64_t alu_out = r1_val;
uint64_t mem_val = static_cast<uint64_t>(ReadDW(b2_val + d2_val + x2_val));
alu_out += mem_val;
SetS390ConditionCode<uint64_t>(alu_out, 0);
set_register(r1, alu_out);
return length;
}
EVALUATE(SLG) {
DCHECK_OPCODE(SLG);
#ifndef V8_TARGET_ARCH_S390X
DCHECK(false);
#endif
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
uint64_t r1_val = get_register(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
uint64_t alu_out = r1_val;
uint64_t mem_val = static_cast<uint64_t>(ReadDW(b2_val + d2_val + x2_val));
alu_out -= mem_val;
SetS390ConditionCode<uint64_t>(alu_out, 0);
set_register(r1, alu_out);
return length;
}
EVALUATE(MSG) {
DCHECK_OPCODE(MSG);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
int64_t mem_val = ReadDW(b2_val + d2_val + x2_val);
int64_t r1_val = get_register(r1);
set_register(r1, mem_val * r1_val);
return length;
}
EVALUATE(DSG) {
DCHECK_OPCODE(DSG);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
DCHECK_EQ(r1 % 2, 0);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
int64_t mem_val = ReadDW(b2_val + d2_val + x2_val);
int64_t r1_val = get_register(r1 + 1);
int64_t quotient = r1_val / mem_val;
int64_t remainder = r1_val % mem_val;
set_register(r1, remainder);
set_register(r1 + 1, quotient);
return length;
}
EVALUATE(CVBG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LT) {
DCHECK_OPCODE(LT);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t addr = x2_val + b2_val + d2;
int32_t value = ReadW(addr, instr);
set_low_register(r1, value);
SetS390ConditionCode<int32_t>(value, 0);
return length;
}
EVALUATE(LGH) {
DCHECK_OPCODE(LGH);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
// Miscellaneous Loads and Stores
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t addr = x2_val + b2_val + d2;
int64_t mem_val = static_cast<int64_t>(ReadH(addr, instr));
set_register(r1, mem_val);
return length;
}
EVALUATE(LLGF) {
DCHECK_OPCODE(LLGF);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
// Miscellaneous Loads and Stores
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t addr = x2_val + b2_val + d2;
uint64_t mem_val = static_cast<uint64_t>(ReadWU(addr, instr));
set_register(r1, mem_val);
return length;
}
EVALUATE(LLGT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(AGF) {
DCHECK_OPCODE(AGF);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
uint64_t r1_val = get_register(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
uint64_t alu_out = r1_val;
uint32_t mem_val = ReadW(b2_val + d2_val + x2_val, instr);
alu_out += mem_val;
SetS390ConditionCode<int64_t>(alu_out, 0);
set_register(r1, alu_out);
return length;
}
EVALUATE(SGF) {
DCHECK_OPCODE(SGF);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
uint64_t r1_val = get_register(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
uint64_t alu_out = r1_val;
uint32_t mem_val = ReadW(b2_val + d2_val + x2_val, instr);
alu_out -= mem_val;
SetS390ConditionCode<int64_t>(alu_out, 0);
set_register(r1, alu_out);
return length;
}
EVALUATE(ALGF) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SLGF) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MSGF) {
DCHECK_OPCODE(MSGF);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
int64_t mem_val =
static_cast<int64_t>(ReadW(b2_val + d2_val + x2_val, instr));
int64_t r1_val = get_register(r1);
int64_t product = r1_val * mem_val;
set_register(r1, product);
return length;
}
EVALUATE(DSGF) {
DCHECK_OPCODE(DSGF);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
DCHECK_EQ(r1 % 2, 0);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
int64_t mem_val =
static_cast<int64_t>(ReadW(b2_val + d2_val + x2_val, instr));
int64_t r1_val = get_register(r1 + 1);
int64_t quotient = r1_val / mem_val;
int64_t remainder = r1_val % mem_val;
set_register(r1, remainder);
set_register(r1 + 1, quotient);
return length;
}
EVALUATE(LRVG) {
DCHECK_OPCODE(LRVG);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t mem_addr = b2_val + x2_val + d2;
int64_t mem_val = ReadW64(mem_addr, instr);
set_register(r1, ByteReverse(mem_val));
return length;
}
EVALUATE(LRV) {
DCHECK_OPCODE(LRV);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t mem_addr = b2_val + x2_val + d2;
int32_t mem_val = ReadW(mem_addr, instr);
set_low_register(r1, ByteReverse(mem_val));
return length;
}
EVALUATE(LRVH) {
DCHECK_OPCODE(LRVH);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t mem_addr = b2_val + x2_val + d2;
int16_t mem_val = ReadH(mem_addr, instr);
int32_t result = ByteReverse(mem_val) & 0x0000FFFF;
result |= r1_val & 0xFFFF0000;
set_low_register(r1, result);
return length;
}
EVALUATE(CG) {
DCHECK_OPCODE(CG);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t alu_out = get_register(r1);
int64_t mem_val = ReadDW(b2_val + x2_val + d2);
SetS390ConditionCode<int64_t>(alu_out, mem_val);
set_register(r1, alu_out);
return length;
}
EVALUATE(CLG) {
DCHECK_OPCODE(CLG);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t alu_out = get_register(r1);
int64_t mem_val = ReadDW(b2_val + x2_val + d2);
SetS390ConditionCode<uint64_t>(alu_out, mem_val);
set_register(r1, alu_out);
return length;
}
EVALUATE(NTSTG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CVDY) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CVDG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGF) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CLGF) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LTGF) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(PFD) {
DCHECK_OPCODE(PFD);
USE(instr);
return 6;
}
EVALUATE(STRV) {
DCHECK_OPCODE(STRV);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t mem_addr = b2_val + x2_val + d2;
WriteW(mem_addr, ByteReverse(r1_val), instr);
return length;
}
EVALUATE(STRVG) {
DCHECK_OPCODE(STRVG);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t r1_val = get_register(r1);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t mem_addr = b2_val + x2_val + d2;
WriteDW(mem_addr, ByteReverse(r1_val));
return length;
}
EVALUATE(STRVH) {
DCHECK_OPCODE(STRVH);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t mem_addr = b2_val + x2_val + d2;
int16_t result = static_cast<int16_t>(r1_val >> 16);
WriteH(mem_addr, ByteReverse(result), instr);
return length;
}
EVALUATE(BCTG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MSY) {
DCHECK_OPCODE(MSY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
int32_t mem_val = ReadW(b2_val + d2_val + x2_val, instr);
int32_t r1_val = get_low_register<int32_t>(r1);
set_low_register(r1, mem_val * r1_val);
return length;
}
EVALUATE(MSC) {
DCHECK_OPCODE(MSC);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
int32_t mem_val = ReadW(b2_val + d2_val + x2_val, instr);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t result64 =
static_cast<int64_t>(r1_val) * static_cast<int64_t>(mem_val);
int32_t result32 = static_cast<int32_t>(result64);
bool isOF = (static_cast<int64_t>(result32) != result64);
SetS390ConditionCode<int32_t>(result32, 0);
SetS390OverflowCode(isOF);
set_low_register(r1, result32);
set_low_register(r1, mem_val * r1_val);
return length;
}
EVALUATE(NY) {
DCHECK_OPCODE(NY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int32_t alu_out = get_low_register<int32_t>(r1);
int32_t mem_val = ReadW(b2_val + x2_val + d2, instr);
alu_out &= mem_val;
SetS390BitWiseConditionCode<uint32_t>(alu_out);
set_low_register(r1, alu_out);
return length;
}
EVALUATE(CLY) {
DCHECK_OPCODE(CLY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
uint32_t alu_out = get_low_register<uint32_t>(r1);
uint32_t mem_val = ReadWU(b2_val + x2_val + d2, instr);
SetS390ConditionCode<uint32_t>(alu_out, mem_val);
return length;
}
EVALUATE(OY) {
DCHECK_OPCODE(OY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int32_t alu_out = get_low_register<int32_t>(r1);
int32_t mem_val = ReadW(b2_val + x2_val + d2, instr);
alu_out |= mem_val;
SetS390BitWiseConditionCode<uint32_t>(alu_out);
set_low_register(r1, alu_out);
return length;
}
EVALUATE(XY) {
DCHECK_OPCODE(XY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int32_t alu_out = get_low_register<int32_t>(r1);
int32_t mem_val = ReadW(b2_val + x2_val + d2, instr);
alu_out ^= mem_val;
SetS390BitWiseConditionCode<uint32_t>(alu_out);
set_low_register(r1, alu_out);
return length;
}
EVALUATE(CY) {
DCHECK_OPCODE(CY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int32_t alu_out = get_low_register<int32_t>(r1);
int32_t mem_val = ReadW(b2_val + x2_val + d2, instr);
SetS390ConditionCode<int32_t>(alu_out, mem_val);
return length;
}
EVALUATE(AY) {
DCHECK_OPCODE(AY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int32_t alu_out = get_low_register<int32_t>(r1);
int32_t mem_val = ReadW(b2_val + x2_val + d2, instr);
bool isOF = false;
isOF = CheckOverflowForIntAdd(alu_out, mem_val, int32_t);
alu_out += mem_val;
SetS390ConditionCode<int32_t>(alu_out, 0);
SetS390OverflowCode(isOF);
set_low_register(r1, alu_out);
return length;
}
EVALUATE(SY) {
DCHECK_OPCODE(SY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int32_t alu_out = get_low_register<int32_t>(r1);
int32_t mem_val = ReadW(b2_val + x2_val + d2, instr);
bool isOF = false;
isOF = CheckOverflowForIntSub(alu_out, mem_val, int32_t);
alu_out -= mem_val;
SetS390ConditionCode<int32_t>(alu_out, 0);
SetS390OverflowCode(isOF);
set_low_register(r1, alu_out);
return length;
}
EVALUATE(MFY) {
DCHECK_OPCODE(MFY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
DCHECK_EQ(r1 % 2, 0);
int32_t mem_val = ReadW(b2_val + x2_val + d2, instr);
int32_t r1_val = get_low_register<int32_t>(r1 + 1);
int64_t product =
static_cast<int64_t>(r1_val) * static_cast<int64_t>(mem_val);
int32_t high_bits = product >> 32;
r1_val = high_bits;
int32_t low_bits = product & 0x00000000FFFFFFFF;
set_low_register(r1, high_bits);
set_low_register(r1 + 1, low_bits);
return length;
}
EVALUATE(ALY) {
DCHECK_OPCODE(ALY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
uint32_t alu_out = get_low_register<uint32_t>(r1);
uint32_t mem_val = ReadWU(b2_val + x2_val + d2, instr);
alu_out += mem_val;
set_low_register(r1, alu_out);
SetS390ConditionCode<uint32_t>(alu_out, 0);
return length;
}
EVALUATE(SLY) {
DCHECK_OPCODE(SLY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
uint32_t alu_out = get_low_register<uint32_t>(r1);
uint32_t mem_val = ReadWU(b2_val + x2_val + d2, instr);
alu_out -= mem_val;
set_low_register(r1, alu_out);
SetS390ConditionCode<uint32_t>(alu_out, 0);
return length;
}
EVALUATE(STHY) {
DCHECK_OPCODE(STHY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
// Miscellaneous Loads and Stores
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t addr = x2_val + b2_val + d2;
uint16_t value = get_low_register<uint32_t>(r1);
WriteH(addr, value, instr);
return length;
}
EVALUATE(LAY) {
DCHECK_OPCODE(LAY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
// Load Address
int rb = b2;
int rx = x2;
int offset = d2;
int64_t rb_val = (rb == 0) ? 0 : get_register(rb);
int64_t rx_val = (rx == 0) ? 0 : get_register(rx);
set_register(r1, rx_val + rb_val + offset);
return length;
}
EVALUATE(STCY) {
DCHECK_OPCODE(STCY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
// Miscellaneous Loads and Stores
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t addr = x2_val + b2_val + d2;
uint8_t value = get_low_register<uint32_t>(r1);
WriteB(addr, value);
return length;
}
EVALUATE(ICY) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LAEY) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LB) {
DCHECK_OPCODE(LB);
// Miscellaneous Loads and Stores
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t addr = x2_val + b2_val + d2;
int32_t mem_val = ReadB(addr);
set_low_register(r1, mem_val);
return length;
}
EVALUATE(LGB) {
DCHECK_OPCODE(LGB);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
// Miscellaneous Loads and Stores
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t addr = x2_val + b2_val + d2;
int64_t mem_val = ReadB(addr);
set_register(r1, mem_val);
return length;
}
EVALUATE(LHY) {
DCHECK_OPCODE(LHY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
// Miscellaneous Loads and Stores
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t addr = x2_val + b2_val + d2;
int32_t result = static_cast<int32_t>(ReadH(addr, instr));
set_low_register(r1, result);
return length;
}
EVALUATE(CHY) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(AHY) {
DCHECK_OPCODE(AHY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
int32_t mem_val =
static_cast<int32_t>(ReadH(b2_val + d2_val + x2_val, instr));
int32_t alu_out = 0;
bool isOF = false;
alu_out = r1_val + mem_val;
isOF = CheckOverflowForIntAdd(r1_val, mem_val, int32_t);
set_low_register(r1, alu_out);
SetS390ConditionCode<int32_t>(alu_out, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(SHY) {
DCHECK_OPCODE(SHY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int32_t r1_val = get_low_register<int32_t>(r1);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
int32_t mem_val =
static_cast<int32_t>(ReadH(b2_val + d2_val + x2_val, instr));
int32_t alu_out = 0;
bool isOF = false;
alu_out = r1_val - mem_val;
isOF = CheckOverflowForIntSub(r1_val, mem_val, int64_t);
set_low_register(r1, alu_out);
SetS390ConditionCode<int32_t>(alu_out, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(MHY) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(NG) {
DCHECK_OPCODE(NG);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t alu_out = get_register(r1);
int64_t mem_val = ReadDW(b2_val + x2_val + d2);
alu_out &= mem_val;
SetS390BitWiseConditionCode<uint32_t>(alu_out);
set_register(r1, alu_out);
return length;
}
EVALUATE(OG) {
DCHECK_OPCODE(OG);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t alu_out = get_register(r1);
int64_t mem_val = ReadDW(b2_val + x2_val + d2);
alu_out |= mem_val;
SetS390BitWiseConditionCode<uint32_t>(alu_out);
set_register(r1, alu_out);
return length;
}
EVALUATE(XG) {
DCHECK_OPCODE(XG);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t alu_out = get_register(r1);
int64_t mem_val = ReadDW(b2_val + x2_val + d2);
alu_out ^= mem_val;
SetS390BitWiseConditionCode<uint32_t>(alu_out);
set_register(r1, alu_out);
return length;
}
EVALUATE(LGAT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MLG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(DLG) {
DCHECK_OPCODE(DLG);
#ifdef V8_TARGET_ARCH_S390X
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
uint64_t r1_val = get_register(r1);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
DCHECK_EQ(r1 % 2, 0);
unsigned __int128 dividend = static_cast<unsigned __int128>(r1_val) << 64;
dividend += get_register(r1 + 1);
int64_t mem_val = ReadDW(b2_val + x2_val + d2);
uint64_t remainder = dividend % mem_val;
uint64_t quotient = dividend / mem_val;
set_register(r1, remainder);
set_register(r1 + 1, quotient);
return length;
#else
// 32 bit arch doesn't support __int128 type
USE(instr);
UNREACHABLE();
#endif
}
EVALUATE(ALCG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SLBG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STPQ) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LPQ) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LLGH) {
DCHECK_OPCODE(LLGH);
// Load Logical Halfword
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
uint16_t mem_val = ReadHU(b2_val + d2_val + x2_val, instr);
set_register(r1, mem_val);
return length;
}
EVALUATE(LLH) {
DCHECK_OPCODE(LLH);
// Load Logical Halfword
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
uint16_t mem_val = ReadHU(b2_val + d2_val + x2_val, instr);
set_low_register(r1, mem_val);
return length;
}
EVALUATE(ML) {
DCHECK_OPCODE(ML);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
DCHECK_EQ(r1 % 2, 0);
uint32_t mem_val = ReadWU(b2_val + x2_val + d2, instr);
uint32_t r1_val = get_low_register<uint32_t>(r1 + 1);
uint64_t product =
static_cast<uint64_t>(r1_val) * static_cast<uint64_t>(mem_val);
uint32_t high_bits = product >> 32;
r1_val = high_bits;
uint32_t low_bits = product & 0x00000000FFFFFFFF;
set_low_register(r1, high_bits);
set_low_register(r1 + 1, low_bits);
return length;
}
EVALUATE(DL) {
DCHECK_OPCODE(DL);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
DCHECK_EQ(r1 % 2, 0);
uint32_t mem_val = ReadWU(b2_val + x2_val + d2, instr);
uint32_t r1_val = get_low_register<uint32_t>(r1 + 1);
uint64_t quotient =
static_cast<uint64_t>(r1_val) / static_cast<uint64_t>(mem_val);
uint64_t remainder =
static_cast<uint64_t>(r1_val) % static_cast<uint64_t>(mem_val);
set_low_register(r1, remainder);
set_low_register(r1 + 1, quotient);
return length;
}
EVALUATE(ALC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SLB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LLGTAT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LLGFAT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LAT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LBH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LLCH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STCH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LHH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LLHH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STHH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LFHAT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LFH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STFH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CHF) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MVCDK) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MVHHI) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MVGHI) {
DCHECK_OPCODE(MVGHI);
// Move Integer (64)
DECODE_SIL_INSTRUCTION(b1, d1, i2);
int64_t b1_val = (b1 == 0) ? 0 : get_register(b1);
intptr_t src_addr = b1_val + d1;
WriteDW(src_addr, i2);
return length;
}
EVALUATE(MVHI) {
DCHECK_OPCODE(MVHI);
// Move Integer (32)
DECODE_SIL_INSTRUCTION(b1, d1, i2);
int64_t b1_val = (b1 == 0) ? 0 : get_register(b1);
intptr_t src_addr = b1_val + d1;
WriteW(src_addr, i2, instr);
return length;
}
EVALUATE(CHHSI) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGHSI) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CHSI) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CLFHSI) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TBEGIN) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TBEGINC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LMG) {
DCHECK_OPCODE(LMG);
// Store Multiple 64-bits.
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2);
int rb = b2;
int offset = d2;
// Regs roll around if r3 is less than r1.
// Artificially increase r3 by 16 so we can calculate
// the number of regs stored properly.
if (r3 < r1) r3 += 16;
int64_t rb_val = (rb == 0) ? 0 : get_register(rb);
// Store each register in ascending order.
for (int i = 0; i <= r3 - r1; i++) {
int64_t value = ReadDW(rb_val + offset + 8 * i);
set_register((r1 + i) % 16, value);
}
return length;
}
EVALUATE(SRAG) {
DCHECK_OPCODE(SRAG);
// 64-bit non-clobbering shift-left/right arithmetic
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2);
// only takes rightmost 6 bits
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int shiftBits = (b2_val + d2) & 0x3F;
int64_t r3_val = get_register(r3);
intptr_t alu_out = 0;
bool isOF = false;
alu_out = r3_val >> shiftBits;
set_register(r1, alu_out);
SetS390ConditionCode<intptr_t>(alu_out, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(SLAG) {
DCHECK_OPCODE(SLAG);
// 64-bit non-clobbering shift-left/right arithmetic
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2);
// only takes rightmost 6 bits
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int shiftBits = (b2_val + d2) & 0x3F;
int64_t r3_val = get_register(r3);
intptr_t alu_out = 0;
bool isOF = false;
isOF = CheckOverflowForShiftLeft(r3_val, shiftBits);
alu_out = r3_val << shiftBits;
set_register(r1, alu_out);
SetS390ConditionCode<intptr_t>(alu_out, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(SRLG) {
DCHECK_OPCODE(SRLG);
// For SLLG/SRLG, the 64-bit third operand is shifted the number
// of bits specified by the second-operand address, and the result is
// placed at the first-operand location. Except for when the R1 and R3
// fields designate the same register, the third operand remains
// unchanged in general register R3.
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2);
// only takes rightmost 6 bits
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int shiftBits = (b2_val + d2) & 0x3F;
// unsigned
uint64_t r3_val = get_register(r3);
uint64_t alu_out = 0;
alu_out = r3_val >> shiftBits;
set_register(r1, alu_out);
return length;
}
EVALUATE(SLLG) {
DCHECK_OPCODE(SLLG);
// For SLLG/SRLG, the 64-bit third operand is shifted the number
// of bits specified by the second-operand address, and the result is
// placed at the first-operand location. Except for when the R1 and R3
// fields designate the same register, the third operand remains
// unchanged in general register R3.
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2);
// only takes rightmost 6 bits
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int shiftBits = (b2_val + d2) & 0x3F;
// unsigned
uint64_t r3_val = get_register(r3);
uint64_t alu_out = 0;
alu_out = r3_val << shiftBits;
set_register(r1, alu_out);
return length;
}
EVALUATE(CS) {
DCHECK_OPCODE(CS);
DECODE_RS_A_INSTRUCTION(r1, r3, rb, d2);
int32_t offset = d2;
int64_t rb_val = (rb == 0) ? 0 : get_register(rb);
intptr_t target_addr = static_cast<intptr_t>(rb_val) + offset;
int32_t r1_val = get_low_register<int32_t>(r1);
int32_t r3_val = get_low_register<int32_t>(r3);
DCHECK_EQ(target_addr & 0x3, 0);
bool is_success = __atomic_compare_exchange_n(
reinterpret_cast<int32_t*>(target_addr), &r1_val, r3_val, true,
__ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
if (!is_success) {
set_low_register(r1, r1_val);
condition_reg_ = 0x4;
} else {
condition_reg_ = 0x8;
}
return length;
}
EVALUATE(CSY) {
DCHECK_OPCODE(CSY);
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2);
int32_t offset = d2;
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t target_addr = static_cast<intptr_t>(b2_val) + offset;
int32_t r1_val = get_low_register<int32_t>(r1);
int32_t r3_val = get_low_register<int32_t>(r3);
DCHECK_EQ(target_addr & 0x3, 0);
bool is_success = __atomic_compare_exchange_n(
reinterpret_cast<int32_t*>(target_addr), &r1_val, r3_val, true,
__ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
if (!is_success) {
set_low_register(r1, r1_val);
condition_reg_ = 0x4;
} else {
condition_reg_ = 0x8;
}
return length;
}
EVALUATE(CSG) {
DCHECK_OPCODE(CSG);
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2);
int32_t offset = d2;
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t target_addr = static_cast<intptr_t>(b2_val) + offset;
int64_t r1_val = get_register(r1);
int64_t r3_val = get_register(r3);
DCHECK_EQ(target_addr & 0x3, 0);
bool is_success = __atomic_compare_exchange_n(
reinterpret_cast<int64_t*>(target_addr), &r1_val, r3_val, true,
__ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
if (!is_success) {
set_register(r1, r1_val);
condition_reg_ = 0x4;
} else {
condition_reg_ = 0x8;
}
return length;
}
EVALUATE(RLLG) {
DCHECK_OPCODE(RLLG);
// For SLLG/SRLG, the 64-bit third operand is shifted the number
// of bits specified by the second-operand address, and the result is
// placed at the first-operand location. Except for when the R1 and R3
// fields designate the same register, the third operand remains
// unchanged in general register R3.
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2);
// only takes rightmost 6 bits
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int shiftBits = (b2_val + d2) & 0x3F;
// unsigned
uint64_t r3_val = get_register(r3);
uint64_t alu_out = 0;
uint64_t rotateBits = r3_val >> (64 - shiftBits);
alu_out = (r3_val << shiftBits) | (rotateBits);
set_register(r1, alu_out);
return length;
}
EVALUATE(STMG) {
DCHECK_OPCODE(STMG);
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2);
int rb = b2;
int offset = d2;
// Regs roll around if r3 is less than r1.
// Artificially increase r3 by 16 so we can calculate
// the number of regs stored properly.
if (r3 < r1) r3 += 16;
int64_t rb_val = (rb == 0) ? 0 : get_register(rb);
// Store each register in ascending order.
for (int i = 0; i <= r3 - r1; i++) {
int64_t value = get_register((r1 + i) % 16);
WriteDW(rb_val + offset + 8 * i, value);
}
return length;
}
EVALUATE(STMH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STCMH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STCMY) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CDSY) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CDSG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(BXHG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(BXLEG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ECAG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TM) {
DCHECK_OPCODE(TM);
// Test Under Mask (Mem - Imm) (8)
DECODE_SI_INSTRUCTION_I_UINT8(b1, d1_val, imm_val)
int64_t b1_val = (b1 == 0) ? 0 : get_register(b1);
intptr_t addr = b1_val + d1_val;
uint8_t mem_val = ReadB(addr);
uint8_t selected_bits = mem_val & imm_val;
// is TM
bool is_tm_or_tmy = 1;
condition_reg_ = TestUnderMask(selected_bits, imm_val, is_tm_or_tmy);
return length;
}
EVALUATE(TMY) {
DCHECK_OPCODE(TMY);
// Test Under Mask (Mem - Imm) (8)
DECODE_SIY_INSTRUCTION(b1, d1_val, imm_val);
int64_t b1_val = (b1 == 0) ? 0 : get_register(b1);
intptr_t addr = b1_val + d1_val;
uint8_t mem_val = ReadB(addr);
uint8_t selected_bits = mem_val & imm_val;
// is TMY
bool is_tm_or_tmy = 1;
condition_reg_ = TestUnderMask(selected_bits, imm_val, is_tm_or_tmy);
return length;
}
EVALUATE(MVIY) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(NIY) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CLIY) {
DCHECK_OPCODE(CLIY);
DECODE_SIY_INSTRUCTION(b1, d1, i2);
// Compare Immediate (Mem - Imm) (8)
int64_t b1_val = (b1 == 0) ? 0 : get_register(b1);
intptr_t d1_val = d1;
intptr_t addr = b1_val + d1_val;
uint8_t mem_val = ReadB(addr);
uint8_t imm_val = i2;
SetS390ConditionCode<uint8_t>(mem_val, imm_val);
return length;
}
EVALUATE(OIY) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(XIY) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ASI) {
DCHECK_OPCODE(ASI);
// TODO(bcleung): Change all fooInstr->I2Value() to template functions.
// The below static cast to 8 bit and then to 32 bit is necessary
// because siyInstr->I2Value() returns a uint8_t, which a direct
// cast to int32_t could incorrectly interpret.
DECODE_SIY_INSTRUCTION(b1, d1, i2_unsigned);
int8_t i2_8bit = static_cast<int8_t>(i2_unsigned);
int32_t i2 = static_cast<int32_t>(i2_8bit);
intptr_t b1_val = (b1 == 0) ? 0 : get_register(b1);
int d1_val = d1;
intptr_t addr = b1_val + d1_val;
int32_t mem_val = ReadW(addr, instr);
bool isOF = CheckOverflowForIntAdd(mem_val, i2, int32_t);
int32_t alu_out = mem_val + i2;
SetS390ConditionCode<int32_t>(alu_out, 0);
SetS390OverflowCode(isOF);
WriteW(addr, alu_out, instr);
return length;
}
EVALUATE(ALSI) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(AGSI) {
DCHECK_OPCODE(AGSI);
// TODO(bcleung): Change all fooInstr->I2Value() to template functions.
// The below static cast to 8 bit and then to 32 bit is necessary
// because siyInstr->I2Value() returns a uint8_t, which a direct
// cast to int32_t could incorrectly interpret.
DECODE_SIY_INSTRUCTION(b1, d1, i2_unsigned);
int8_t i2_8bit = static_cast<int8_t>(i2_unsigned);
int64_t i2 = static_cast<int64_t>(i2_8bit);
intptr_t b1_val = (b1 == 0) ? 0 : get_register(b1);
int d1_val = d1;
intptr_t addr = b1_val + d1_val;
int64_t mem_val = ReadDW(addr);
int isOF = CheckOverflowForIntAdd(mem_val, i2, int64_t);
int64_t alu_out = mem_val + i2;
SetS390ConditionCode<uint64_t>(alu_out, 0);
SetS390OverflowCode(isOF);
WriteDW(addr, alu_out);
return length;
}
EVALUATE(ALGSI) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ICMH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ICMY) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MVCLU) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CLCLU) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STMY) {
DCHECK_OPCODE(STMY);
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2);
// Load/Store Multiple (32)
int offset = d2;
// Regs roll around if r3 is less than r1.
// Artificially increase r3 by 16 so we can calculate
// the number of regs stored properly.
if (r3 < r1) r3 += 16;
int32_t b2_val = (b2 == 0) ? 0 : get_low_register<int32_t>(b2);
// Store each register in ascending order.
for (int i = 0; i <= r3 - r1; i++) {
int32_t value = get_low_register<int32_t>((r1 + i) % 16);
WriteW(b2_val + offset + 4 * i, value, instr);
}
return length;
}
EVALUATE(LMH) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LMY) {
DCHECK_OPCODE(LMY);
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2);
// Load/Store Multiple (32)
int offset = d2;
// Regs roll around if r3 is less than r1.
// Artificially increase r3 by 16 so we can calculate
// the number of regs stored properly.
if (r3 < r1) r3 += 16;
int32_t b2_val = (b2 == 0) ? 0 : get_low_register<int32_t>(b2);
// Store each register in ascending order.
for (int i = 0; i <= r3 - r1; i++) {
int32_t value = ReadW(b2_val + offset + 4 * i, instr);
set_low_register((r1 + i) % 16, value);
}
return length;
}
EVALUATE(TP) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SRAK) {
DCHECK_OPCODE(SRAK);
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2);
// 32-bit non-clobbering shift-left/right arithmetic
// only takes rightmost 6 bits
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int shiftBits = (b2_val + d2) & 0x3F;
int32_t r3_val = get_low_register<int32_t>(r3);
int32_t alu_out = 0;
bool isOF = false;
alu_out = r3_val >> shiftBits;
set_low_register(r1, alu_out);
SetS390ConditionCode<int32_t>(alu_out, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(SLAK) {
DCHECK_OPCODE(SLAK);
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2);
// 32-bit non-clobbering shift-left/right arithmetic
// only takes rightmost 6 bits
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int shiftBits = (b2_val + d2) & 0x3F;
int32_t r3_val = get_low_register<int32_t>(r3);
int32_t alu_out = 0;
bool isOF = false;
isOF = CheckOverflowForShiftLeft(r3_val, shiftBits);
alu_out = r3_val << shiftBits;
set_low_register(r1, alu_out);
SetS390ConditionCode<int32_t>(alu_out, 0);
SetS390OverflowCode(isOF);
return length;
}
EVALUATE(SRLK) {
DCHECK_OPCODE(SRLK);
// For SLLK/SRLL, the 32-bit third operand is shifted the number
// of bits specified by the second-operand address, and the result is
// placed at the first-operand location. Except for when the R1 and R3
// fields designate the same register, the third operand remains
// unchanged in general register R3.
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2);
// only takes rightmost 6 bits
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int shiftBits = (b2_val + d2) & 0x3F;
// unsigned
uint32_t r3_val = get_low_register<uint32_t>(r3);
uint32_t alu_out = 0;
alu_out = r3_val >> shiftBits;
set_low_register(r1, alu_out);
return length;
}
EVALUATE(SLLK) {
DCHECK_OPCODE(SLLK);
// For SLLK/SRLL, the 32-bit third operand is shifted the number
// of bits specified by the second-operand address, and the result is
// placed at the first-operand location. Except for when the R1 and R3
// fields designate the same register, the third operand remains
// unchanged in general register R3.
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2);
// only takes rightmost 6 bits
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int shiftBits = (b2_val + d2) & 0x3F;
// unsigned
uint32_t r3_val = get_low_register<uint32_t>(r3);
uint32_t alu_out = 0;
alu_out = r3_val << shiftBits;
set_low_register(r1, alu_out);
return length;
}
EVALUATE(LOCG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STOCG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
#define ATOMIC_LOAD_AND_UPDATE_WORD64(op) \
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2); \
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2); \
intptr_t addr = static_cast<intptr_t>(b2_val) + d2; \
int64_t r3_val = get_register(r3); \
DCHECK_EQ(addr & 0x3, 0); \
int64_t r1_val = \
op(reinterpret_cast<int64_t*>(addr), r3_val, __ATOMIC_SEQ_CST); \
set_register(r1, r1_val);
EVALUATE(LANG) {
DCHECK_OPCODE(LANG);
ATOMIC_LOAD_AND_UPDATE_WORD64(__atomic_fetch_and);
return length;
}
EVALUATE(LAOG) {
DCHECK_OPCODE(LAOG);
ATOMIC_LOAD_AND_UPDATE_WORD64(__atomic_fetch_or);
return length;
}
EVALUATE(LAXG) {
DCHECK_OPCODE(LAXG);
ATOMIC_LOAD_AND_UPDATE_WORD64(__atomic_fetch_xor);
return length;
}
EVALUATE(LAAG) {
DCHECK_OPCODE(LAAG);
ATOMIC_LOAD_AND_UPDATE_WORD64(__atomic_fetch_add);
return length;
}
EVALUATE(LAALG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
#undef ATOMIC_LOAD_AND_UPDATE_WORD64
EVALUATE(LOC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(STOC) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
#define ATOMIC_LOAD_AND_UPDATE_WORD32(op) \
DECODE_RSY_A_INSTRUCTION(r1, r3, b2, d2); \
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2); \
intptr_t addr = static_cast<intptr_t>(b2_val) + d2; \
int32_t r3_val = get_low_register<int32_t>(r3); \
DCHECK_EQ(addr & 0x3, 0); \
int32_t r1_val = \
op(reinterpret_cast<int32_t*>(addr), r3_val, __ATOMIC_SEQ_CST); \
set_low_register(r1, r1_val);
EVALUATE(LAN) {
DCHECK_OPCODE(LAN);
ATOMIC_LOAD_AND_UPDATE_WORD32(__atomic_fetch_and);
return length;
}
EVALUATE(LAO) {
DCHECK_OPCODE(LAO);
ATOMIC_LOAD_AND_UPDATE_WORD32(__atomic_fetch_or);
return length;
}
EVALUATE(LAX) {
DCHECK_OPCODE(LAX);
ATOMIC_LOAD_AND_UPDATE_WORD32(__atomic_fetch_xor);
return length;
}
EVALUATE(LAA) {
DCHECK_OPCODE(LAA);
ATOMIC_LOAD_AND_UPDATE_WORD32(__atomic_fetch_add);
return length;
}
EVALUATE(LAAL) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
#undef ATOMIC_LOAD_AND_UPDATE_WORD32
EVALUATE(BRXHG) {
DCHECK_OPCODE(BRXHG);
DECODE_RIE_E_INSTRUCTION(r1, r3, i2);
int64_t r1_val = (r1 == 0) ? 0 : get_register(r1);
int64_t r3_val = (r3 == 0) ? 0 : get_register(r3);
intptr_t branch_address = get_pc() + (2 * i2);
r1_val += r3_val;
int64_t compare_val = r3 % 2 == 0 ? get_register(r3 + 1) : r3_val;
if (r1_val > compare_val) {
set_pc(branch_address);
}
set_register(r1, r1_val);
return length;
}
EVALUATE(BRXLG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(RISBLG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(RNSBG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ROSBG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(RXSBG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(RISBGN) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(RISBHG) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGRJ) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGIT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CIT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CLFIT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGIJ) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CIJ) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ALHSIK) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(ALGHSIK) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGRB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CGIB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CIB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LDEB) {
DCHECK_OPCODE(LDEB);
DECODE_RXE_INSTRUCTION(r1, b2, x2, d2);
int rb = b2;
int rx = x2;
int offset = d2;
int64_t rb_val = (rb == 0) ? 0 : get_register(rb);
int64_t rx_val = (rx == 0) ? 0 : get_register(rx);
float fval = ReadFloat(rx_val + rb_val + offset);
set_d_register_from_double(r1, static_cast<double>(fval));
return length;
}
EVALUATE(LXDB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LXEB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MXDB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(KEB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CEB) {
DCHECK_OPCODE(CEB);
DECODE_RXE_INSTRUCTION(r1, b2, x2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
float r1_val = get_float32_from_d_register(r1);
float fval = ReadFloat(b2_val + x2_val + d2_val);
SetS390ConditionCode<float>(r1_val, fval);
return length;
}
EVALUATE(AEB) {
DCHECK_OPCODE(AEB);
DECODE_RXE_INSTRUCTION(r1, b2, x2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
float r1_val = get_float32_from_d_register(r1);
float fval = ReadFloat(b2_val + x2_val + d2_val);
r1_val += fval;
set_d_register_from_float32(r1, r1_val);
SetS390ConditionCode<float>(r1_val, 0);
return length;
}
EVALUATE(SEB) {
DCHECK_OPCODE(SEB);
DECODE_RXE_INSTRUCTION(r1, b2, x2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
float r1_val = get_float32_from_d_register(r1);
float fval = ReadFloat(b2_val + x2_val + d2_val);
r1_val -= fval;
set_d_register_from_float32(r1, r1_val);
SetS390ConditionCode<float>(r1_val, 0);
return length;
}
EVALUATE(MDEB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(DEB) {
DCHECK_OPCODE(DEB);
DECODE_RXE_INSTRUCTION(r1, b2, x2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
float r1_val = get_float32_from_d_register(r1);
float fval = ReadFloat(b2_val + x2_val + d2_val);
r1_val /= fval;
set_d_register_from_float32(r1, r1_val);
return length;
}
EVALUATE(MAEB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MSEB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TCEB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TCDB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TCXB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SQEB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SQDB) {
DCHECK_OPCODE(SQDB);
DECODE_RXE_INSTRUCTION(r1, b2, x2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
double r1_val = get_double_from_d_register(r1);
double dbl_val = ReadDouble(b2_val + x2_val + d2_val);
r1_val = std::sqrt(dbl_val);
set_d_register_from_double(r1, r1_val);
return length;
}
EVALUATE(MEEB) {
DCHECK_OPCODE(MEEB);
DECODE_RXE_INSTRUCTION(r1, b2, x2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
float r1_val = get_float32_from_d_register(r1);
float fval = ReadFloat(b2_val + x2_val + d2_val);
r1_val *= fval;
set_d_register_from_float32(r1, r1_val);
return length;
}
EVALUATE(KDB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CDB) {
DCHECK_OPCODE(CDB);
DECODE_RXE_INSTRUCTION(r1, b2, x2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
double r1_val = get_double_from_d_register(r1);
double dbl_val = ReadDouble(b2_val + x2_val + d2_val);
SetS390ConditionCode<double>(r1_val, dbl_val);
return length;
}
EVALUATE(ADB) {
DCHECK_OPCODE(ADB);
DECODE_RXE_INSTRUCTION(r1, b2, x2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
double r1_val = get_double_from_d_register(r1);
double dbl_val = ReadDouble(b2_val + x2_val + d2_val);
r1_val += dbl_val;
set_d_register_from_double(r1, r1_val);
SetS390ConditionCode<double>(r1_val, 0);
return length;
}
EVALUATE(SDB) {
DCHECK_OPCODE(SDB);
DECODE_RXE_INSTRUCTION(r1, b2, x2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
double r1_val = get_double_from_d_register(r1);
double dbl_val = ReadDouble(b2_val + x2_val + d2_val);
r1_val -= dbl_val;
set_d_register_from_double(r1, r1_val);
SetS390ConditionCode<double>(r1_val, 0);
return length;
}
EVALUATE(MDB) {
DCHECK_OPCODE(MDB);
DECODE_RXE_INSTRUCTION(r1, b2, x2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
double r1_val = get_double_from_d_register(r1);
double dbl_val = ReadDouble(b2_val + x2_val + d2_val);
r1_val *= dbl_val;
set_d_register_from_double(r1, r1_val);
return length;
}
EVALUATE(DDB) {
DCHECK_OPCODE(DDB);
DECODE_RXE_INSTRUCTION(r1, b2, x2, d2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
intptr_t d2_val = d2;
double r1_val = get_double_from_d_register(r1);
double dbl_val = ReadDouble(b2_val + x2_val + d2_val);
r1_val /= dbl_val;
set_d_register_from_double(r1, r1_val);
return length;
}
EVALUATE(MADB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(MSDB) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SLDT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SRDT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SLXT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(SRXT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TDCET) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TDGET) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TDCDT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TDGDT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TDCXT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(TDGXT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(LEY) {
DCHECK_OPCODE(LEY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
// Miscellaneous Loads and Stores
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t addr = x2_val + b2_val + d2;
float float_val = *reinterpret_cast<float*>(addr);
set_d_register_from_float32(r1, float_val);
return length;
}
EVALUATE(LDY) {
DCHECK_OPCODE(LDY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
// Miscellaneous Loads and Stores
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t addr = x2_val + b2_val + d2;
uint64_t dbl_val = *reinterpret_cast<uint64_t*>(addr);
set_d_register(r1, dbl_val);
return length;
}
EVALUATE(STEY) {
DCHECK_OPCODE(STEY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
// Miscellaneous Loads and Stores
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t addr = x2_val + b2_val + d2;
int64_t frs_val = get_d_register(r1) >> 32;
WriteW(addr, static_cast<int32_t>(frs_val), instr);
return length;
}
EVALUATE(STDY) {
DCHECK_OPCODE(STDY);
DECODE_RXY_A_INSTRUCTION(r1, x2, b2, d2);
// Miscellaneous Loads and Stores
int64_t x2_val = (x2 == 0) ? 0 : get_register(x2);
int64_t b2_val = (b2 == 0) ? 0 : get_register(b2);
intptr_t addr = x2_val + b2_val + d2;
int64_t frs_val = get_d_register(r1);
WriteDW(addr, frs_val);
return length;
}
EVALUATE(CZDT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CZXT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CDZT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
EVALUATE(CXZT) {
UNIMPLEMENTED();
USE(instr);
return 0;
}
#undef EVALUATE
#undef SScanF
#undef S390_SUPPORTED_VECTOR_OPCODE_LIST
#undef CheckOverflowForIntAdd
#undef CheckOverflowForIntSub
#undef CheckOverflowForUIntAdd
#undef CheckOverflowForUIntSub
#undef CheckOverflowForMul
#undef CheckOverflowForShiftRight
#undef CheckOverflowForShiftLeft
#undef DCHECK_OPCODE
#undef AS
#undef DECODE_RIL_A_INSTRUCTION
#undef DECODE_RIL_B_INSTRUCTION
#undef DECODE_RIL_C_INSTRUCTION
#undef DECODE_RXY_A_INSTRUCTION
#undef DECODE_RX_A_INSTRUCTION
#undef DECODE_RS_A_INSTRUCTION
#undef DECODE_RS_A_INSTRUCTION_NO_R3
#undef DECODE_RSI_INSTRUCTION
#undef DECODE_SI_INSTRUCTION_I_UINT8
#undef DECODE_SIL_INSTRUCTION
#undef DECODE_SIY_INSTRUCTION
#undef DECODE_RRE_INSTRUCTION
#undef DECODE_RRE_INSTRUCTION_M3
#undef DECODE_RRE_INSTRUCTION_NO_R2
#undef DECODE_RRD_INSTRUCTION
#undef DECODE_RRF_E_INSTRUCTION
#undef DECODE_RRF_A_INSTRUCTION
#undef DECODE_RRF_C_INSTRUCTION
#undef DECODE_RR_INSTRUCTION
#undef DECODE_RIE_D_INSTRUCTION
#undef DECODE_RIE_E_INSTRUCTION
#undef DECODE_RIE_F_INSTRUCTION
#undef DECODE_RSY_A_INSTRUCTION
#undef DECODE_RI_A_INSTRUCTION
#undef DECODE_RI_B_INSTRUCTION
#undef DECODE_RI_C_INSTRUCTION
#undef DECODE_RXE_INSTRUCTION
#undef DECODE_VRR_A_INSTRUCTION
#undef DECODE_VRR_B_INSTRUCTION
#undef DECODE_VRR_C_INSTRUCTION
#undef DECODE_VRR_E_INSTRUCTION
#undef DECODE_VRX_INSTRUCTION
#undef DECODE_VRS_INSTRUCTION
#undef DECODE_VRI_A_INSTRUCTION
#undef DECODE_VRI_C_INSTRUCTION
#undef GET_ADDRESS
#undef VECTOR_BINARY_OP_FOR_TYPE
#undef VECTOR_BINARY_OP
#undef VECTOR_MAX_MIN_FOR_TYPE
#undef VECTOR_MAX_MIN
#undef VECTOR_COMPARE_FOR_TYPE
#undef VECTOR_COMPARE
#undef VECTOR_SHIFT_FOR_TYPE
#undef VECTOR_SHIFT
#undef VECTOR_FP_BINARY_OP
#undef VECTOR_FP_MAX_MIN_FOR_TYPE
#undef VECTOR_FP_MAX_MIN
#undef VECTOR_FP_COMPARE_FOR_TYPE
#undef VECTOR_FP_COMPARE
} // namespace internal
} // namespace v8
#endif // USE_SIMULATOR
| apache-2.0 |
yma88/indy | addons/koji/jaxrs/src/main/java/org/commonjava/indy/koji/bind/jaxrs/KojiRepairResource.java | 9199 | /**
* Copyright (C) 2011-2020 Red Hat, Inc. (https://github.com/Commonjava/indy)
*
* 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.commonjava.indy.koji.bind.jaxrs;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.redhat.red.build.koji.KojiClientException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.commonjava.indy.IndyWorkflowException;
import org.commonjava.indy.bind.jaxrs.IndyResources;
import org.commonjava.indy.bind.jaxrs.SecurityManager;
import org.commonjava.indy.bind.jaxrs.util.REST;
import org.commonjava.indy.bind.jaxrs.util.ResponseHelper;
import org.commonjava.indy.koji.data.KojiRepairException;
import org.commonjava.indy.koji.data.KojiRepairManager;
import org.commonjava.indy.koji.model.KojiMultiRepairResult;
import org.commonjava.indy.koji.model.KojiRepairRequest;
import org.commonjava.indy.koji.model.KojiRepairResult;
import org.commonjava.indy.util.ApplicationContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import static org.commonjava.indy.bind.jaxrs.util.JaxRsUriFormatter.getBaseUrlByStoreKey;
import static org.commonjava.indy.koji.model.IndyKojiConstants.ALL_MASKS;
import static org.commonjava.indy.koji.model.IndyKojiConstants.MASK;
import static org.commonjava.indy.koji.model.IndyKojiConstants.META_TIMEOUT;
import static org.commonjava.indy.koji.model.IndyKojiConstants.META_TIMEOUT_ALL;
import static org.commonjava.indy.koji.model.IndyKojiConstants.REPAIR_KOJI;
import static org.commonjava.indy.koji.model.IndyKojiConstants.VOL;
import static org.commonjava.indy.util.ApplicationContent.application_json;
@Api( value = "Koji repairVolume operation", description = "Repair Koji remote repositories." )
@Path( "/api/" + REPAIR_KOJI )
@Produces( { application_json } )
@REST
public class KojiRepairResource
implements IndyResources
{
private final Logger logger = LoggerFactory.getLogger( getClass() );
@Inject
private ObjectMapper mapper;
@Inject
private SecurityManager securityManager;
@Inject
private KojiRepairManager repairManager;
@Inject
private ResponseHelper responseHelper;
@ApiOperation( "Repair koji repository remote url /vol." )
@ApiResponse( code = 200, message = "Operation finished (consult response content for success/failure).",
response = KojiRepairResult.class )
@ApiImplicitParam( name = "body", paramType = "body",
value = "JSON request specifying source and other configuration options",
required = true, dataType = "org.commonjava.indy.koji.model.KojiRepairRequest" )
@POST
@Path( "/" + VOL )
@Consumes( ApplicationContent.application_json )
public KojiRepairResult repairVolumes( final KojiRepairRequest request, final @Context HttpServletRequest servletRequest,
final @Context SecurityContext securityContext, final @Context UriInfo uriInfo )
{
try
{
String user = securityManager.getUser( securityContext, servletRequest );
final String baseUrl = getBaseUrlByStoreKey( uriInfo, request.getSource() );
return repairManager.repairVol( request, user, baseUrl );
}
catch ( KojiRepairException | KojiClientException e )
{
logger.error( e.getMessage(), e );
responseHelper.throwError( e );
}
return null;
}
@ApiOperation( "Repair koji repository path masks." )
@ApiResponse( code = 200, message = "Operation finished (consult response content for success/failure).",
response = KojiRepairResult.class )
@ApiImplicitParam( name = "body", paramType = "body",
value = "JSON request specifying source and other configuration options",
required = true, dataType = "org.commonjava.indy.koji.model.KojiRepairRequest" )
@POST
@Path( "/" + MASK )
@Consumes( ApplicationContent.application_json )
public KojiRepairResult repairPathMasks( final KojiRepairRequest request, final @Context HttpServletRequest servletRequest,
final @Context SecurityContext securityContext, final @Context UriInfo uriInfo )
{
try
{
String user = securityManager.getUser( securityContext, servletRequest );
return repairManager.repairPathMask( request, user );
}
catch ( KojiRepairException e )
{
logger.error( e.getMessage(), e );
responseHelper.throwError( e );
}
return null;
}
@ApiOperation( "Repair koji repository path masks for ALL koji remote repositories." )
@ApiResponse( code = 200, message = "Operation finished (consult response content for success/failure).",
response = KojiMultiRepairResult.class )
@POST
@Path( "/" + ALL_MASKS )
@Consumes( ApplicationContent.application_json )
public KojiMultiRepairResult repairAllPathMasks( final @Context HttpServletRequest servletRequest,
final @Context SecurityContext securityContext, final @Context UriInfo uriInfo )
{
try
{
String user = securityManager.getUser( securityContext, servletRequest );
return repairManager.repairAllPathMasks( user );
}
catch ( KojiRepairException | IndyWorkflowException e )
{
logger.error( e.getMessage(), e );
responseHelper.throwError( e );
}
return null;
}
@ApiOperation( "Repair koji repository metadata timeout to \"never timeout(-1)\"." )
@ApiResponse( code = 200, message = "Operation finished (consult response content for success/failure).",
response = KojiRepairResult.class )
@ApiImplicitParam( name = "body", paramType = "body",
value = "JSON request specifying source and other configuration options",
required = true, dataType = "org.commonjava.indy.koji.model.KojiRepairRequest" )
@POST
@Path( "/" + META_TIMEOUT )
@Consumes( ApplicationContent.application_json )
public KojiRepairResult repairMetadataTimeout( final KojiRepairRequest request, final @Context HttpServletRequest servletRequest,
final @Context SecurityContext securityContext )
{
try
{
String user = securityManager.getUser( securityContext, servletRequest );
return repairManager.repairMetadataTimeout( request, user );
}
catch ( KojiRepairException e )
{
logger.error( e.getMessage(), e );
responseHelper.throwError( e );
}
return null;
}
@ApiOperation(
"Repair koji repository metadata timeout to \"never timeout(-1)\" for all koji remote repositories." )
@ApiImplicitParam( name = "isDryRun", paramType = "query",
value = "boolean value to specify if this request is a dry run request", defaultValue = "false",
dataType = "java.lang.Boolean" )
@ApiResponse( code = 200, message = "Operation finished (consult response content for success/failure).",
response = KojiMultiRepairResult.class )
@POST
@Path( "/" + META_TIMEOUT_ALL )
@Consumes( ApplicationContent.application_json )
public KojiMultiRepairResult repairAllMetadataTimeout( final @Context HttpServletRequest servletRequest,
final @QueryParam( "isDryRun" ) Boolean isDryRun,
final @Context SecurityContext securityContext )
{
String user = securityManager.getUser( securityContext, servletRequest );
final boolean dryRun = isDryRun == null ? false : isDryRun;
try
{
return repairManager.repairAllMetadataTimeout( user, dryRun );
}
catch ( KojiRepairException | IndyWorkflowException e )
{
logger.error( e.getMessage(), e );
responseHelper.throwError( e );
}
return null;
}
}
| apache-2.0 |
gkatsikas/onos | protocols/bgp/api/src/main/java/org/onosproject/bgp/controller/BgpPacketStats.java | 1512 | /*
* Copyright 2015-present Open Networking Foundation
*
* 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.onosproject.bgp.controller;
/**
* A representation of a packet context which allows any provider to view a packet in event, but may block the response
* to the event if blocked has been called. This packet context can be used to react to the packet in event with a
* packet out.
*/
public interface BgpPacketStats {
/**
* Returns the count for no of packets sent out.
*
* @return int value of no of packets sent
*/
int outPacketCount();
/**
* Returns the count for no of packets received.
*
* @return int value of no of packets sent
*/
int inPacketCount();
/**
* Returns the count for no of wrong packets received.
*
* @return int value of no of wrong packets received
*/
int wrongPacketCount();
/**
* Returns the time.
*
* @return the time
*/
long getTime();
} | apache-2.0 |
fholm/IronJS | Src/Tests/Sputnik/sputnik-v1/tests/Conformance/15_Native_ECMA_Script_Objects/15.9_Date_Objects/15.9.5_Properties_of_the_Date_Prototype_Object/15.9.5.38_Date.prototype.setMonth/S15.9.5.38_A3_T1.js | 550 | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.9.5.38_A3_T1;
* @section: 15.9.5.38;
* @assertion: The Date.prototype.setMonth property "length" has { ReadOnly, DontDelete, DontEnum } attributes;
* @description: Checking ReadOnly attribute;
*/
x = Date.prototype.setMonth.length;
Date.prototype.setMonth.length = 1;
if (Date.prototype.setMonth.length !== x) {
$ERROR('#1: The Date.prototype.setMonth.length has the attribute ReadOnly');
}
| apache-2.0 |
apache/incubator-openaz | openaz-xacml-pdp/src/main/java/org/apache/openaz/xacml/pdp/policy/expressions/AttributeValueExpression.java | 3800 | /*
* 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.
*
*/
/*
* AT&T - PROPRIETARY
* THIS FILE CONTAINS PROPRIETARY INFORMATION OF
* AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN
* ACCORDANCE WITH APPLICABLE AGREEMENTS.
*
* Copyright (c) 2013 AT&T Knowledge Ventures
* Unpublished and Not for Publication
* All Rights Reserved
*/
package org.apache.openaz.xacml.pdp.policy.expressions;
import org.apache.openaz.xacml.api.AttributeValue;
import org.apache.openaz.xacml.api.StatusCode;
import org.apache.openaz.xacml.pdp.eval.EvaluationContext;
import org.apache.openaz.xacml.pdp.eval.EvaluationException;
import org.apache.openaz.xacml.pdp.policy.Expression;
import org.apache.openaz.xacml.pdp.policy.ExpressionResult;
import org.apache.openaz.xacml.pdp.policy.PolicyDefaults;
import org.apache.openaz.xacml.std.StdStatus;
import org.apache.openaz.xacml.std.StdStatusCode;
/**
* AttributeValueExpression extends {@link org.apache.openaz.xacml.pdp.policy.Expression} to represent XACML
* AttributeValue elements in an Expression context.
*/
public class AttributeValueExpression extends Expression {
private AttributeValue<?> attributeValue;
public AttributeValueExpression(StatusCode statusCodeIn, String statusMessageIn) {
super(statusCodeIn, statusMessageIn);
}
public AttributeValueExpression(StatusCode statusCodeIn) {
super(statusCodeIn);
}
public AttributeValueExpression() {
}
public AttributeValueExpression(AttributeValue<?> attributeValueIn) {
this.attributeValue = attributeValueIn;
}
public AttributeValue<?> getAttributeValue() {
return this.attributeValue;
}
public void setAttributeValue(AttributeValue<?> attributeValueIn) {
this.attributeValue = attributeValueIn;
}
@Override
public ExpressionResult evaluate(EvaluationContext evaluationContext, PolicyDefaults policyDefaults)
throws EvaluationException {
if (!this.validate()) {
return ExpressionResult.newError(new StdStatus(this.getStatusCode(), this.getStatusMessage()));
}
return ExpressionResult.newSingle(this.getAttributeValue());
}
@Override
protected boolean validateComponent() {
if (this.getAttributeValue() == null) {
this.setStatus(StdStatusCode.STATUS_CODE_SYNTAX_ERROR, "Missing AttributeValue");
return false;
} else {
this.setStatus(StdStatusCode.STATUS_CODE_OK, null);
return true;
}
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder("{");
Object objectToDump;
if ((objectToDump = this.getAttributeValue()) != null) {
stringBuilder.append("attributeValue=");
stringBuilder.append(objectToDump.toString());
}
stringBuilder.append('}');
return stringBuilder.toString();
}
}
| apache-2.0 |
klcodanr/sling | contrib/explorers/resourceeditor/src/main/resources/SLING-INF/libs/sling/resource-editor-static-content/js/tree/JSTreeAdapter.js | 5929 | /*
* 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.
*/
// creating the namespace
var org = org || {};
org.apache = org.apache || {};
org.apache.sling = org.apache.sling || {};
org.apache.sling.reseditor = org.apache.sling.reseditor || {};
/*
JSTreeAdapter - It adapts the JSTree library for the use in the Sling Resource Editor.
This JSTreeAdapter contains as less logic as needed to configure the JSTree for the Sling Resource Editor. For
everything that goes beyond that and contains more functionality, the other Sling Resource Editor controllers are called.
*/
//defining the module
org.apache.sling.reseditor.JSTreeAdapter = (function() {
function JSTreeAdapter(settings, treeController, mainController){
this.settings = settings;
this.treeController = treeController;
this.mainController = mainController;
var thisJSTreeAdapter = this;
$(document).ready(function() {
$(window).resize( function() {
thisJSTreeAdapter.mainController.adjust_height();
});
var scrollToPathFinished=false;
thisJSTreeAdapter.mainController.adjust_height();
// TO CREATE AN INSTANCE
// select the tree container using jQuery
$("#tree")
.bind("loaded.jstree", function (event, data) {
var pathElements = treeController.getPathElements(settings.resourcePath);
if (pathElements.length >= 1 && pathElements[0] != "") {
treeController.openElement($("#tree > ul > li[nodename=''] > ul"), pathElements);
}
// position the info-icon
$('#tree-info-icon').show();
$('#root i:first').before($('#tree-info-icon'));
})
// call `.jstree` with the options object
.jstree({
"core" : {
"check_callback" : true,
multiple: true,
animation: 600,
'data' : {
'url' : function (liJson) {
// initial call for the root element
if (liJson.id === '#'){
return settings.contextPath+"/reseditor/.rootnodes.json";
} else {
// the li the user clicked on.
var li = $('#'+liJson.id);
return treeController.get_uri_from_li(li,".nodes.json");
}
},
'data' : function (node) {
return { 'id' : node.id };
}
}
},
"ui" : {
"select_limit" : 2
},
"crrm" : {
"move" : {
"always_copy" : false,
"check_move" : function (m) {
// you find the member description here
// http://www.jstree.com/documentation/core.html#_get_move
// TODO refactor to the new jsTree version
var src_li = m.o;
var src_nt = mainController.getNTFromLi(src_li);
var src_nodename = src_li.attr("nodename");
var new_parent_ul = m.np.children("ul");
var calculated_position = m.cp;
var liAlreadySelected = new_parent_ul.length==0 && m.np.prop("tagName").toUpperCase() == 'LI';
var dest_li = liAlreadySelected ? m.np : new_parent_ul.children("li:eq("+(calculated_position-1)+")");
var dest_nt = mainController.getNTFromLi(dest_li);
var result;
if (dest_nt != null){
result = dest_nt.canAddChildNode(src_nodename, src_nt);
}
return result;
}
}
},
"dnd" : {
"drop_finish" : function () {
console.log("drop");
},
"drag_finish" : function (data) {
console.log("drag");
}
},
// the `plugins` array allows you to configure the active plugins on this instance
"plugins" : [ "themes", "ui", "core", "hotkeys", "crrm", "dnd"]
}).bind("rename_node.jstree", function (e, data) {
treeController.renameNode(e, data);
}).bind("move_node.jstree", function (e, data) {
// see http://www.jstree.com/documentation/core ._get_move()
// TODO refactor to the new jsTree version
var src_li = data.rslt.o;
var src_path = ""+settings.contextPath+src_li.children("a").attr("target");
var dest_li = data.rslt.np; // new parent .cr - same as np, but if a root node is created this is -1
var dest_li_path = dest_li.children("a").attr("target") == "/" ? "" : dest_li.children("a").attr("target");
var dest_path = ""+settings.contextPath+dest_li_path+"/"+src_li.attr("nodename");
var original_parent = data.rslt.op;
var is_copy = data.rslt.cy;
var position = data.rslt.cp;
$.ajax({
type: 'POST',
url: src_path,
dataType: "json",
success: function(server_data) {
var target = ""+settings.contextPath+dest_path;
location.href=target+".reseditor.html";
},
error: function(errorJson) {
displayAlert(errorJson);
},
data: {
":operation": "move",
// ":order": position,
":dest": dest_path
}
});
}).on('hover_node.jstree', function (event, nodeObj) {
//noop
}).on('keydown.jstree', 'a.jstree-anchor', function (e) {
treeController.configureKeyListeners(e);
}).on('select_node.jstree', function (e, data) {
;
}).on('after_open.jstree', function(e, data){
treeController.afterOpen(data.node);
}).on('close_node.jstree', function(e, data){
treeController.beforeClose(data.node);
});
});
};
return JSTreeAdapter;
}());
| apache-2.0 |
sijie/bookkeeper | stream/distributedlog/common/src/main/java/org/apache/distributedlog/io/package-info.java | 884 | /*
* 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.
*/
/**
* IO Utils for distributedlog.
*/
package org.apache.distributedlog.io;
| apache-2.0 |
zi1jing/spring-net | test/Spring/Spring.Web.Tests/Web/UI/SessionModelPersistenceMediumTests.cs | 2594 | #region License
/*
* Copyright © 2002-2011 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
*
* 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.
*/
#endregion
#region Imports
using System;
using System.Collections;
using System.Web.UI;
using NUnit.Framework;
using Spring.Collections;
using Spring.TestSupport;
#endregion
namespace Spring.Web.UI
{
/// <summary>
///
/// </summary>
/// <author>Erich Eichinger</author>
[TestFixture]
public class SessionModelPersistenceMediumTests
{
private class TestSessionModelPersistenceMedium : SessionModelPersistenceMedium
{
private Hashtable _sessionItems = new CaseInsensitiveHashtable();
public Hashtable SessionItems
{
get { return _sessionItems; }
}
protected override object GetItem( System.Web.UI.Control context, string key )
{
//return base.GetItem( context, key );
return _sessionItems[key];
}
protected override void SetItem( System.Web.UI.Control context, string key, object item )
{
//base.SetItem( context, key, item );
_sessionItems[key] = item;
}
protected override string GetKey( Control context )
{
//return base.GetKey( context );
return context.ID;
}
}
[Test]
public void StoresAndRetrievesModelItem()
{
TestSessionModelPersistenceMedium pm = new TestSessionModelPersistenceMedium();
Control tuc = new TestUserControl("TucID");
pm.SaveToMedium( tuc, this );
// ensure key was generated by GetKey() and Item was added to storage
Assert.AreEqual( this, pm.SessionItems["TucID"] );
// ensure key was generated by GetKey() and Item is retrieved from storage
Assert.AreEqual( this, pm.LoadFromMedium( tuc ) );
}
}
} | apache-2.0 |
sendilkumarn/generator-jhipster | generators/server/needle-api/needle-server-maven.js | 9100 | /**
* Copyright 2013-2020 the original author or authors from the JHipster project.
*
* This file is part of the JHipster project, see https://www.jhipster.tech/
* for more information.
*
* 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.
*/
const chalk = require('chalk');
const needleServer = require('./needle-server');
const pomPath = 'pom.xml';
module.exports = class extends needleServer {
addDependencyManagement(groupId, artifactId, version, type, scope, other) {
const errorMessage = `${chalk.yellow('Reference to maven dependency ')}
(groupId: ${groupId}, artifactId:${artifactId}, version:${version})${chalk.yellow(' not added.\n')}`;
// prettier-ignore
let dependency = `${'<dependency>\n'
+ ' <groupId>'}${groupId}</groupId>\n`
+ ` <artifactId>${artifactId}</artifactId>\n`;
if (version) {
dependency += ` <version>${version}</version>\n`;
}
if (type) {
dependency += ` <type>${type}</type>\n`;
}
if (scope) {
dependency += ` <scope>${scope}</scope>\n`;
}
if (other) {
dependency += `${other}\n`;
}
dependency += ' </dependency>';
const rewriteFileModel = this.generateFileModel(pomPath, '<!-- jhipster-needle-maven-add-dependency-management -->', dependency);
this.addBlockContentToFile(rewriteFileModel, errorMessage);
}
addRepository(id, url, other = '') {
const errorMessage = `${chalk.yellow(' Reference to ')}maven repository (id: ${id}, url:${url})${chalk.yellow(' not added.\n')}`;
// prettier-ignore
let repository = `${'<repository>\n'
+ ' <id>'}${id}</id>\n`
+ ` <url>${url}</url>\n`;
if (other) {
repository += `${other}\n`;
}
repository += ' </repository>';
const rewriteFileModel = this.generateFileModel(pomPath, '<!-- jhipster-needle-maven-repository -->', repository);
this.addBlockContentToFile(rewriteFileModel, errorMessage);
}
addPluginRepository(id, url) {
const errorMessage = `${chalk.yellow(' Reference to ')}maven plugin repository (id: ${id}, url:${url})
${chalk.yellow(' not added.\n')}`;
// prettier-ignore
const repository = `${'<pluginRepository>\n'
+ ' <id>'}${id}</id>\n`
+ ` <url>${url}</url>\n`
+ ' </pluginRepository>';
const rewriteFileModel = this.generateFileModel(pomPath, '<!-- jhipster-needle-maven-plugin-repository -->', repository);
this.addBlockContentToFile(rewriteFileModel, errorMessage);
}
addDistributionManagement(snapshotsId, snapshotsUrl, releasesId, releasesUrl) {
const errorMessage = `${chalk.yellow('Reference to maven distribution management ')}
(id: ${snapshotsId}, url:${snapshotsId}), (id: ${releasesId}, url:${releasesUrl})${chalk.yellow(' not added.\n')}`;
// prettier-ignore
const repository = `${'<distributionManagement>\n'
+ ' <snapshotRepository>\n'
+ ' <id>'}${snapshotsId}</id>\n`
+ ` <url>${snapshotsUrl}</url>\n`
+ ' </snapshotRepository>\n'
+ ' <repository>\n'
+ ` <id>${releasesId}</id>\n`
+ ` <url>${releasesUrl}</url>\n`
+ ' </repository>\n'
+ ' </distributionManagement>';
const rewriteFileModel = this.generateFileModel(pomPath, '<!-- jhipster-needle-distribution-management -->', repository);
this.addBlockContentToFile(rewriteFileModel, errorMessage);
}
addProperty(name, value) {
const errorMessage = `${chalk.yellow('Reference to maven property name ')}
(name: ${name}, value:${value})${chalk.yellow(' not added.\n')}`;
const property = `<${name}>${value}</${name}>`;
const rewriteFileModel = this.generateFileModel(pomPath, '<!-- jhipster-needle-maven-property -->', property);
this.addBlockContentToFile(rewriteFileModel, errorMessage);
}
addDependencyInDirectory(directory, groupId, artifactId, version, other) {
const errorMessage = `${chalk.yellow('Reference to maven dependency ')}
(groupId: ${groupId}, artifactId:${artifactId}, version:${version})${chalk.yellow(' not added.\n')}`;
// prettier-ignore
let dependency = `${'<dependency>\n'
+ ' <groupId>'}${groupId}</groupId>\n`
+ ` <artifactId>${artifactId}</artifactId>\n`;
if (version) {
dependency += ` <version>${version}</version>\n`;
}
if (other) {
dependency += `${other}\n`;
}
dependency += ' </dependency>';
const rewriteFileModel = this.generateFileModelWithPath(
directory,
pomPath,
'<!-- jhipster-needle-maven-add-dependency -->',
dependency
);
this.addBlockContentToFile(rewriteFileModel, errorMessage);
}
addPlugin(groupId, artifactId, version, other) {
const errorMessage = `${chalk.yellow('Reference to maven plugin ')}
(groupId: ${groupId}, artifactId:${artifactId}, version:${version})${chalk.yellow(' not added.\n')}`;
// prettier-ignore
let plugin = `${'<plugin>\n'
+ ' <groupId>'}${groupId}</groupId>\n`
+ ` <artifactId>${artifactId}</artifactId>\n`;
if (version) {
plugin += ` <version>${version}</version>\n`;
}
if (other) {
plugin += `${other}\n`;
}
plugin += ' </plugin>';
const rewriteFileModel = this.generateFileModel(pomPath, '<!-- jhipster-needle-maven-add-plugin -->', plugin);
this.addBlockContentToFile(rewriteFileModel, errorMessage);
}
addPluginManagement(groupId, artifactId, version, other) {
const errorMessage = `${chalk.yellow('Reference to maven plugin management ')}
(groupId: ${groupId}, artifactId:${artifactId}, version:${version})${chalk.yellow(' not added.\n')}`;
// prettier-ignore
let plugin = `${' <plugin>\n'
+ ' <groupId>'}${groupId}</groupId>\n`
+ ` <artifactId>${artifactId}</artifactId>\n`;
if (version) {
plugin += ` <version>${version}</version>\n`;
}
if (other) {
plugin += `${other}\n`;
}
plugin += ' </plugin>';
const rewriteFileModel = this.generateFileModel(pomPath, '<!-- jhipster-needle-maven-add-plugin-management -->', plugin);
this.addBlockContentToFile(rewriteFileModel, errorMessage);
}
addAnnotationProcessor(groupId, artifactId, version) {
const errorMessage = `${chalk.yellow(
' Reference to '
)}maven annotation processor (groupId: ${groupId}, artifactId:${artifactId}, version:${version})
${chalk.yellow(' not added.\n')}`;
// prettier-ignore
const annotationProcessorPath = `${'<path>\n'
+ ' <groupId>'}${groupId}</groupId>\n`
+ ` <artifactId>${artifactId}</artifactId>\n`
+ ` <version>${version}</version>\n`
+ ' </path>';
const rewriteFileModel = this.generateFileModel(
pomPath,
'<!-- jhipster-needle-maven-add-annotation-processor -->',
annotationProcessorPath
);
this.addBlockContentToFile(rewriteFileModel, errorMessage);
}
addProfile(profileId, other) {
const errorMessage = `${chalk.yellow('Reference to maven profile ')}
(id: ${profileId})${chalk.yellow(' not added.\n')}`;
// prettier-ignore
let profile = '<profile>\n'
+ ` <id>${profileId}</id>\n`;
if (other) {
profile += `${other}\n`;
}
profile += ' </profile>';
const rewriteFileModel = this.generateFileModel(pomPath, '<!-- jhipster-needle-maven-add-profile -->', profile);
this.addBlockContentToFile(rewriteFileModel, errorMessage);
}
};
| apache-2.0 |
envoy/ember-nf-graph | app/components/nf-selection-box.js | 3680 | import Ember from 'ember';
import HasGraphParent from 'ember-nf-graph/mixins/graph-has-graph-parent';
import RequireScaleSource from 'ember-nf-graph/mixins/graph-requires-scale-source';
import { normalizeScale } from 'ember-nf-graph/utils/nf/scale-utils';
/**
Draws a rectangle on an `nf-graph` given domain values `xMin`, `xMax`, `yMin` and `yMax`.
@namespace components
@class nf-selection-box
@extends Ember.Component
@uses mixins.graph-has-graph-parent
@uses mixins.graph-requires-scale-source
*/
export default Ember.Component.extend(HasGraphParent, RequireScaleSource, {
tagName: 'g',
/**
The duration of the transition in ms
@property duration
@type Number
@default 400
*/
duration: 400,
/**
The minimum x domain value to encompass.
@property xMin
@default null
*/
xMin: null,
/**
The maximum x domain value to encompoass.
@property xMax
@default null
*/
xMax: null,
/**
The minimum y domain value to encompass.
@property yMin
@default null
*/
yMin: null,
/**
The maximum y domain value to encompass
@property yMax
@default null
*/
yMax: null,
classNames: ['nf-selection-box'],
/**
The x pixel position of xMin
@property x0
@type Number
*/
x0: Ember.computed('xMin', 'xScale', function(){
return normalizeScale(this.get('xScale'), this.get('xMin'));
}),
/**
The x pixel position of xMax
@property x1
@type Number
*/
x1: Ember.computed('xMax', 'xScale', function(){
return normalizeScale(this.get('xScale'), this.get('xMax'));
}),
/**
The y pixel position of yMin
@property y0
@type Number
*/
y0: Ember.computed('yMin', 'yScale', function(){
return normalizeScale(this.get('yScale'), this.get('yMin'));
}),
/**
The y pixel position of yMax
@property y1
@type Number
*/
y1: Ember.computed('yMax', 'yScale', function(){
return normalizeScale(this.get('yScale'), this.get('yMax'));
}),
/**
The SVG path string for the box's rectangle.
@property rectPath
@type String
*/
rectPath: Ember.computed('x0', 'x1', 'y0', 'y1', function(){
var x0 = this.get('x0');
var x1 = this.get('x1');
var y0 = this.get('y0');
var y1 = this.get('y1');
return `M${x0},${y0} L${x0},${y1} L${x1},${y1} L${x1},${y0} L${x0},${y0}`;
}),
/**
Updates the position of the box with a transition
@method doUpdatePosition
*/
doUpdatePosition: function(){
var boxRect = this.get('boxRectElement');
var rectPath = this.get('rectPath');
var duration = this.get('duration');
boxRect.transition().duration(duration)
.attr('d', rectPath);
},
doUpdatePositionStatic: function(){
var boxRect = this.get('boxRectElement');
var rectPath = this.get('rectPath');
boxRect.attr('d', rectPath);
},
/**
Schedules an update to the position of the box after render.
@method updatePosition
@private
*/
updatePosition: Ember.observer('xMin', 'xMax', 'yMin', 'yMax', function(){
Ember.run.once(this, this.doUpdatePosition);
}),
staticPositionChange: Ember.on('didInsertElement', Ember.observer('xScale', 'yScale', function(){
Ember.run.once(this, this.doUpdatePositionStatic);
})),
/**
Sets up the required d3 elements after component
is inserted into the DOM
@method didInsertElement
*/
didInsertElement: function(){
var element = this.get('element');
var g = d3.select(element);
var boxRect = g.append('path')
.attr('class', 'nf-selection-box-rect')
.attr('d', this.get('rectPath'));
this.set('boxRectElement', boxRect);
},
}); | apache-2.0 |
khyperia/roslyn | src/Workspaces/CSharp/Portable/LanguageServices/CSharpSemanticFactsService.cs | 13425 | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal class CSharpSemanticFactsService : ISemanticFactsService
{
internal static readonly CSharpSemanticFactsService Instance = new CSharpSemanticFactsService();
private CSharpSemanticFactsService()
{
}
public bool SupportsImplicitInterfaceImplementation => true;
public bool ExposesAnonymousFunctionParameterNames => false;
public bool IsExpressionContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsExpressionContext(
position,
semanticModel.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken),
attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel);
}
public bool IsInExpressionTree(SemanticModel semanticModel, SyntaxNode node, INamedTypeSymbol expressionTypeOpt, CancellationToken cancellationToken)
=> node.IsInExpressionTree(semanticModel, expressionTypeOpt, cancellationToken);
public bool IsStatementContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsStatementContext(
position, semanticModel.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken), cancellationToken);
}
public bool IsTypeContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsTypeContext(position, cancellationToken, semanticModel);
}
public bool IsNamespaceContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsNamespaceContext(position, cancellationToken, semanticModel);
}
public bool IsNamespaceDeclarationNameContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsNamespaceDeclarationNameContext(position, cancellationToken);
}
public bool IsTypeDeclarationContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsTypeDeclarationContext(
position, semanticModel.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken), cancellationToken);
}
public bool IsMemberDeclarationContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsMemberDeclarationContext(
position, semanticModel.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken), cancellationToken);
}
public bool IsPreProcessorDirectiveContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsPreProcessorDirectiveContext(
position, semanticModel.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken);
}
public bool IsGlobalStatementContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsGlobalStatementContext(position, cancellationToken);
}
public bool IsLabelContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsLabelContext(position, cancellationToken);
}
public bool IsAttributeNameContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsAttributeNameContext(position, cancellationToken);
}
public bool IsWrittenTo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
=> (node as ExpressionSyntax).IsWrittenTo();
public bool IsOnlyWrittenTo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
=> (node as ExpressionSyntax).IsOnlyWrittenTo();
public bool IsInOutContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
=> (node as ExpressionSyntax).IsInOutContext();
public bool IsInRefContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
=> (node as ExpressionSyntax).IsInRefContext();
public bool IsInInContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
=> (node as ExpressionSyntax).IsInInContext();
public bool CanReplaceWithRValue(SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken)
{
return (expression as ExpressionSyntax).CanReplaceWithRValue(semanticModel, cancellationToken);
}
public string GenerateNameForExpression(SemanticModel semanticModel, SyntaxNode expression, bool capitalize, CancellationToken cancellationToken)
=> semanticModel.GenerateNameForExpression((ExpressionSyntax)expression, capitalize, cancellationToken);
public ISymbol GetDeclaredSymbol(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken)
{
var location = token.GetLocation();
var q = from node in token.GetAncestors<SyntaxNode>()
let symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken)
where symbol != null && symbol.Locations.Contains(location)
select symbol;
return q.FirstOrDefault();
}
public bool LastEnumValueHasInitializer(INamedTypeSymbol namedTypeSymbol)
{
var enumDecl = namedTypeSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).OfType<EnumDeclarationSyntax>().FirstOrDefault();
if (enumDecl != null)
{
var lastMember = enumDecl.Members.LastOrDefault();
if (lastMember != null)
{
return lastMember.EqualsValue != null;
}
}
return false;
}
public bool SupportsParameterizedProperties
{
get
{
return false;
}
}
public bool TryGetSpeculativeSemanticModel(SemanticModel oldSemanticModel, SyntaxNode oldNode, SyntaxNode newNode, out SemanticModel speculativeModel)
{
Contract.Requires(oldNode.Kind() == newNode.Kind());
var model = oldSemanticModel;
// currently we only support method. field support will be added later.
var oldMethod = oldNode as BaseMethodDeclarationSyntax;
var newMethod = newNode as BaseMethodDeclarationSyntax;
if (oldMethod == null || newMethod == null || oldMethod.Body == null)
{
speculativeModel = null;
return false;
}
var success = model.TryGetSpeculativeSemanticModelForMethodBody(oldMethod.Body.OpenBraceToken.Span.End, newMethod, out var csharpModel);
speculativeModel = csharpModel;
return success;
}
public ImmutableHashSet<string> GetAliasNameSet(SemanticModel model, CancellationToken cancellationToken)
{
var original = model.GetOriginalSemanticModel();
if (!original.SyntaxTree.HasCompilationUnitRoot)
{
return ImmutableHashSet.Create<string>();
}
var root = original.SyntaxTree.GetCompilationUnitRoot(cancellationToken);
var builder = ImmutableHashSet.CreateBuilder<string>(StringComparer.Ordinal);
AppendAliasNames(root.Usings, builder);
AppendAliasNames(root.Members.OfType<NamespaceDeclarationSyntax>(), builder, cancellationToken);
return builder.ToImmutable();
}
private static void AppendAliasNames(SyntaxList<UsingDirectiveSyntax> usings, ImmutableHashSet<string>.Builder builder)
{
foreach (var @using in usings)
{
if (@using.Alias == null || @using.Alias.Name == null)
{
continue;
}
@using.Alias.Name.Identifier.ValueText.AppendToAliasNameSet(builder);
}
}
private void AppendAliasNames(IEnumerable<NamespaceDeclarationSyntax> namespaces, ImmutableHashSet<string>.Builder builder, CancellationToken cancellationToken)
{
foreach (var @namespace in namespaces)
{
cancellationToken.ThrowIfCancellationRequested();
AppendAliasNames(@namespace.Usings, builder);
AppendAliasNames(@namespace.Members.OfType<NamespaceDeclarationSyntax>(), builder, cancellationToken);
}
}
public ForEachSymbols GetForEachSymbols(SemanticModel semanticModel, SyntaxNode forEachStatement)
{
if (forEachStatement is CommonForEachStatementSyntax csforEachStatement)
{
var info = semanticModel.GetForEachStatementInfo(csforEachStatement);
return new ForEachSymbols(
info.GetEnumeratorMethod,
info.MoveNextMethod,
info.CurrentProperty,
info.DisposeMethod,
info.ElementType);
}
else
{
return default;
}
}
public ImmutableArray<IMethodSymbol> GetDeconstructionAssignmentMethods(SemanticModel semanticModel, SyntaxNode node)
{
if (node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction())
{
var builder = ArrayBuilder<IMethodSymbol>.GetInstance();
FlattenDeconstructionMethods(semanticModel.GetDeconstructionInfo(assignment), builder);
return builder.ToImmutableAndFree();
}
return ImmutableArray<IMethodSymbol>.Empty;
}
public ImmutableArray<IMethodSymbol> GetDeconstructionForEachMethods(SemanticModel semanticModel, SyntaxNode node)
{
if (node is ForEachVariableStatementSyntax @foreach)
{
var builder = ArrayBuilder<IMethodSymbol>.GetInstance();
FlattenDeconstructionMethods(semanticModel.GetDeconstructionInfo(@foreach), builder);
return builder.ToImmutableAndFree();
}
return ImmutableArray<IMethodSymbol>.Empty;
}
private static void FlattenDeconstructionMethods(DeconstructionInfo deconstruction, ArrayBuilder<IMethodSymbol> builder)
{
var method = deconstruction.Method;
if (method != null)
{
builder.Add(method);
}
foreach (var nested in deconstruction.Nested)
{
FlattenDeconstructionMethods(nested, builder);
}
}
public bool IsAssignableTo(ITypeSymbol fromSymbol, ITypeSymbol toSymbol, Compilation compilation)
{
return fromSymbol != null &&
toSymbol != null &&
((CSharpCompilation)compilation).ClassifyConversion(fromSymbol, toSymbol).IsImplicit;
}
public bool IsNameOfContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsNameOfContext(position, semanticModel, cancellationToken);
}
public bool IsPartial(ITypeSymbol typeSymbol, CancellationToken cancellationToken)
{
var syntaxRefs = typeSymbol.DeclaringSyntaxReferences;
return syntaxRefs.Any(n => ((BaseTypeDeclarationSyntax)n.GetSyntax(cancellationToken)).Modifiers.Any(SyntaxKind.PartialKeyword));
}
public IEnumerable<ISymbol> GetDeclaredSymbols(
SemanticModel semanticModel, SyntaxNode memberDeclaration, CancellationToken cancellationToken)
{
if (memberDeclaration is FieldDeclarationSyntax field)
{
return field.Declaration.Variables.Select(
v => semanticModel.GetDeclaredSymbol(v, cancellationToken));
}
return SpecializedCollections.SingletonEnumerable(
semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken));
}
}
}
| apache-2.0 |
hgschmie/presto | presto-parquet/src/main/java/io/prestosql/parquet/writer/repdef/DefLevelIterables.java | 9220 | /*
* 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 io.prestosql.parquet.writer.repdef;
import com.google.common.collect.AbstractIterator;
import io.prestosql.parquet.writer.repdef.DefLevelIterable.DefLevelIterator;
import io.prestosql.spi.block.Block;
import io.prestosql.spi.block.ColumnarArray;
import io.prestosql.spi.block.ColumnarMap;
import io.prestosql.spi.block.ColumnarRow;
import java.util.Iterator;
import java.util.List;
import java.util.OptionalInt;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.util.Collections.nCopies;
import static java.util.Objects.requireNonNull;
public class DefLevelIterables
{
private DefLevelIterables() {}
public static DefLevelIterable of(Block block, int maxDefinitionLevel)
{
return new PrimitiveDefLevelIterable(block, maxDefinitionLevel);
}
public static DefLevelIterable of(ColumnarRow columnarRow, int maxDefinitionLevel)
{
return new ColumnRowDefLevelIterable(columnarRow, maxDefinitionLevel);
}
public static DefLevelIterable of(ColumnarArray columnarArray, int maxDefinitionLevel)
{
return new ColumnArrayDefLevelIterable(columnarArray, maxDefinitionLevel);
}
public static DefLevelIterable of(ColumnarMap columnarMap, int maxDefinitionLevel)
{
return new ColumnMapDefLevelIterable(columnarMap, maxDefinitionLevel);
}
public static Iterator<Integer> getIterator(List<DefLevelIterable> iterables)
{
return new NestedDefLevelIterator(iterables);
}
static class PrimitiveDefLevelIterable
implements DefLevelIterable
{
private final Block block;
private final int maxDefinitionLevel;
PrimitiveDefLevelIterable(Block block, int maxDefinitionLevel)
{
this.block = requireNonNull(block, "block is null");
this.maxDefinitionLevel = maxDefinitionLevel;
}
@Override
public DefLevelIterator getIterator()
{
return new DefLevelIterator()
{
private int position = -1;
@Override
boolean end()
{
return true;
}
@Override
protected OptionalInt computeNext()
{
position++;
if (position == block.getPositionCount()) {
return endOfData();
}
if (block.isNull(position)) {
return OptionalInt.of(maxDefinitionLevel - 1);
}
return OptionalInt.of(maxDefinitionLevel);
}
};
}
}
static class ColumnRowDefLevelIterable
implements DefLevelIterable
{
private final ColumnarRow columnarRow;
private final int maxDefinitionLevel;
ColumnRowDefLevelIterable(ColumnarRow columnarRow, int maxDefinitionLevel)
{
this.columnarRow = requireNonNull(columnarRow, "columnarRow is null");
this.maxDefinitionLevel = maxDefinitionLevel;
}
@Override
public DefLevelIterator getIterator()
{
return new DefLevelIterator()
{
private int position = -1;
@Override
boolean end()
{
return true;
}
@Override
protected OptionalInt computeNext()
{
position++;
if (position == columnarRow.getPositionCount()) {
return endOfData();
}
if (columnarRow.isNull(position)) {
return OptionalInt.of(maxDefinitionLevel - 1);
}
return OptionalInt.empty();
}
};
}
}
static class ColumnMapDefLevelIterable
implements DefLevelIterable
{
private final ColumnarMap columnarMap;
private final int maxDefinitionLevel;
ColumnMapDefLevelIterable(ColumnarMap columnarMap, int maxDefinitionLevel)
{
this.columnarMap = requireNonNull(columnarMap, "columnarMap is null");
this.maxDefinitionLevel = maxDefinitionLevel;
}
@Override
public DefLevelIterator getIterator()
{
return new DefLevelIterator()
{
private int position = -1;
private Iterator<OptionalInt> iterator;
@Override
boolean end()
{
return iterator == null || !iterator.hasNext();
}
@Override
protected OptionalInt computeNext()
{
if (iterator != null && iterator.hasNext()) {
return iterator.next();
}
position++;
if (position == columnarMap.getPositionCount()) {
return endOfData();
}
if (columnarMap.isNull(position)) {
return OptionalInt.of(maxDefinitionLevel - 2);
}
int arrayLength = columnarMap.getEntryCount(position);
if (arrayLength == 0) {
return OptionalInt.of(maxDefinitionLevel - 1);
}
iterator = nCopies(arrayLength, OptionalInt.empty()).iterator();
return iterator.next();
}
};
}
}
static class ColumnArrayDefLevelIterable
implements DefLevelIterable
{
private final ColumnarArray columnarArray;
private final int maxDefinitionLevel;
ColumnArrayDefLevelIterable(ColumnarArray columnarArray, int maxDefinitionLevel)
{
this.columnarArray = requireNonNull(columnarArray, "columnarArray is null");
this.maxDefinitionLevel = maxDefinitionLevel;
}
@Override
public DefLevelIterator getIterator()
{
return new DefLevelIterator()
{
private int position = -1;
private Iterator<OptionalInt> iterator;
@Override
boolean end()
{
return iterator == null || !iterator.hasNext();
}
@Override
protected OptionalInt computeNext()
{
if (iterator != null && iterator.hasNext()) {
return iterator.next();
}
position++;
if (position == columnarArray.getPositionCount()) {
return endOfData();
}
if (columnarArray.isNull(position)) {
return OptionalInt.of(maxDefinitionLevel - 2);
}
int arrayLength = columnarArray.getLength(position);
if (arrayLength == 0) {
return OptionalInt.of(maxDefinitionLevel - 1);
}
iterator = nCopies(arrayLength, OptionalInt.empty()).iterator();
return iterator.next();
}
};
}
}
static class NestedDefLevelIterator
extends AbstractIterator<Integer>
{
private final List<DefLevelIterator> iterators;
private int iteratorIndex;
NestedDefLevelIterator(List<DefLevelIterable> iterables)
{
this.iterators = iterables.stream().map(DefLevelIterable::getIterator).collect(toImmutableList());
}
@Override
protected Integer computeNext()
{
DefLevelIterator current = iterators.get(iteratorIndex);
while (iteratorIndex > 0 && current.end()) {
iteratorIndex--;
current = iterators.get(iteratorIndex);
}
while (current.hasNext()) {
OptionalInt next = current.next();
if (next.isPresent()) {
return next.getAsInt();
}
iteratorIndex++;
current = iterators.get(iteratorIndex);
}
checkState(iterators.stream().noneMatch(AbstractIterator::hasNext));
return endOfData();
}
}
}
| apache-2.0 |
jpkrohling/hawkular-btm | server/processors/src/main/java/org/hawkular/apm/server/processor/tracecompletiontime/TraceCompletionInformationUtil.java | 4318 | /*
* Copyright 2015-2017 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.hawkular.apm.server.processor.tracecompletiontime;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hawkular.apm.api.model.trace.ContainerNode;
import org.hawkular.apm.api.model.trace.CorrelationIdentifier;
import org.hawkular.apm.api.model.trace.CorrelationIdentifier.Scope;
import org.hawkular.apm.api.model.trace.Node;
import org.hawkular.apm.api.model.trace.Producer;
/**
* This class represents utility functions to help calculate completion time for
* trace instances.
*
* @author gbrown
*/
public class TraceCompletionInformationUtil {
private static final Logger log = Logger.getLogger(TraceCompletionInformationUtil.class.getName());
/**
* This method initialises the completion time information for a trace
* instance.
*
* @param ci The information
* @param fragmentBaseTime The base time for the fragment (microseconds)
* @param n The node
* @param nodeId The path id for the node
*/
public static void initialiseLinks(TraceCompletionInformation ci, long fragmentBaseTime, Node n,
StringBuilder nodeId) {
// Add Communication to represent a potential 'CausedBy' link from one or more fragments back to
// this node
TraceCompletionInformation.Communication c = new TraceCompletionInformation.Communication();
c.getIds().add(nodeId.toString());
// Define a a multi-consumer as potentially multiple CausedBy correlations may be created
// back to this node
c.setMultipleConsumers(true);
// Calculate the base duration for the communication
c.setBaseDuration(n.getTimestamp() - fragmentBaseTime);
c.setExpire(System.currentTimeMillis()+
TraceCompletionInformation.Communication.DEFAULT_EXPIRY_WINDOW_MILLIS);
if (log.isLoggable(Level.FINEST)) {
log.finest("Adding communication to completion information: ci=" + ci + " comms=" + c);
}
ci.getCommunications().add(c);
if (n.getClass() == Producer.class) {
// Get correlation ids
List<CorrelationIdentifier> cids = n.findCorrelationIds(Scope.Interaction, Scope.ControlFlow);
if (!cids.isEmpty()) {
c = new TraceCompletionInformation.Communication();
for (int i = 0; i < cids.size(); i++) {
c.getIds().add(cids.get(i).getValue());
}
c.setMultipleConsumers(((Producer) n).multipleConsumers());
// Calculate the base duration for the communication
c.setBaseDuration(n.getTimestamp() - fragmentBaseTime);
c.setExpire(System.currentTimeMillis() +
TraceCompletionInformation.Communication.DEFAULT_EXPIRY_WINDOW_MILLIS);
if (log.isLoggable(Level.FINEST)) {
log.finest("Adding communication to completion information: ci=" + ci + " comms=" + c);
}
ci.getCommunications().add(c);
}
} else if (n.containerNode()) {
ContainerNode cn = (ContainerNode) n;
for (int i = 0; i < cn.getNodes().size(); i++) {
int len = nodeId.length();
nodeId.append(':');
nodeId.append(i);
initialiseLinks(ci, fragmentBaseTime, cn.getNodes().get(i), nodeId);
// Remove this child's specific path, so that next iteration will add a different path number
nodeId.delete(len, nodeId.length());
}
}
}
}
| apache-2.0 |
Microsoft/VisualStudio-SharedProject | Product/SharedProject/Automation/VSProject/OAAssemblyReference.cs | 5793 | /* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using VSLangProj;
namespace Microsoft.VisualStudioTools.Project.Automation {
[ComVisible(true)]
public class OAAssemblyReference : OAReferenceBase {
internal OAAssemblyReference(AssemblyReferenceNode assemblyReference) :
base(assemblyReference) {
}
internal new AssemblyReferenceNode BaseReferenceNode {
get {
return (AssemblyReferenceNode)base.BaseReferenceNode;
}
}
#region Reference override
public override int BuildNumber {
get {
if ((null == BaseReferenceNode.ResolvedAssembly) ||
(null == BaseReferenceNode.ResolvedAssembly.Version)) {
return 0;
}
return BaseReferenceNode.ResolvedAssembly.Version.Build;
}
}
public override string Culture {
get {
if ((null == BaseReferenceNode.ResolvedAssembly) ||
(null == BaseReferenceNode.ResolvedAssembly.CultureInfo)) {
return string.Empty;
}
return BaseReferenceNode.ResolvedAssembly.CultureInfo.Name;
}
}
public override string Identity {
get {
// Note that in this function we use the assembly name instead of the resolved one
// because the identity of this reference is the assembly name needed by the project,
// not the specific instance found in this machine / environment.
if (null == BaseReferenceNode.AssemblyName) {
return null;
}
// changed from MPFProj, http://mpfproj10.codeplex.com/workitem/11274
return BaseReferenceNode.AssemblyName.Name;
}
}
public override int MajorVersion {
get {
if ((null == BaseReferenceNode.ResolvedAssembly) ||
(null == BaseReferenceNode.ResolvedAssembly.Version)) {
return 0;
}
return BaseReferenceNode.ResolvedAssembly.Version.Major;
}
}
public override int MinorVersion {
get {
if ((null == BaseReferenceNode.ResolvedAssembly) ||
(null == BaseReferenceNode.ResolvedAssembly.Version)) {
return 0;
}
return BaseReferenceNode.ResolvedAssembly.Version.Minor;
}
}
public override string PublicKeyToken {
get {
if ((null == BaseReferenceNode.ResolvedAssembly) ||
(null == BaseReferenceNode.ResolvedAssembly.GetPublicKeyToken())) {
return null;
}
StringBuilder builder = new StringBuilder();
byte[] publicKeyToken = BaseReferenceNode.ResolvedAssembly.GetPublicKeyToken();
for (int i = 0; i < publicKeyToken.Length; i++) {
// changed from MPFProj:
// http://mpfproj10.codeplex.com/WorkItem/View.aspx?WorkItemId=8257
builder.AppendFormat("{0:x2}", publicKeyToken[i]);
}
return builder.ToString();
}
}
public override string Name {
get {
if (null != BaseReferenceNode.ResolvedAssembly) {
return BaseReferenceNode.ResolvedAssembly.Name;
}
if (null != BaseReferenceNode.AssemblyName) {
return BaseReferenceNode.AssemblyName.Name;
}
return null;
}
}
public override int RevisionNumber {
get {
if ((null == BaseReferenceNode.ResolvedAssembly) ||
(null == BaseReferenceNode.ResolvedAssembly.Version)) {
return 0;
}
return BaseReferenceNode.ResolvedAssembly.Version.Revision;
}
}
public override bool StrongName {
get {
if ((null == BaseReferenceNode.ResolvedAssembly) ||
(0 == (BaseReferenceNode.ResolvedAssembly.Flags & AssemblyNameFlags.PublicKey))) {
return false;
}
return true;
}
}
public override prjReferenceType Type {
get {
return prjReferenceType.prjReferenceTypeAssembly;
}
}
public override string Version {
get {
if ((null == BaseReferenceNode.ResolvedAssembly) ||
(null == BaseReferenceNode.ResolvedAssembly.Version)) {
return string.Empty;
}
return BaseReferenceNode.ResolvedAssembly.Version.ToString();
}
}
#endregion
}
}
| apache-2.0 |
home-assistant/home-assistant | homeassistant/components/tag/trigger.py | 1877 | """Support for tag triggers."""
import voluptuous as vol
from homeassistant.components.automation import (
AutomationActionType,
AutomationTriggerInfo,
)
from homeassistant.const import CONF_PLATFORM
from homeassistant.core import CALLBACK_TYPE, Event, HassJob, HomeAssistant
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.typing import ConfigType
from .const import DEVICE_ID, DOMAIN, EVENT_TAG_SCANNED, TAG_ID
TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_PLATFORM): DOMAIN,
vol.Required(TAG_ID): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(DEVICE_ID): vol.All(cv.ensure_list, [cv.string]),
}
)
async def async_attach_trigger(
hass: HomeAssistant,
config: ConfigType,
action: AutomationActionType,
automation_info: AutomationTriggerInfo,
) -> CALLBACK_TYPE:
"""Listen for tag_scanned events based on configuration."""
trigger_data = automation_info["trigger_data"]
tag_ids = set(config[TAG_ID])
device_ids = set(config[DEVICE_ID]) if DEVICE_ID in config else None
job = HassJob(action)
async def handle_event(event: Event) -> None:
"""Listen for tag scan events and calls the action when data matches."""
if event.data.get(TAG_ID) not in tag_ids or (
device_ids is not None and event.data.get(DEVICE_ID) not in device_ids
):
return
task = hass.async_run_hass_job(
job,
{
"trigger": {
**trigger_data,
"platform": DOMAIN,
"event": event,
"description": "Tag scanned",
}
},
event.context,
)
if task:
await task
return hass.bus.async_listen(EVENT_TAG_SCANNED, handle_event)
| apache-2.0 |
kuujo/onos | protocols/lisp/msg/src/main/java/org/onosproject/lisp/msg/protocols/LispGenericLocator.java | 3797 | /*
* Copyright 2017-present Open Networking Foundation
*
* 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.onosproject.lisp.msg.protocols;
import io.netty.buffer.ByteBuf;
import org.onosproject.lisp.msg.exceptions.LispWriterException;
import org.onosproject.lisp.msg.types.LispAfiAddress;
/**
* A generic LISP locator used for both location and referral purposes.
*/
public interface LispGenericLocator {
/**
* Obtains priority value.
*
* @return priority value
*/
byte getPriority();
/**
* Obtains weight value.
*
* @return weight value
*/
byte getWeight();
/**
* Obtains multi-cast priority value.
*
* @return multi-cast priority value
*/
byte getMulticastPriority();
/**
* Obtains multi-cast weight value.
*
* @return multi-cast weight value
*/
byte getMulticastWeight();
/**
* Obtains local locator flag.
*
* @return local locator flag
*/
boolean isLocalLocator();
/**
* Obtains RLOC probed flag.
*
* @return RLOC probed flag
*/
boolean isRlocProbed();
/**
* Obtains routed flag.
*
* @return routed flag
*/
boolean isRouted();
/**
* Obtains locator AFI.
*
* @return locator AFI
*/
LispAfiAddress getLocatorAfi();
/**
* Writes LISP message object into communication channel.
*
* @param byteBuf byte buffer
* @throws LispWriterException on error
*/
void writeTo(ByteBuf byteBuf) throws LispWriterException;
/**
* A builder of LISP generic locator.
*
* @param <T> sub-builder type
*/
interface GenericLocatorBuilder<T> {
/**
* Sets priority value.
*
* @param priority priority
* @return parameterized object
*/
T withPriority(byte priority);
/**
* Sets weight value.
*
* @param weight weight
* @return parameterized object
*/
T withWeight(byte weight);
/**
* Sets multi-cast priority value.
*
* @param priority priority
* @return parameterized object
*/
T withMulticastPriority(byte priority);
/**
* Sets multi-cast weight value.
*
* @param weight weight
* @return parameterized object
*/
T withMulticastWeight(byte weight);
/**
* Sets local locator flag.
*
* @param localLocator local locator flag
* @return parameterized object
*/
T withLocalLocator(boolean localLocator);
/**
* Sets RLOC probed flag.
*
* @param rlocProbed RLOC probed flag
* @return parameterized object
*/
T withRlocProbed(boolean rlocProbed);
/**
* Sets routed flag.
*
* @param routed routed flag
* @return parameterized object
*/
T withRouted(boolean routed);
/**
* Sets locator AFI.
*
* @param locatorAfi locator AFI
* @return parameterized object
*/
T withLocatorAfi(LispAfiAddress locatorAfi);
}
}
| apache-2.0 |
estatio/isis | core/metamodel/src/test/java/org/apache/isis/core/metamodel/adapter/oid/RootOidTest_create.java | 2846 | /*
* 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.isis.core.metamodel.adapter.oid;
import org.junit.Test;
import org.apache.isis.core.metamodel.spec.ObjectSpecId;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
public class RootOidTest_create {
@Test
public void create() throws Exception {
ObjectSpecId objectSpecId = ObjectSpecId.of("CUS");
RootOid oid = RootOid.create(objectSpecId, "123");
assertThat(oid.getObjectSpecId(), is(objectSpecId));
assertThat(oid.getIdentifier(), is("123"));
assertThat(oid.getVersion(), is(nullValue()));
assertThat(oid.isTransient(), is(false));
}
@Test
public void createTransient() throws Exception {
ObjectSpecId objectSpecId = ObjectSpecId.of("CUS");
RootOid oid = RootOid.createTransient(objectSpecId, "123");
assertThat(oid.getObjectSpecId(), is(objectSpecId));
assertThat(oid.getIdentifier(), is("123"));
assertThat(oid.getVersion(), is(nullValue()));
assertThat(oid.isTransient(), is(true));
}
@Test
public void createWithVersion() throws Exception {
ObjectSpecId objectSpecId = ObjectSpecId.of("CUS");
RootOid oid = RootOid.create(objectSpecId, "123", 456L);
assertThat(oid.getObjectSpecId(), is(objectSpecId));
assertThat(oid.getIdentifier(), is("123"));
assertThat(oid.getVersion().getSequence(), is(456L));
assertThat(oid.isTransient(), is(false));
}
@Test
public void createTransientNoVersion() throws Exception {
ObjectSpecId objectSpecId = ObjectSpecId.of("CUS");
RootOid oid = RootOid.createTransient(objectSpecId, "123");
assertThat(oid.getObjectSpecId(), is(objectSpecId));
assertThat(oid.getIdentifier(), is("123"));
assertThat(oid.getVersion(), is(nullValue()));
assertThat(oid.isTransient(), is(true));
}
}
| apache-2.0 |
robertwb/incubator-beam | sdks/java/io/kinesis/src/test/java/org/apache/beam/sdk/io/kinesis/ShardReadersPoolTest.java | 14746 | /*
* 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.beam.sdk.io.kinesis;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Stopwatch;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
/** Tests {@link ShardReadersPool}. */
@RunWith(MockitoJUnitRunner.Silent.class)
public class ShardReadersPoolTest {
private static final int TIMEOUT_IN_MILLIS = (int) TimeUnit.SECONDS.toMillis(10);
@Mock private ShardRecordsIterator firstIterator, secondIterator, thirdIterator, fourthIterator;
@Mock private ShardCheckpoint firstCheckpoint, secondCheckpoint;
@Mock private SimplifiedKinesisClient kinesis;
@Mock private KinesisRecord a, b, c, d;
@Mock private WatermarkPolicyFactory watermarkPolicyFactory;
@Mock private RateLimitPolicyFactory rateLimitPolicyFactory;
@Mock private RateLimitPolicy customRateLimitPolicy;
private ShardReadersPool shardReadersPool;
private final Instant now = Instant.now();
@Before
public void setUp() throws TransientKinesisException {
when(a.getShardId()).thenReturn("shard1");
when(b.getShardId()).thenReturn("shard1");
when(c.getShardId()).thenReturn("shard2");
when(d.getShardId()).thenReturn("shard2");
when(firstCheckpoint.getShardId()).thenReturn("shard1");
when(firstCheckpoint.getStreamName()).thenReturn("testStream");
when(secondCheckpoint.getShardId()).thenReturn("shard2");
when(firstIterator.getShardId()).thenReturn("shard1");
when(firstIterator.getStreamName()).thenReturn("testStream");
when(firstIterator.getCheckpoint()).thenReturn(firstCheckpoint);
when(secondIterator.getShardId()).thenReturn("shard2");
when(secondIterator.getCheckpoint()).thenReturn(secondCheckpoint);
when(thirdIterator.getShardId()).thenReturn("shard3");
when(fourthIterator.getShardId()).thenReturn("shard4");
WatermarkPolicy watermarkPolicy =
WatermarkPolicyFactory.withArrivalTimePolicy().createWatermarkPolicy();
RateLimitPolicy rateLimitPolicy = RateLimitPolicyFactory.withoutLimiter().getRateLimitPolicy();
KinesisReaderCheckpoint checkpoint =
new KinesisReaderCheckpoint(ImmutableList.of(firstCheckpoint, secondCheckpoint));
shardReadersPool =
Mockito.spy(
new ShardReadersPool(
kinesis, checkpoint, watermarkPolicyFactory, rateLimitPolicyFactory, 100));
when(watermarkPolicyFactory.createWatermarkPolicy()).thenReturn(watermarkPolicy);
when(rateLimitPolicyFactory.getRateLimitPolicy()).thenReturn(rateLimitPolicy);
doReturn(firstIterator).when(shardReadersPool).createShardIterator(kinesis, firstCheckpoint);
doReturn(secondIterator).when(shardReadersPool).createShardIterator(kinesis, secondCheckpoint);
}
@After
public void clean() {
shardReadersPool.stop();
}
@Test
public void shouldReturnAllRecords()
throws TransientKinesisException, KinesisShardClosedException {
when(firstIterator.readNextBatch())
.thenReturn(Collections.emptyList())
.thenReturn(ImmutableList.of(a, b))
.thenReturn(Collections.emptyList());
when(secondIterator.readNextBatch())
.thenReturn(singletonList(c))
.thenReturn(singletonList(d))
.thenReturn(Collections.emptyList());
shardReadersPool.start();
List<KinesisRecord> fetchedRecords = new ArrayList<>();
while (fetchedRecords.size() < 4) {
CustomOptional<KinesisRecord> nextRecord = shardReadersPool.nextRecord();
if (nextRecord.isPresent()) {
fetchedRecords.add(nextRecord.get());
}
}
assertThat(fetchedRecords).containsExactlyInAnyOrder(a, b, c, d);
assertThat(shardReadersPool.getRecordsQueue().remainingCapacity()).isEqualTo(100 * 2);
}
@Test
public void shouldReturnAbsentOptionalWhenNoRecords()
throws TransientKinesisException, KinesisShardClosedException {
when(firstIterator.readNextBatch()).thenReturn(Collections.emptyList());
when(secondIterator.readNextBatch()).thenReturn(Collections.emptyList());
shardReadersPool.start();
CustomOptional<KinesisRecord> nextRecord = shardReadersPool.nextRecord();
assertThat(nextRecord.isPresent()).isFalse();
}
@Test
public void shouldCheckpointReadRecords()
throws TransientKinesisException, KinesisShardClosedException {
when(firstIterator.readNextBatch())
.thenReturn(ImmutableList.of(a, b))
.thenReturn(Collections.emptyList());
when(secondIterator.readNextBatch())
.thenReturn(singletonList(c))
.thenReturn(singletonList(d))
.thenReturn(Collections.emptyList());
shardReadersPool.start();
int recordsFound = 0;
while (recordsFound < 4) {
CustomOptional<KinesisRecord> nextRecord = shardReadersPool.nextRecord();
if (nextRecord.isPresent()) {
recordsFound++;
KinesisRecord kinesisRecord = nextRecord.get();
if ("shard1".equals(kinesisRecord.getShardId())) {
verify(firstIterator).ackRecord(kinesisRecord);
} else {
verify(secondIterator).ackRecord(kinesisRecord);
}
}
}
}
@Test
public void shouldInterruptKinesisReadingAndStopShortly()
throws TransientKinesisException, KinesisShardClosedException {
when(firstIterator.readNextBatch())
.thenAnswer(
(Answer<List<KinesisRecord>>)
invocation -> {
Thread.sleep(TIMEOUT_IN_MILLIS / 2);
return Collections.emptyList();
});
shardReadersPool.start();
Stopwatch stopwatch = Stopwatch.createStarted();
shardReadersPool.stop();
assertThat(stopwatch.elapsed(TimeUnit.MILLISECONDS)).isLessThan(TIMEOUT_IN_MILLIS);
}
@Test
public void shouldInterruptPuttingRecordsToQueueAndStopShortly()
throws TransientKinesisException, KinesisShardClosedException {
when(firstIterator.readNextBatch()).thenReturn(ImmutableList.of(a, b, c));
KinesisReaderCheckpoint checkpoint =
new KinesisReaderCheckpoint(ImmutableList.of(firstCheckpoint, secondCheckpoint));
WatermarkPolicyFactory watermarkPolicyFactory = WatermarkPolicyFactory.withArrivalTimePolicy();
RateLimitPolicyFactory rateLimitPolicyFactory = RateLimitPolicyFactory.withoutLimiter();
ShardReadersPool shardReadersPool =
new ShardReadersPool(
kinesis, checkpoint, watermarkPolicyFactory, rateLimitPolicyFactory, 2);
shardReadersPool.start();
Stopwatch stopwatch = Stopwatch.createStarted();
shardReadersPool.stop();
assertThat(stopwatch.elapsed(TimeUnit.MILLISECONDS)).isLessThan(TIMEOUT_IN_MILLIS);
}
@Test
public void shouldStopReadingShardAfterReceivingShardClosedException() throws Exception {
when(firstIterator.readNextBatch()).thenThrow(KinesisShardClosedException.class);
when(firstIterator.findSuccessiveShardRecordIterators()).thenReturn(Collections.emptyList());
shardReadersPool.start();
verify(firstIterator, timeout(TIMEOUT_IN_MILLIS).times(1)).readNextBatch();
verify(secondIterator, timeout(TIMEOUT_IN_MILLIS).atLeast(2)).readNextBatch();
}
@Test
public void shouldStartReadingSuccessiveShardsAfterReceivingShardClosedException()
throws Exception {
when(firstIterator.readNextBatch()).thenThrow(KinesisShardClosedException.class);
when(firstIterator.findSuccessiveShardRecordIterators())
.thenReturn(ImmutableList.of(thirdIterator, fourthIterator));
shardReadersPool.start();
verify(thirdIterator, timeout(TIMEOUT_IN_MILLIS).atLeast(2)).readNextBatch();
verify(fourthIterator, timeout(TIMEOUT_IN_MILLIS).atLeast(2)).readNextBatch();
}
@Test
public void shouldStopReadersPoolWhenLastShardReaderStopped() throws Exception {
when(firstIterator.readNextBatch()).thenThrow(KinesisShardClosedException.class);
when(firstIterator.findSuccessiveShardRecordIterators()).thenReturn(Collections.emptyList());
shardReadersPool.start();
verify(firstIterator, timeout(TIMEOUT_IN_MILLIS).times(1)).readNextBatch();
}
@Test
public void shouldStopReadersPoolAlsoWhenExceptionsOccurDuringStopping() throws Exception {
when(firstIterator.readNextBatch()).thenThrow(KinesisShardClosedException.class);
when(firstIterator.findSuccessiveShardRecordIterators())
.thenThrow(TransientKinesisException.class)
.thenReturn(Collections.emptyList());
shardReadersPool.start();
verify(firstIterator, timeout(TIMEOUT_IN_MILLIS).times(2)).readNextBatch();
}
@Test
public void shouldReturnAbsentOptionalWhenStartedWithNoIterators() throws Exception {
KinesisReaderCheckpoint checkpoint = new KinesisReaderCheckpoint(Collections.emptyList());
WatermarkPolicyFactory watermarkPolicyFactory = WatermarkPolicyFactory.withArrivalTimePolicy();
RateLimitPolicyFactory rateLimitPolicyFactory = RateLimitPolicyFactory.withoutLimiter();
shardReadersPool =
Mockito.spy(
new ShardReadersPool(
kinesis,
checkpoint,
watermarkPolicyFactory,
rateLimitPolicyFactory,
ShardReadersPool.DEFAULT_CAPACITY_PER_SHARD));
doReturn(firstIterator)
.when(shardReadersPool)
.createShardIterator(eq(kinesis), any(ShardCheckpoint.class));
shardReadersPool.start();
assertThat(shardReadersPool.nextRecord()).isEqualTo(CustomOptional.absent());
}
@Test
public void shouldForgetClosedShardIterator() throws Exception {
when(firstIterator.readNextBatch()).thenThrow(KinesisShardClosedException.class);
List<ShardRecordsIterator> emptyList = Collections.emptyList();
when(firstIterator.findSuccessiveShardRecordIterators()).thenReturn(emptyList);
shardReadersPool.start();
verify(shardReadersPool)
.startReadingShards(ImmutableList.of(firstIterator, secondIterator), "testStream");
verify(shardReadersPool, timeout(TIMEOUT_IN_MILLIS))
.startReadingShards(emptyList, "testStream");
KinesisReaderCheckpoint checkpointMark = shardReadersPool.getCheckpointMark();
assertThat(checkpointMark.iterator())
.extracting("shardId", String.class)
.containsOnly("shard2")
.doesNotContain("shard1");
}
@Test
public void shouldReturnTheLeastWatermarkOfAllShards() throws TransientKinesisException {
Instant threeMin = now.minus(Duration.standardMinutes(3));
Instant twoMin = now.minus(Duration.standardMinutes(2));
when(firstIterator.getShardWatermark()).thenReturn(threeMin).thenReturn(now);
when(secondIterator.getShardWatermark()).thenReturn(twoMin);
shardReadersPool.start();
assertThat(shardReadersPool.getWatermark()).isEqualTo(threeMin);
assertThat(shardReadersPool.getWatermark()).isEqualTo(twoMin);
verify(firstIterator, times(2)).getShardWatermark();
verify(secondIterator, times(2)).getShardWatermark();
}
@Test
public void shouldReturnTheOldestFromLatestRecordTimestampOfAllShards()
throws TransientKinesisException {
Instant threeMin = now.minus(Duration.standardMinutes(3));
Instant twoMin = now.minus(Duration.standardMinutes(2));
when(firstIterator.getLatestRecordTimestamp()).thenReturn(threeMin).thenReturn(now);
when(secondIterator.getLatestRecordTimestamp()).thenReturn(twoMin);
shardReadersPool.start();
assertThat(shardReadersPool.getLatestRecordTimestamp()).isEqualTo(threeMin);
assertThat(shardReadersPool.getLatestRecordTimestamp()).isEqualTo(twoMin);
verify(firstIterator, times(2)).getLatestRecordTimestamp();
verify(secondIterator, times(2)).getLatestRecordTimestamp();
}
@Test
public void shouldCallRateLimitPolicy()
throws TransientKinesisException, KinesisShardClosedException, InterruptedException {
KinesisClientThrottledException e = new KinesisClientThrottledException("", null);
when(firstIterator.readNextBatch())
.thenThrow(e)
.thenReturn(ImmutableList.of(a, b))
.thenReturn(Collections.emptyList());
when(secondIterator.readNextBatch())
.thenReturn(singletonList(c))
.thenReturn(singletonList(d))
.thenReturn(Collections.emptyList());
when(rateLimitPolicyFactory.getRateLimitPolicy()).thenReturn(customRateLimitPolicy);
shardReadersPool.start();
List<KinesisRecord> fetchedRecords = new ArrayList<>();
while (fetchedRecords.size() < 4) {
CustomOptional<KinesisRecord> nextRecord = shardReadersPool.nextRecord();
if (nextRecord.isPresent()) {
fetchedRecords.add(nextRecord.get());
}
}
verify(customRateLimitPolicy, timeout(TIMEOUT_IN_MILLIS)).onThrottle(same(e));
verify(customRateLimitPolicy, timeout(TIMEOUT_IN_MILLIS)).onSuccess(eq(ImmutableList.of(a, b)));
verify(customRateLimitPolicy, timeout(TIMEOUT_IN_MILLIS)).onSuccess(eq(singletonList(c)));
verify(customRateLimitPolicy, timeout(TIMEOUT_IN_MILLIS)).onSuccess(eq(singletonList(d)));
verify(customRateLimitPolicy, timeout(TIMEOUT_IN_MILLIS).atLeastOnce())
.onSuccess(eq(Collections.emptyList()));
}
}
| apache-2.0 |
genericDataCompany/hsandbox | common/mahout-distribution-0.7-hadoop1/core/src/main/java/org/apache/mahout/classifier/sgd/CrossFoldLearner.java | 9258 | /**
* 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.mahout.classifier.sgd;
import com.google.common.collect.Lists;
import org.apache.hadoop.io.Writable;
import org.apache.mahout.classifier.AbstractVectorClassifier;
import org.apache.mahout.classifier.OnlineLearner;
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.Vector;
import org.apache.mahout.math.function.DoubleDoubleFunction;
import org.apache.mahout.math.function.Functions;
import org.apache.mahout.math.stats.GlobalOnlineAuc;
import org.apache.mahout.math.stats.OnlineAuc;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.List;
/**
* Does cross-fold validation of log-likelihood and AUC on several online logistic regression
* models. Each record is passed to all but one of the models for training and to the remaining
* model for evaluation. In order to maintain proper segregation between the different folds across
* training data iterations, data should either be passed to this learner in the same order each
* time the training data is traversed or a tracking key such as the file offset of the training
* record should be passed with each training example.
*/
public class CrossFoldLearner extends AbstractVectorClassifier implements OnlineLearner, Writable {
private int record;
// minimum score to be used for computing log likelihood
private static final double MIN_SCORE = 1.0e-50;
private OnlineAuc auc = new GlobalOnlineAuc();
private double logLikelihood;
private final List<OnlineLogisticRegression> models = Lists.newArrayList();
// lambda, learningRate, perTermOffset, perTermExponent
private double[] parameters = new double[4];
private int numFeatures;
private PriorFunction prior;
private double percentCorrect;
private int windowSize = Integer.MAX_VALUE;
public CrossFoldLearner() {
}
public CrossFoldLearner(int folds, int numCategories, int numFeatures, PriorFunction prior) {
this.numFeatures = numFeatures;
this.prior = prior;
for (int i = 0; i < folds; i++) {
OnlineLogisticRegression model = new OnlineLogisticRegression(numCategories, numFeatures, prior);
model.alpha(1).stepOffset(0).decayExponent(0);
models.add(model);
}
}
// -------- builder-like configuration methods
public CrossFoldLearner lambda(double v) {
for (OnlineLogisticRegression model : models) {
model.lambda(v);
}
return this;
}
public CrossFoldLearner learningRate(double x) {
for (OnlineLogisticRegression model : models) {
model.learningRate(x);
}
return this;
}
public CrossFoldLearner stepOffset(int x) {
for (OnlineLogisticRegression model : models) {
model.stepOffset(x);
}
return this;
}
public CrossFoldLearner decayExponent(double x) {
for (OnlineLogisticRegression model : models) {
model.decayExponent(x);
}
return this;
}
public CrossFoldLearner alpha(double alpha) {
for (OnlineLogisticRegression model : models) {
model.alpha(alpha);
}
return this;
}
// -------- training methods
@Override
public void train(int actual, Vector instance) {
train(record, null, actual, instance);
}
@Override
public void train(long trackingKey, int actual, Vector instance) {
train(trackingKey, null, actual, instance);
}
@Override
public void train(long trackingKey, String groupKey, int actual, Vector instance) {
record++;
int k = 0;
for (OnlineLogisticRegression model : models) {
if (k == trackingKey % models.size()) {
Vector v = model.classifyFull(instance);
double score = Math.max(v.get(actual), MIN_SCORE);
logLikelihood += (Math.log(score) - logLikelihood) / Math.min(record, windowSize);
int correct = v.maxValueIndex() == actual ? 1 : 0;
percentCorrect += (correct - percentCorrect) / Math.min(record, windowSize);
if (numCategories() == 2) {
auc.addSample(actual, groupKey, v.get(1));
}
} else {
model.train(trackingKey, groupKey, actual, instance);
}
k++;
}
}
@Override
public void close() {
for (OnlineLogisticRegression m : models) {
m.close();
}
}
public void resetLineCounter() {
record = 0;
}
public boolean validModel() {
boolean r = true;
for (OnlineLogisticRegression model : models) {
r &= model.validModel();
}
return r;
}
// -------- classification methods
@Override
public Vector classify(Vector instance) {
Vector r = new DenseVector(numCategories() - 1);
DoubleDoubleFunction scale = Functions.plusMult(1.0 / models.size());
for (OnlineLogisticRegression model : models) {
r.assign(model.classify(instance), scale);
}
return r;
}
@Override
public Vector classifyNoLink(Vector instance) {
Vector r = new DenseVector(numCategories() - 1);
DoubleDoubleFunction scale = Functions.plusMult(1.0 / models.size());
for (OnlineLogisticRegression model : models) {
r.assign(model.classifyNoLink(instance), scale);
}
return r;
}
@Override
public double classifyScalar(Vector instance) {
double r = 0;
int n = 0;
for (OnlineLogisticRegression model : models) {
n++;
r += model.classifyScalar(instance);
}
return r / n;
}
// -------- status reporting methods
@Override
public int numCategories() {
return models.get(0).numCategories();
}
public double auc() {
return auc.auc();
}
public double logLikelihood() {
return logLikelihood;
}
public double percentCorrect() {
return percentCorrect;
}
// -------- evolutionary optimization
public CrossFoldLearner copy() {
CrossFoldLearner r = new CrossFoldLearner(models.size(), numCategories(), numFeatures, prior);
r.models.clear();
for (OnlineLogisticRegression model : models) {
model.close();
OnlineLogisticRegression newModel =
new OnlineLogisticRegression(model.numCategories(), model.numFeatures(), model.prior);
newModel.copyFrom(model);
r.models.add(newModel);
}
return r;
}
public int getRecord() {
return record;
}
public void setRecord(int record) {
this.record = record;
}
public OnlineAuc getAucEvaluator() {
return auc;
}
public void setAucEvaluator(OnlineAuc auc) {
this.auc = auc;
}
public double getLogLikelihood() {
return logLikelihood;
}
public void setLogLikelihood(double logLikelihood) {
this.logLikelihood = logLikelihood;
}
public List<OnlineLogisticRegression> getModels() {
return models;
}
public void addModel(OnlineLogisticRegression model) {
models.add(model);
}
public double[] getParameters() {
return parameters;
}
public void setParameters(double[] parameters) {
this.parameters = parameters;
}
public int getNumFeatures() {
return numFeatures;
}
public void setNumFeatures(int numFeatures) {
this.numFeatures = numFeatures;
}
public void setWindowSize(int windowSize) {
this.windowSize = windowSize;
auc.setWindowSize(windowSize);
}
public PriorFunction getPrior() {
return prior;
}
public void setPrior(PriorFunction prior) {
this.prior = prior;
}
@Override
public void write(DataOutput out) throws IOException {
out.writeInt(record);
PolymorphicWritable.write(out, auc);
out.writeDouble(logLikelihood);
out.writeInt(models.size());
for (OnlineLogisticRegression model : models) {
model.write(out);
}
for (double x : parameters) {
out.writeDouble(x);
}
out.writeInt(numFeatures);
PolymorphicWritable.write(out, prior);
out.writeDouble(percentCorrect);
out.writeInt(windowSize);
}
@Override
public void readFields(DataInput in) throws IOException {
record = in.readInt();
auc = PolymorphicWritable.read(in, OnlineAuc.class);
logLikelihood = in.readDouble();
int n = in.readInt();
for (int i = 0; i < n; i++) {
OnlineLogisticRegression olr = new OnlineLogisticRegression();
olr.readFields(in);
models.add(olr);
}
parameters = new double[4];
for (int i = 0; i < 4; i++) {
parameters[i] = in.readDouble();
}
numFeatures = in.readInt();
prior = PolymorphicWritable.read(in, PriorFunction.class);
percentCorrect = in.readDouble();
windowSize = in.readInt();
}
}
| apache-2.0 |
gladyscarrizales/manifoldcf | framework/pull-agent/src/main/java/org/apache/manifoldcf/authorities/system/AuthCheckThread.java | 6548 | /* $Id: AuthCheckThread.java 988245 2010-08-23 18:39:35Z kwright $ */
/**
* 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.manifoldcf.authorities.system;
import org.apache.manifoldcf.core.interfaces.*;
import org.apache.manifoldcf.agents.interfaces.*;
import org.apache.manifoldcf.authorities.interfaces.*;
import org.apache.manifoldcf.authorities.system.Logging;
import java.util.*;
import java.lang.reflect.*;
/** This thread periodically calls the cleanup method in all connected repository connectors. The ostensible purpose
* is to allow the connectors to shutdown idle connections etc.
*/
public class AuthCheckThread extends Thread
{
public static final String _rcsid = "@(#)$Id: AuthCheckThread.java 988245 2010-08-23 18:39:35Z kwright $";
// Local data
protected RequestQueue<AuthRequest> requestQueue;
/** Constructor.
*/
public AuthCheckThread(String id, RequestQueue<AuthRequest> requestQueue)
throws ManifoldCFException
{
super();
this.requestQueue = requestQueue;
setName("Auth check thread "+id);
setDaemon(true);
}
public void run()
{
// Create a thread context object.
IThreadContext threadContext = ThreadContextFactory.make();
try
{
// Create an authority connection pool object.
IAuthorityConnectorPool authorityConnectorPool = AuthorityConnectorPoolFactory.make(threadContext);
// Loop
while (true)
{
// Do another try/catch around everything in the loop
try
{
if (Thread.currentThread().isInterrupted())
throw new ManifoldCFException("Interrupted",ManifoldCFException.INTERRUPTED);
// Wait for a request.
AuthRequest theRequest = requestQueue.getRequest();
// Try to fill the request before going back to sleep.
if (Logging.authorityService.isDebugEnabled())
{
Logging.authorityService.debug(" Calling connector class '"+theRequest.getAuthorityConnection().getClassName()+"'");
}
AuthorizationResponse response = null;
Throwable exception = null;
// Grab an authorization response only if there's a user
if (theRequest.getUserID() != null)
{
try
{
IAuthorityConnector connector = authorityConnectorPool.grab(theRequest.getAuthorityConnection());
// If this is null, we MUST treat this as an "unauthorized" condition!!
// We signal that by setting the exception value.
try
{
if (connector == null)
exception = new ManifoldCFException("Authority connector "+theRequest.getAuthorityConnection().getClassName()+" is not registered.");
else
{
// Get the acl for the user
try
{
response = connector.getAuthorizationResponse(theRequest.getUserID());
}
catch (ManifoldCFException e)
{
if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)
throw e;
Logging.authorityService.warn("Authority error: "+e.getMessage(),e);
response = AuthorityConnectorFactory.getDefaultAuthorizationResponse(threadContext,theRequest.getAuthorityConnection().getClassName(),theRequest.getUserID());
}
}
}
finally
{
authorityConnectorPool.release(theRequest.getAuthorityConnection(),connector);
}
}
catch (ManifoldCFException e)
{
if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)
throw e;
Logging.authorityService.warn("Authority connection exception: "+e.getMessage(),e);
response = AuthorityConnectorFactory.getDefaultAuthorizationResponse(threadContext,theRequest.getAuthorityConnection().getClassName(),theRequest.getUserID());
if (response == null)
exception = e;
}
catch (Throwable e)
{
Logging.authorityService.warn("Authority connection error: "+e.getMessage(),e);
response = AuthorityConnectorFactory.getDefaultAuthorizationResponse(threadContext,theRequest.getAuthorityConnection().getClassName(),theRequest.getUserID());
if (response == null)
exception = e;
}
}
// The request is complete
theRequest.completeRequest(response,exception);
// Repeat, and only go to sleep if there are no more requests.
}
catch (ManifoldCFException e)
{
if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)
break;
// Log it, but keep the thread alive
Logging.authorityService.error("Exception tossed: "+e.getMessage(),e);
if (e.getErrorCode() == ManifoldCFException.SETUP_ERROR)
{
// Shut the whole system down!
System.exit(1);
}
}
catch (InterruptedException e)
{
// We're supposed to quit
break;
}
catch (Throwable e)
{
// A more severe error - but stay alive
Logging.authorityService.fatal("Error tossed: "+e.getMessage(),e);
}
}
}
catch (ManifoldCFException e)
{
// Severe error on initialization
System.err.println("Authority service auth check thread could not start - shutting down");
Logging.authorityService.fatal("AuthCheckThread initialization error tossed: "+e.getMessage(),e);
System.exit(-300);
}
}
}
| apache-2.0 |
robin13/elasticsearch | x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/saml/sp/SamlServiceProviderIndex.java | 15291 | /*
* 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.idp.saml.sp;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.OriginSettingClient;
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateListener;
import org.elasticsearch.cluster.metadata.IndexAbstraction;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.ValidationException;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.util.CachedSupplier;
import org.elasticsearch.common.xcontent.LoggingDeprecationHandler;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.gateway.GatewayService;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.get.GetResult;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.xpack.core.ClientHelper;
import org.elasticsearch.xpack.core.template.TemplateUtils;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Arrays;
import java.util.Objects;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* This class provides utility methods to read/write {@link SamlServiceProviderDocument} to an Elasticsearch index.
*/
public class SamlServiceProviderIndex implements Closeable {
private final Logger logger = LogManager.getLogger();
private final Client client;
private final ClusterService clusterService;
private final ClusterStateListener clusterStateListener;
private volatile boolean aliasExists;
private volatile boolean templateInstalled;
public static final String ALIAS_NAME = "saml-service-provider";
public static final String INDEX_NAME = "saml-service-provider-v1";
static final String TEMPLATE_NAME = ALIAS_NAME;
private static final String TEMPLATE_RESOURCE = "/org/elasticsearch/xpack/idp/saml-service-provider-template.json";
private static final String TEMPLATE_META_VERSION_KEY = "idp-version";
private static final String TEMPLATE_VERSION_SUBSTITUTE = "idp.template.version";
public static final class DocumentVersion {
public final String id;
public final long primaryTerm;
public final long seqNo;
public DocumentVersion(String id, long primaryTerm, long seqNo) {
this.id = id;
this.primaryTerm = primaryTerm;
this.seqNo = seqNo;
}
public DocumentVersion(GetResponse get) {
this(get.getId(), get.getPrimaryTerm(), get.getSeqNo());
}
public DocumentVersion(GetResult get) {
this(get.getId(), get.getPrimaryTerm(), get.getSeqNo());
}
public DocumentVersion(SearchHit hit) {
this(hit.getId(), hit.getPrimaryTerm(), hit.getSeqNo());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final DocumentVersion that = (DocumentVersion) o;
return Objects.equals(this.id, that.id) && primaryTerm == that.primaryTerm &&
seqNo == that.seqNo;
}
@Override
public int hashCode() {
return Objects.hash(id, primaryTerm, seqNo);
}
}
public static final class DocumentSupplier {
public final DocumentVersion version;
public final Supplier<SamlServiceProviderDocument> document;
public DocumentSupplier(DocumentVersion version, Supplier<SamlServiceProviderDocument> document) {
this.version = version;
this.document = new CachedSupplier<>(document);
}
public SamlServiceProviderDocument getDocument() {
return document.get();
}
}
public SamlServiceProviderIndex(Client client, ClusterService clusterService) {
this.client = new OriginSettingClient(client, ClientHelper.IDP_ORIGIN);
this.clusterService = clusterService;
this.clusterStateListener = this::clusterChanged;
clusterService.addListener(clusterStateListener);
}
private void clusterChanged(ClusterChangedEvent clusterChangedEvent) {
final ClusterState state = clusterChangedEvent.state();
installTemplateIfRequired(state);
checkForAliasStateChange(state);
}
private void installTemplateIfRequired(ClusterState state) {
if (templateInstalled) {
return;
}
if (state.blocks().hasGlobalBlock(GatewayService.STATE_NOT_RECOVERED_BLOCK)) {
return;
}
if (isTemplateUpToDate(state)) {
templateInstalled = true;
return;
}
if (state.nodes().isLocalNodeElectedMaster() == false) {
return;
}
installIndexTemplate(ActionListener.wrap(
installed -> {
templateInstalled = true;
if (installed) {
logger.debug("Template [{}] has been updated", TEMPLATE_NAME);
} else {
logger.debug("Template [{}] appears to be up to date", TEMPLATE_NAME);
}
}, e -> logger.warn(new ParameterizedMessage("Failed to install template [{}]", TEMPLATE_NAME), e)
));
}
private void checkForAliasStateChange(ClusterState state) {
final IndexAbstraction aliasInfo = state.getMetadata().getIndicesLookup().get(ALIAS_NAME);
final boolean previousState = aliasExists;
this.aliasExists = aliasInfo != null;
if (aliasExists != previousState) {
logChangedAliasState(aliasInfo);
}
}
@Override
public void close() {
logger.debug("Closing ... removing cluster state listener");
clusterService.removeListener(clusterStateListener);
}
private void logChangedAliasState(IndexAbstraction aliasInfo) {
if (aliasInfo == null) {
logger.warn("service provider index/alias [{}] no longer exists", ALIAS_NAME);
} else if (aliasInfo.getType() != IndexAbstraction.Type.ALIAS) {
logger.warn("service provider index [{}] does not exist as an alias, but it should be", ALIAS_NAME);
} else if (aliasInfo.getIndices().size() != 1) {
logger.warn("service provider alias [{}] refers to multiple indices [{}] - this is unexpected and is likely to cause problems",
ALIAS_NAME, Strings.collectionToCommaDelimitedString(aliasInfo.getIndices()));
} else {
logger.info("service provider alias [{}] refers to [{}]", ALIAS_NAME, aliasInfo.getIndices().get(0).getIndex());
}
}
public void installIndexTemplate(ActionListener<Boolean> listener) {
final ClusterState state = clusterService.state();
if (isTemplateUpToDate(state)) {
listener.onResponse(false);
return;
}
final String template = TemplateUtils.loadTemplate(TEMPLATE_RESOURCE, Version.CURRENT.toString(), TEMPLATE_VERSION_SUBSTITUTE);
final PutIndexTemplateRequest request = new PutIndexTemplateRequest(TEMPLATE_NAME).source(template, XContentType.JSON);
client.admin().indices().putTemplate(request, ActionListener.wrap(response -> {
logger.info("Installed template [{}]", TEMPLATE_NAME);
listener.onResponse(true);
}, listener::onFailure));
}
private boolean isTemplateUpToDate(ClusterState state) {
return TemplateUtils.checkTemplateExistsAndIsUpToDate(TEMPLATE_NAME, TEMPLATE_META_VERSION_KEY, state, logger);
}
public void deleteDocument(DocumentVersion version, WriteRequest.RefreshPolicy refreshPolicy, ActionListener<DeleteResponse> listener) {
final DeleteRequest request = new DeleteRequest(aliasExists ? ALIAS_NAME : INDEX_NAME)
.id(version.id)
.setIfSeqNo(version.seqNo)
.setIfPrimaryTerm(version.primaryTerm)
.setRefreshPolicy(refreshPolicy);
client.delete(request, ActionListener.wrap(response -> {
logger.debug("Deleted service provider document [{}] ({})", version.id, response.getResult());
listener.onResponse(response);
}, listener::onFailure));
}
public void writeDocument(SamlServiceProviderDocument document, DocWriteRequest.OpType opType,
WriteRequest.RefreshPolicy refreshPolicy, ActionListener<DocWriteResponse> listener) {
final ValidationException exception = document.validate();
if (exception != null) {
listener.onFailure(exception);
return;
}
if (templateInstalled) {
_writeDocument(document, opType, refreshPolicy, listener);
} else {
installIndexTemplate(ActionListener.wrap(installed ->
_writeDocument(document, opType, refreshPolicy, listener), listener::onFailure));
}
}
private void _writeDocument(SamlServiceProviderDocument document, DocWriteRequest.OpType opType,
WriteRequest.RefreshPolicy refreshPolicy, ActionListener<DocWriteResponse> listener) {
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
XContentBuilder xContentBuilder = new XContentBuilder(XContentType.JSON.xContent(), out)) {
document.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS);
// Due to the lack of "alias templates" (at the current time), we cannot write to the alias if it doesn't exist yet
// - that would cause the alias to be created as a concrete index, which is not what we want.
// So, until we know that the alias exists we have to write to the expected index name instead.
final IndexRequest request = new IndexRequest(aliasExists ? ALIAS_NAME : INDEX_NAME)
.opType(opType)
.source(xContentBuilder)
.id(document.docId)
.setRefreshPolicy(refreshPolicy);
client.index(request, ActionListener.wrap(response -> {
logger.debug("Wrote service provider [{}][{}] as document [{}] ({})",
document.name, document.entityId, response.getId(), response.getResult());
listener.onResponse(response);
}, listener::onFailure));
} catch (IOException e) {
listener.onFailure(e);
}
}
public void readDocument(String documentId, ActionListener<DocumentSupplier> listener) {
final GetRequest request = new GetRequest(ALIAS_NAME, documentId);
client.get(request, ActionListener.wrap(response -> {
if (response.isExists()) {
listener.onResponse(
new DocumentSupplier(new DocumentVersion(response), () -> toDocument(documentId, response.getSourceAsBytesRef()))
);
} else {
listener.onResponse(null);
}
}, listener::onFailure));
}
public void findByEntityId(String entityId, ActionListener<Set<DocumentSupplier>> listener) {
final QueryBuilder query = QueryBuilders.termQuery(SamlServiceProviderDocument.Fields.ENTITY_ID.getPreferredName(), entityId);
findDocuments(query, listener);
}
public void findAll(ActionListener<Set<DocumentSupplier>> listener) {
final QueryBuilder query = QueryBuilders.matchAllQuery();
findDocuments(query, listener);
}
public void refresh(ActionListener<Void> listener) {
client.admin().indices().refresh(new RefreshRequest(ALIAS_NAME), ActionListener.wrap(
response -> listener.onResponse(null), listener::onFailure));
}
private void findDocuments(QueryBuilder query, ActionListener<Set<DocumentSupplier>> listener) {
logger.trace("Searching [{}] for [{}]", ALIAS_NAME, query);
final SearchRequest request = client.prepareSearch(ALIAS_NAME)
.setQuery(query)
.setSize(1000)
.setFetchSource(true)
.request();
client.search(request, ActionListener.wrap(response -> {
if (logger.isTraceEnabled()) {
logger.trace("Search hits: [{}] [{}]", response.getHits().getTotalHits(), Arrays.toString(response.getHits().getHits()));
}
final Set<DocumentSupplier> docs = Stream.of(response.getHits().getHits())
.map(hit -> new DocumentSupplier(new DocumentVersion(hit), () -> toDocument(hit.getId(), hit.getSourceRef())))
.collect(Collectors.toUnmodifiableSet());
listener.onResponse(docs);
}, ex -> {
if (ex instanceof IndexNotFoundException) {
listener.onResponse(Set.of());
} else {
listener.onFailure(ex);
}
}));
}
private SamlServiceProviderDocument toDocument(String documentId, BytesReference source) {
try (StreamInput in = source.streamInput();
XContentParser parser = XContentType.JSON.xContent().createParser(
NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, in)) {
return SamlServiceProviderDocument.fromXContent(documentId, parser);
} catch (IOException e) {
throw new UncheckedIOException("failed to parse document [" + documentId + "]", e);
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "{alias=" + ALIAS_NAME + " [" + (aliasExists ? "exists" : "not-found") + "]}";
}
}
| apache-2.0 |
ibinti/intellij-community | platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ModuleLibraryOrderEntryImpl.java | 5958 | /*
* Copyright 2000-2015 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.roots.impl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.impl.libraries.LibraryEx;
import com.intellij.openapi.roots.impl.libraries.LibraryImpl;
import com.intellij.openapi.roots.impl.libraries.LibraryTableImplUtil;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.PersistentLibraryKind;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager;
import com.intellij.util.PathUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.serialization.java.JpsJavaModelSerializerExtension;
import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer;
/**
* Library entry for module ("in-place") libraries
* @author dsl
*/
public class ModuleLibraryOrderEntryImpl extends LibraryOrderEntryBaseImpl implements LibraryOrderEntry, ClonableOrderEntry, WritableOrderEntry {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.roots.impl.LibraryOrderEntryImpl");
private final Library myLibrary;
@NonNls public static final String ENTRY_TYPE = JpsModuleRootModelSerializer.MODULE_LIBRARY_TYPE;
private boolean myExported;
@NonNls public static final String EXPORTED_ATTR = JpsJavaModelSerializerExtension.EXPORTED_ATTRIBUTE;
//cloning
private ModuleLibraryOrderEntryImpl(@NotNull Library library, @NotNull RootModelImpl rootModel, boolean isExported, @NotNull DependencyScope scope) {
super(rootModel, ProjectRootManagerImpl.getInstanceImpl(rootModel.getProject()));
myLibrary = ((LibraryImpl)library).cloneLibrary(getRootModel());
doinit();
myExported = isExported;
myScope = scope;
}
ModuleLibraryOrderEntryImpl(String name, final PersistentLibraryKind kind, @NotNull RootModelImpl rootModel,
@NotNull ProjectRootManagerImpl projectRootManager, ProjectModelExternalSource externalSource) {
super(rootModel, projectRootManager);
myLibrary = LibraryTableImplUtil.createModuleLevelLibrary(name, kind, getRootModel(), externalSource);
doinit();
}
ModuleLibraryOrderEntryImpl(@NotNull Element element, @NotNull RootModelImpl rootModel, @NotNull ProjectRootManagerImpl projectRootManager) throws InvalidDataException {
super(rootModel, projectRootManager);
LOG.assertTrue(ENTRY_TYPE.equals(element.getAttributeValue(OrderEntryFactory.ORDER_ENTRY_TYPE_ATTR)));
myExported = element.getAttributeValue(EXPORTED_ATTR) != null;
myScope = DependencyScope.readExternal(element);
myLibrary = LibraryTableImplUtil.loadLibrary(element, getRootModel());
doinit();
}
private void doinit() {
Disposer.register(this, myLibrary);
init();
}
@Override
protected RootProvider getRootProvider() {
return myLibrary.getRootProvider();
}
@Override
public Library getLibrary() {
return myLibrary;
}
@Override
public boolean isModuleLevel() {
return true;
}
@Override
public String getLibraryName() {
return myLibrary.getName();
}
@Override
public String getLibraryLevel() {
return LibraryTableImplUtil.MODULE_LEVEL;
}
@NotNull
@Override
public String getPresentableName() {
final String name = myLibrary.getName();
if (name != null) {
return name;
}
else {
if (myLibrary instanceof LibraryEx && ((LibraryEx)myLibrary).isDisposed()) {
return "<unknown>";
}
final String[] urls = myLibrary.getUrls(OrderRootType.CLASSES);
if (urls.length > 0) {
String url = urls[0];
return PathUtil.toPresentableUrl(url);
}
else {
return ProjectBundle.message("library.empty.library.item");
}
}
}
@Override
public boolean isValid() {
return !isDisposed() && myLibrary != null;
}
@Override
public <R> R accept(RootPolicy<R> policy, R initialValue) {
return policy.visitLibraryOrderEntry(this, initialValue);
}
@Override
public boolean isSynthetic() {
return true;
}
@Override
public OrderEntry cloneEntry(RootModelImpl rootModel,
ProjectRootManagerImpl projectRootManager,
VirtualFilePointerManager filePointerManager) {
return new ModuleLibraryOrderEntryImpl(myLibrary, rootModel, myExported, myScope);
}
@Override
public void writeExternal(Element rootElement) throws WriteExternalException {
final Element element = OrderEntryFactory.createOrderEntryElement(ENTRY_TYPE);
if (myExported) {
element.setAttribute(EXPORTED_ATTR, "");
}
myScope.writeExternal(element);
myLibrary.writeExternal(element);
rootElement.addContent(element);
}
@Override
public boolean isExported() {
return myExported;
}
@Override
public void setExported(boolean value) {
myExported = value;
}
@Override
@NotNull
public DependencyScope getScope() {
return myScope;
}
@Override
public void setScope(@NotNull DependencyScope scope) {
myScope = scope;
}
}
| apache-2.0 |
treasure-data/presto | presto-plugin-toolkit/src/main/java/io/prestosql/plugin/base/classloader/ClassLoaderSafeNodePartitioningProvider.java | 3606 | /*
* 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 io.prestosql.plugin.base.classloader;
import io.prestosql.spi.classloader.ThreadContextClassLoader;
import io.prestosql.spi.connector.BucketFunction;
import io.prestosql.spi.connector.ConnectorBucketNodeMap;
import io.prestosql.spi.connector.ConnectorNodePartitioningProvider;
import io.prestosql.spi.connector.ConnectorPartitionHandle;
import io.prestosql.spi.connector.ConnectorPartitioningHandle;
import io.prestosql.spi.connector.ConnectorSession;
import io.prestosql.spi.connector.ConnectorSplit;
import io.prestosql.spi.connector.ConnectorTransactionHandle;
import io.prestosql.spi.type.Type;
import javax.inject.Inject;
import java.util.List;
import java.util.function.ToIntFunction;
import static java.util.Objects.requireNonNull;
public final class ClassLoaderSafeNodePartitioningProvider
implements ConnectorNodePartitioningProvider
{
private final ConnectorNodePartitioningProvider delegate;
private final ClassLoader classLoader;
@Inject
public ClassLoaderSafeNodePartitioningProvider(@ForClassLoaderSafe ConnectorNodePartitioningProvider delegate, ClassLoader classLoader)
{
this.delegate = requireNonNull(delegate, "delegate is null");
this.classLoader = requireNonNull(classLoader, "classLoader is null");
}
@Override
public BucketFunction getBucketFunction(
ConnectorTransactionHandle transactionHandle,
ConnectorSession session,
ConnectorPartitioningHandle partitioningHandle,
List<Type> partitionChannelTypes,
int bucketCount)
{
try (ThreadContextClassLoader ignored = new ThreadContextClassLoader(classLoader)) {
return delegate.getBucketFunction(transactionHandle, session, partitioningHandle, partitionChannelTypes, bucketCount);
}
}
@Override
public List<ConnectorPartitionHandle> listPartitionHandles(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorPartitioningHandle partitioningHandle)
{
try (ThreadContextClassLoader ignored = new ThreadContextClassLoader(classLoader)) {
return delegate.listPartitionHandles(transactionHandle, session, partitioningHandle);
}
}
@Override
public ConnectorBucketNodeMap getBucketNodeMap(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorPartitioningHandle partitioningHandle)
{
try (ThreadContextClassLoader ignored = new ThreadContextClassLoader(classLoader)) {
return delegate.getBucketNodeMap(transactionHandle, session, partitioningHandle);
}
}
@Override
public ToIntFunction<ConnectorSplit> getSplitBucketFunction(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorPartitioningHandle partitioningHandle)
{
try (ThreadContextClassLoader ignored = new ThreadContextClassLoader(classLoader)) {
return delegate.getSplitBucketFunction(transactionHandle, session, partitioningHandle);
}
}
}
| apache-2.0 |
Victor-Y-Fadeev/qreal | qrtranslations/fr/qrgui_pluginsManager_fr.ts | 833 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="fr_FR">
<context>
<name>qReal::InterpreterEditorManager</name>
<message>
<location filename="../../qrgui/plugins/pluginManager/interpreterEditorManager.cpp" line="924"/>
<source>Deleted</source>
<translation>Supprimé</translation>
</message>
<message>
<location filename="../../qrgui/plugins/pluginManager/interpreterEditorManager.cpp" line="930"/>
<source>Existed</source>
<translation>En cours d'utilisation</translation>
</message>
<message>
<location filename="../../qrgui/plugins/pluginManager/interpreterEditorManager.cpp" line="932"/>
<source>Renamed to </source>
<translation>A été renomme en </translation>
</message>
</context>
</TS>
| apache-2.0 |
xmaruto/mcord | xos/synchronizers/base/steps/sync_controller_sites.py | 2981 | import os
import base64
from django.db.models import F, Q
from xos.config import Config
from synchronizers.openstack.openstacksyncstep import OpenStackSyncStep
from core.models.site import *
from synchronizers.base.syncstep import *
from synchronizers.base.ansible import *
from xos.logger import observer_logger as logger
import json
class SyncControllerSites(OpenStackSyncStep):
requested_interval=0
provides=[Site]
observes=ControllerSite
playbook = 'sync_controller_sites.yaml'
def fetch_pending(self, deleted=False):
lobjs = ControllerSite.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False),Q(controller__isnull=False))
return lobjs
def map_sync_inputs(self, controller_site):
tenant_fields = {'endpoint':controller_site.controller.auth_url,
'endpoint_v3': controller_site.controller.auth_url_v3,
'domain': controller_site.controller.domain,
'admin_user': controller_site.controller.admin_user,
'admin_password': controller_site.controller.admin_password,
'admin_tenant': controller_site.controller.admin_tenant,
'ansible_tag': '%s@%s'%(controller_site.site.login_base,controller_site.controller.name), # name of ansible playbook
'tenant': controller_site.site.login_base,
'tenant_description': controller_site.site.name}
return tenant_fields
def map_sync_outputs(self, controller_site, res):
controller_site.tenant_id = res[0]['id']
controller_site.backend_status = '1 - OK'
controller_site.save()
def delete_record(self, controller_site):
controller_register = json.loads(controller_site.controller.backend_register)
if (controller_register.get('disabled',False)):
raise InnocuousException('Controller %s is disabled'%controller_site.controller.name)
if controller_site.tenant_id:
driver = self.driver.admin_driver(controller=controller_site.controller)
driver.delete_tenant(controller_site.tenant_id)
"""
Ansible does not support tenant deletion yet
import pdb
pdb.set_trace()
template = os_template_env.get_template('delete_controller_sites.yaml')
tenant_fields = {'endpoint':controller_site.controller.auth_url,
'admin_user': controller_site.controller.admin_user,
'admin_password': controller_site.controller.admin_password,
'admin_tenant': 'admin',
'ansible_tag': 'controller_sites/%s@%s'%(controller_site.controller_site.site.login_base,controller_site.controller_site.deployment.name), # name of ansible playbook
'tenant': controller_site.controller_site.site.login_base,
'delete': True}
rendered = template.render(tenant_fields)
res = run_template('sync_controller_sites.yaml', tenant_fields)
if (len(res)!=1):
raise Exception('Could not assign roles for user %s'%tenant_fields['tenant'])
"""
| apache-2.0 |
popravich/typescript | tests/Fidelity/test262/suite/ch15/15.2/15.2.4/15.2.4.7/S15.2.4.7_A2_T1.js | 883 | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* When the propertyIsEnumerable method is called with argument V, the following steps are taken:
* i) Let O be this object
* ii) Call ToString(V)
* iii) If O doesn't have a property with the name given by Result(ii), return false
* iv) If the property has the DontEnum attribute, return false
* v) Return true
*
* @path ch15/15.2/15.2.4/15.2.4.7/S15.2.4.7_A2_T1.js
* @description Checking the type of Object.prototype.propertyIsEnumerable and the returned result
*/
//CHECK#1
if (typeof Object.prototype.propertyIsEnumerable !== "function") {
$ERROR('#1: hasOwnProperty method is defined');
}
//CHECK#2
if (Object.prototype.propertyIsEnumerable("propertyIsEnumerable")) {
$ERROR('#2: hasOwnProperty method works properly');
}
//
| apache-2.0 |
trejkaz/derby | java/testing/org/apache/derbyTesting/functionTests/tests/lang/MiscErrorsTest.java | 3706 | /*
Derby - Class org.apache.derbyTesting.functionTests.tests.lang.MiscErrorsTest
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.derbyTesting.functionTests.tests.lang;
import java.sql.SQLException;
import java.sql.Statement;
import junit.framework.Test;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.TestConfiguration;
/**
* Tests miscellaneous error situations.
*/
public class MiscErrorsTest extends BaseJDBCTestCase {
public MiscErrorsTest(String name) {
super(name);
}
public static Test suite() {
return TestConfiguration.defaultSuite(MiscErrorsTest.class);
}
public void testLexicalError() {
String sql = "select @#^%*&! from swearwords";
assertCompileError("42X02", sql);
}
/**
* Try to create duplicate table.
*/
public void testDuplicateTableCreation() throws SQLException {
String sql = "create table a (one int)";
Statement st = createStatement();
st.executeUpdate(sql);
sql = "create table a (one int, two int)";
assertStatementError("X0Y32", st, sql);
sql = "create table a (one int)";
assertStatementError("X0Y32", st, sql);
dropTable("a");
sql = "create table a (one int, two int, three int)";
st.executeUpdate(sql);
sql = "insert into a values (1,2,3)";
assertEquals(1, st.executeUpdate(sql));
sql = "select * from a";
JDBC.assertUnorderedResultSet(st.executeQuery(sql),
new String[][] { { "1", "2", "3", } });
dropTable("a");
}
/**
* See that statements that fail at parse or bind time
* are not put in the statement cache.
*/
public void testStatementCache() throws SQLException {
String sql = "values 1";
Statement st = createStatement();
JDBC.assertSingleValueResultSet(st.executeQuery(sql), "1");
//a stronger test.
sql = "select SQL_TEXT from syscs_diag.statement_cache"
+ " where CAST(SQL_TEXT AS LONG VARCHAR)" + " LIKE '%values 1%'";
JDBC.assertUnorderedResultSet(st.executeQuery(sql),
new String[][] {
{ sql }, { "values 1" }, }
);
sql = "select SQL_TEXT from syscs_diag.statement_cache"
+ " where CAST(SQL_TEXT AS LONG VARCHAR)" + " LIKE '%932432%'";
JDBC.assertSingleValueResultSet(st.executeQuery(sql), sql);
sql = "VALUES FRED932432";
assertCompileError("42X04", sql);
sql = "SELECT * FROM BILL932432";
assertCompileError("42X05", sql);
sql = "SELECT 932432";
assertCompileError("42X01", sql);
sql = "select SQL_TEXT from syscs_diag.statement_cache"
+ " where CAST(SQL_TEXT AS LONG VARCHAR)" + " LIKE '%932432%'";
JDBC.assertSingleValueResultSet(st.executeQuery(sql), sql);
}
}
| apache-2.0 |
davidzchen/bazel | src/test/java/com/google/devtools/build/android/r8/CompatDxTest.java | 8162 | // Copyright 2020 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.android.r8;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Test for CompatDx. */
@RunWith(JUnit4.class)
public class CompatDxTest {
private static final String EXAMPLE_JAR_FILE_1 = System.getProperty("CompatDxTests.arithmetic");
private static final String EXAMPLE_JAR_FILE_2 = System.getProperty("CompatDxTests.barray");
private static final String NO_LOCALS = "--no-locals";
private static final String NO_POSITIONS = "--positions=none";
private static final String MULTIDEX = "--multi-dex";
private static final String NUM_THREADS_5 = "--num-threads=5";
@Rule public TemporaryFolder temp = new TemporaryFolder();
@Test
public void noFilesTest() throws IOException {
runDexer("--no-files");
}
@Test
public void noOutputTest() throws IOException {
runDexerWithoutOutput(NO_POSITIONS, NO_LOCALS, MULTIDEX, EXAMPLE_JAR_FILE_1);
}
@Test
public void singleJarInputFile() throws IOException {
runDexer(NO_POSITIONS, NO_LOCALS, MULTIDEX, EXAMPLE_JAR_FILE_1);
}
@Test
public void multipleJarInputFiles() throws IOException {
runDexer(NO_POSITIONS, NO_LOCALS, MULTIDEX, EXAMPLE_JAR_FILE_1, EXAMPLE_JAR_FILE_2);
}
@Test
public void outputZipFile() throws IOException {
runDexerWithOutput("foo.dex.zip", NO_POSITIONS, NO_LOCALS, MULTIDEX, EXAMPLE_JAR_FILE_1);
}
@Test
public void useMultipleThreads() throws IOException {
runDexer(NUM_THREADS_5, NO_POSITIONS, NO_LOCALS, EXAMPLE_JAR_FILE_1);
}
@Test
public void withPositions() throws IOException {
runDexer(NO_LOCALS, MULTIDEX, EXAMPLE_JAR_FILE_1);
}
@Test
public void withLocals() throws IOException {
runDexer(NO_POSITIONS, MULTIDEX, EXAMPLE_JAR_FILE_1);
}
@Test
public void withoutMultidex() throws IOException {
runDexer(NO_POSITIONS, NO_LOCALS, EXAMPLE_JAR_FILE_1);
}
@Test
public void writeToNamedDexFile() throws IOException {
runDexerWithOutput("named-output.dex", EXAMPLE_JAR_FILE_1);
}
@Test
public void keepClassesSingleDexTest() throws IOException {
runDexerWithOutput("out.zip", "--keep-classes", EXAMPLE_JAR_FILE_1);
}
@Test
public void keepClassesMultiDexTest() throws IOException {
runDexerWithOutput("out.zip", "--keep-classes", "--multi-dex", EXAMPLE_JAR_FILE_1);
}
@Test
public void ignoreDexInArchiveTest() throws IOException {
// Create a JAR with both a .class and a .dex file (the .dex file is just empty).
Path jarWithClassesAndDex = temp.newFile("test.jar").toPath();
Files.copy(
Paths.get(EXAMPLE_JAR_FILE_1), jarWithClassesAndDex, StandardCopyOption.REPLACE_EXISTING);
jarWithClassesAndDex.toFile().setWritable(true);
URI uri = URI.create("jar:" + jarWithClassesAndDex.toUri());
try (FileSystem fileSystem =
FileSystems.newFileSystem(uri, ImmutableMap.of("create", "true"))) {
Path dexFile = fileSystem.getPath("classes.dex");
Files.newOutputStream(dexFile, StandardOpenOption.CREATE).close();
}
// Only test this with CompatDx, as dx does not like the empty .dex file.
List<String> d8Args =
ImmutableList.of("--output=" + temp.newFolder("out"), jarWithClassesAndDex.toString());
CompatDx.main(d8Args.toArray(new String[0]));
}
private void runDexer(String... args) throws IOException {
runDexerWithOutput("", args);
}
private void runDexerWithoutOutput(String... args) throws IOException {
runDexerWithOutput(null, args);
}
private Path getOutputD8() {
return temp.getRoot().toPath().resolve("d8-out");
}
private Path getOutputDX() {
return temp.getRoot().toPath().resolve("dx-out");
}
private void runDexerWithOutput(String out, String... args) throws IOException {
Path d8Out = null;
Path dxOut = null;
if (out != null) {
Path baseD8 = getOutputD8();
Path baseDX = getOutputDX();
Files.createDirectory(baseD8);
Files.createDirectory(baseDX);
d8Out = baseD8.resolve(out);
dxOut = baseDX.resolve(out);
assertThat(dxOut.toString()).isNotEqualTo(d8Out.toString());
}
List<String> d8Args = new ArrayList<>();
d8Args.add("--dex");
if (d8Out != null) {
d8Args.add("--output=" + d8Out);
}
Collections.addAll(d8Args, args);
System.out.println("running: d8 " + Joiner.on(" ").join(d8Args));
CompatDx.main(d8Args.toArray(new String[0]));
List<String> dxArgs = new ArrayList<>();
dxArgs.add("--dex");
if (dxOut != null) {
dxArgs.add("--output=" + dxOut);
}
Collections.addAll(dxArgs, args);
System.out.println("running: dx " + Joiner.on(" ").join(dxArgs));
com.android.dx.command.Main.main(dxArgs.toArray(new String[0]));
if (out == null) {
// Can't check output if explicitly not writing any.
return;
}
List<Path> d8Files;
try (Stream<Path> d8FilesStream =
Files.list(Files.isDirectory(d8Out) ? d8Out : d8Out.getParent())) {
d8Files = d8FilesStream.sorted().collect(toList());
}
List<Path> dxFiles;
try (Stream<Path> dxFilesStream =
Files.list(Files.isDirectory(dxOut) ? dxOut : dxOut.getParent())) {
dxFiles = dxFilesStream.sorted().collect(toList());
}
assertWithMessage("Out file names differ")
.that(
Joiner.on(System.lineSeparator())
.join(d8Files.stream().map(Path::getFileName).iterator()))
.isEqualTo(
Joiner.on(System.lineSeparator())
.join(dxFiles.stream().map(Path::getFileName).iterator()));
for (int i = 0; i < d8Files.size(); i++) {
if (FileUtils.isArchive(d8Files.get(i))) {
compareArchiveFiles(d8Files.get(i), dxFiles.get(i));
}
}
}
private static void compareArchiveFiles(Path d8File, Path dxFile) throws IOException {
ZipFile d8Zip = new ZipFile(d8File.toFile(), UTF_8);
ZipFile dxZip = new ZipFile(dxFile.toFile(), UTF_8);
// TODO(zerny): This should test resource containment too once supported.
Set<String> d8Content = d8Zip.stream().map(ZipEntry::getName).collect(toSet());
Set<String> dxContent =
dxZip.stream()
.map(ZipEntry::getName)
.filter(
name ->
name.endsWith(FileUtils.DEX_EXTENSION)
|| name.endsWith(FileUtils.CLASS_EXTENSION))
.collect(toSet());
assertWithMessage("Expected dx and d8 output to contain same DEX anf class file entries")
.that(d8Content)
.containsExactlyElementsIn(dxContent);
}
}
| apache-2.0 |
LucasOromi/Ratrace.NET | Custom.WebClient.Trading/bin/Debug/Angular.import.debug.js | 163 | //! Angular.import.debug.js
//
(function($) {
Type.registerNamespace('AngularApi');
})(jQuery);
//! This script was generated using Script# v0.7.4.0
| apache-2.0 |
adhikasp/nightlyBlog | www/public/modules/system/lang/nl/validation.php | 5406 | <?php
return array(
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| such as the size rules. Feel free to tweak each of these messages.
|
*/
"accepted" => "Het veld :attribute moet worden geaccepteerd.",
"active_url" => "De URL van :attribute is ongeldig.",
"after" => "De datum van :attribute moet een waarde zijn na :date.",
"alpha" => "Het veld :attribute mag enkel uit letters bestaan.",
"alpha_dash" => "Het veld :attribute mag enkel uit letters, cijfers en streepjes bestaan.",
"alpha_num" => "Het veld :attribute mag enkel uit letters en cijfers bestaan.",
"array" => "Het veld :attribute moet een array zijn.",
"before" => "De datum van :attribute moet een waarde zijn voor :date.",
"between" => array(
"numeric" => "Het veld :attribute moet een waarde hebben tussen :min en :max.",
"file" => "De bestandsgrootte van :attribute moet tussen :min en :max kilobytes zijn.",
"string" => "Het aantal tekens van :attribute moet tussen de :min en :max zijn.",
"array" => "Het veld :attribute moet tussen de :min en :max objecten bevatten.",
),
"confirmed" => "De bevestiging van :attribute is ongeldig.",
"date" => "De datum van :attribute is ongeldig.",
"date_format" => "Het veld :attribute komt niet overeen met het formaat :format.",
"different" => "De velden :attribute en :other moeten verschillend zijn.",
"digits" => "Het veld :attribute moet uit :digits cijfers bestaan.",
"digits_between" => "Het veld :attribute moet tussen :min en :max tekens lang zijn.",
"email" => "Het e-mailadres van :attribute is ongeldig.",
"exists" => "De waarde van :attribute is ongeldig.",
"image" => "De afbeelding van :attribute is ongeldig.",
"in" => "De gekozen waarde van :attribute is ongeldig.",
"integer" => "De waarde van :attribute moet uit een heel getal bestaan.",
"ip" => "Het IP-adres van :attribute is ongeldig.",
"max" => array(
"numeric" => "De waarde van :attribute mag niet hoger zijn dan :max.",
"file" => "De bestandsgrootte van :attribute mag niet groter zijn dan :max kilobytes.",
"string" => "Het aantal tekens van :attribute mag niet groter zijn dan :max tekens.",
"array" => "Het veld :attribute mag niet meer dan :max objecten bevatten.",
),
"mimes" => "Het bestand van :attribute mag enkel zijn van het type: :values.",
"min" => array(
"numeric" => "De waarde van :attribute minimaal :min zijn.",
"file" => "De bestandsgrootte van :attribute moet minimaal :min kilobytes zijn.",
"string" => "Het aantal tekens van :attribute moet minimaal :min zijn.",
"array" => "Het veld :attribute moet minimaal :min objecten bevatten.",
),
"not_in" => "De gekozen waarde van :attribute is ongeldig.",
"numeric" => "De waarde van :attribute moet numeriek zijn.",
"regex" => "De opbouw van :attribute is ongeldig.",
"required" => "Het veld :attribute is verplicht.",
"required_if" => "Het veld :attribute is verplicht wanneer :other is :value.",
"required_with" => "Het veld :attribute is verplicht wanneer :values is gekozen.",
"required_without" => "Het veld :attribute is verplicht wanneer :values niet is gekozen.",
"same" => "De velden :attribute en :other moeten overeen komen.",
"size" => array(
"numeric" => "De waarde van :attribute moet exact :size zijn.",
"file" => "De bestandsgrootte van :attribute moet exact :size kilobytes zijn.",
"string" => "Het aantal tekens van :attribute moet exact :size zijn.",
"array" => "Het veld :attribute moet exact :size objecten bevatten.",
),
"unique" => "Het veld :attribute is al toegewezen.",
"url" => "De URL van :attribute is ongeldig.",
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => array(),
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => array(),
);
| artistic-2.0 |
BenjaminHCCarr/homebrew-cask | Casks/displaperture.rb | 221 | cask "displaperture" do
version :latest
sha256 :no_check
url "https://manytricks.com/download/displaperture"
name "Displaperture"
homepage "https://manytricks.com/displaperture/"
app "Displaperture.app"
end
| bsd-2-clause |
edporras/homebrew-core | Formula/hdf5.rb | 2821 | class Hdf5 < Formula
desc "File format designed to store large amounts of data"
homepage "https://www.hdfgroup.org/HDF5"
url "https://support.hdfgroup.org/ftp/HDF5/releases/hdf5-1.12/hdf5-1.12.0/src/hdf5-1.12.0.tar.bz2"
sha256 "97906268640a6e9ce0cde703d5a71c9ac3092eded729591279bf2e3ca9765f61"
bottle do
cellar :any
sha256 "6c68f33613e960a0c9efec780d07d34c2ce9c0795d723af7027ee6b88219abbf" => :catalina
sha256 "77cf2db15c52c69da64ca5535eb03e44ec2bd953cbb2166996580739db467241" => :mojave
sha256 "88a4048d5d26ccea95574726fd874d8b69409301ed6a0f36d9c695168b3fc144" => :high_sierra
end
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "gcc" # for gfortran
depends_on "szip"
uses_from_macos "zlib"
def install
inreplace %w[c++/src/h5c++.in fortran/src/h5fc.in bin/h5cc.in],
"${libdir}/libhdf5.settings",
"#{pkgshare}/libhdf5.settings"
inreplace "src/Makefile.am",
"settingsdir=$(libdir)",
"settingsdir=#{pkgshare}"
system "autoreconf", "-fiv"
args = %W[
--disable-dependency-tracking
--disable-silent-rules
--prefix=#{prefix}
--with-szlib=#{Formula["szip"].opt_prefix}
--enable-build-mode=production
--enable-fortran
--enable-cxx
]
system "./configure", *args
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <stdio.h>
#include "hdf5.h"
int main()
{
printf("%d.%d.%d\\n", H5_VERS_MAJOR, H5_VERS_MINOR, H5_VERS_RELEASE);
return 0;
}
EOS
system "#{bin}/h5cc", "test.c"
assert_equal version.to_s, shell_output("./a.out").chomp
(testpath/"test.f90").write <<~EOS
use hdf5
integer(hid_t) :: f, dspace, dset
integer(hsize_t), dimension(2) :: dims = [2, 2]
integer :: error = 0, major, minor, rel
call h5open_f (error)
if (error /= 0) call abort
call h5fcreate_f ("test.h5", H5F_ACC_TRUNC_F, f, error)
if (error /= 0) call abort
call h5screate_simple_f (2, dims, dspace, error)
if (error /= 0) call abort
call h5dcreate_f (f, "data", H5T_NATIVE_INTEGER, dspace, dset, error)
if (error /= 0) call abort
call h5dclose_f (dset, error)
if (error /= 0) call abort
call h5sclose_f (dspace, error)
if (error /= 0) call abort
call h5fclose_f (f, error)
if (error /= 0) call abort
call h5close_f (error)
if (error /= 0) call abort
CALL h5get_libversion_f (major, minor, rel, error)
if (error /= 0) call abort
write (*,"(I0,'.',I0,'.',I0)") major, minor, rel
end
EOS
system "#{bin}/h5fc", "test.f90"
assert_equal version.to_s, shell_output("./a.out").chomp
end
end
| bsd-2-clause |
sebastienros/jint | Jint.Tests.Test262/test/language/statements/class/dstr-async-gen-meth-ary-ptrn-elem-ary-rest-iter.js | 2597 | // This file was procedurally generated from the following sources:
// - src/dstr-binding/ary-ptrn-elem-ary-rest-iter.case
// - src/dstr-binding/default/cls-decl-async-gen-meth.template
/*---
description: BindingElement with array binding pattern and initializer is not used (class expression method)
esid: sec-class-definitions-runtime-semantics-evaluation
features: [async-iteration]
flags: [generated, async]
info: |
ClassDeclaration : class BindingIdentifier ClassTail
1. Let className be StringValue of BindingIdentifier.
2. Let value be the result of ClassDefinitionEvaluation of ClassTail with
argument className.
[...]
14.5.14 Runtime Semantics: ClassDefinitionEvaluation
21. For each ClassElement m in order from methods
a. If IsStatic of m is false, then
i. Let status be the result of performing
PropertyDefinitionEvaluation for m with arguments proto and
false.
[...]
Runtime Semantics: PropertyDefinitionEvaluation
AsyncGeneratorMethod :
async [no LineTerminator here] * PropertyName ( UniqueFormalParameters )
{ AsyncGeneratorBody }
1. Let propKey be the result of evaluating PropertyName.
2. ReturnIfAbrupt(propKey).
3. If the function code for this AsyncGeneratorMethod is strict mode code, let strict be true.
Otherwise let strict be false.
4. Let scope be the running execution context's LexicalEnvironment.
5. Let closure be ! AsyncGeneratorFunctionCreate(Method, UniqueFormalParameters,
AsyncGeneratorBody, scope, strict).
[...]
13.3.3.6 Runtime Semantics: IteratorBindingInitialization
BindingElement : BindingPatternInitializer opt
1. If iteratorRecord.[[done]] is false, then
a. Let next be IteratorStep(iteratorRecord.[[iterator]]).
[...]
e. Else,
i. Let v be IteratorValue(next).
[...]
4. Return the result of performing BindingInitialization of BindingPattern
with v and environment as the arguments.
---*/
var values = [2, 1, 3];
var initCount = 0;
var callCount = 0;
class C {
async *method([[...x] = function() { initCount += 1; }()]) {
assert(Array.isArray(x));
assert.sameValue(x[0], 2);
assert.sameValue(x[1], 1);
assert.sameValue(x[2], 3);
assert.sameValue(x.length, 3);
assert.notSameValue(x, values);
assert.sameValue(initCount, 0);
callCount = callCount + 1;
}
};
new C().method([values]).next().then(() => {
assert.sameValue(callCount, 1, 'invoked exactly once');
}).then($DONE, $DONE);
| bsd-2-clause |
ondrejvelisek/perun | perun-core/src/main/java/cz/metacentrum/perun/core/impl/AuthzResolverImpl.java | 27180 | package cz.metacentrum.perun.core.impl;
import cz.metacentrum.perun.core.api.ActionType;
import cz.metacentrum.perun.core.api.AttributeDefinition;
import cz.metacentrum.perun.core.api.Facility;
import cz.metacentrum.perun.core.api.Group;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcPerunTemplate;
import org.springframework.jdbc.core.RowMapper;
import cz.metacentrum.perun.core.api.Member;
import cz.metacentrum.perun.core.api.Pair;
import cz.metacentrum.perun.core.api.Perun;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.Resource;
import cz.metacentrum.perun.core.api.Role;
import cz.metacentrum.perun.core.api.SecurityTeam;
import cz.metacentrum.perun.core.api.Service;
import cz.metacentrum.perun.core.api.SpecificUserType;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.Vo;
import cz.metacentrum.perun.core.api.exceptions.AlreadyAdminException;
import cz.metacentrum.perun.core.api.exceptions.GroupNotAdminException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.UserNotAdminException;
import cz.metacentrum.perun.core.api.exceptions.rt.InternalErrorRuntimeException;
import cz.metacentrum.perun.core.implApi.AuthzResolverImplApi;
import java.util.HashSet;
import java.util.Set;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.EmptyResultDataAccessException;
public class AuthzResolverImpl implements AuthzResolverImplApi {
final static Logger log = LoggerFactory.getLogger(FacilitiesManagerImpl.class);
//http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html
private static JdbcPerunTemplate jdbc;
private Perun perun;
private final static Pattern patternForExtractingPerunBean = Pattern.compile("^pb_([a-z_]+)_id$");
public final static String authzRoleMappingSelectQuery = " authz.user_id as authz_user_id, authz.role_id as authz_role_id," +
"authz.authorized_group_id as authz_authorized_group_id, authz.vo_id as pb_vo_id, authz.group_id as pb_group_id, " +
"authz.facility_id as pb_facility_id, authz.member_id as pb_member_id, authz.resource_id as pb_resource_id, " +
"authz.service_id as pb_service_id, authz.service_principal_id as pb_user_id, authz.security_team_id as pb_security_team_id, " +
"authz.sponsored_user_id as pb_sponsored_user_id";
protected static final RowMapper<Role> AUTHZROLE_MAPPER_FOR_ATTRIBUTES = new RowMapper<Role>() {
public Role mapRow(ResultSet rs, int i) throws SQLException {
Role role = Role.valueOf(rs.getString("name").toUpperCase());
return role;
}
};
public static final RowMapper<Pair<Role, Map<String, Set<Integer>>>> AUTHZROLE_MAPPER = new RowMapper<Pair<Role, Map<String, Set<Integer>>>>() {
public Pair<Role, Map<String, Set<Integer>>> mapRow(ResultSet rs, int i) throws SQLException {
try {
Map<String, Set<Integer>> perunBeans = null;
Role role = Role.valueOf(rs.getString("role_name").toUpperCase());
// Iterate through all returned columns and try to extract PerunBean name from the labels
for (int j = rs.getMetaData().getColumnCount(); j > 0; j--) {
Matcher matcher = patternForExtractingPerunBean.matcher(rs.getMetaData().getColumnLabel(j).toLowerCase());
if (matcher.find()) {
String perunBeanName = matcher.group(1);
int id = rs.getInt(j);
if (!rs.wasNull()) {
// We have to make first letters o words uppercase
String className = convertUnderScoreCaseToCamelCase(perunBeanName);
if (perunBeans == null) {
perunBeans = new HashMap<String, Set<Integer>>();
}
if (perunBeans.get(className) == null) {
perunBeans.put(className, new HashSet<Integer>());
}
perunBeans.get(className).add(id);
}
}
}
return new Pair<Role, Map<String, Set<Integer>>>(role, perunBeans);
} catch (Exception e) {
throw new InternalErrorRuntimeException(e);
}
}
};
private static String convertUnderScoreCaseToCamelCase(String name) {
boolean nextIsCapital = true;
StringBuilder nameBuilder = new StringBuilder();
for (char c : name.toCharArray()) {
if (c == '_') {
nextIsCapital = true;
} else {
if (nextIsCapital) {
c = Character.toUpperCase(c);
nextIsCapital = false;
}
nameBuilder.append(c);
}
}
return nameBuilder.toString();
}
public AuthzResolverImpl(DataSource perunPool) {
jdbc = new JdbcPerunTemplate(perunPool);
}
public AuthzRoles getRoles(User user) throws InternalErrorException {
AuthzRoles authzRoles = new AuthzRoles();
if (user != null) {
try {
// Get roles from Authz table
List<Pair<Role, Map<String, Set<Integer>>>> authzRolesPairs = jdbc.query("select " + authzRoleMappingSelectQuery
+ ", roles.name as role_name from authz left join roles on authz.role_id=roles.id where authz.user_id=? or authorized_group_id in "
+ "(select groups.id from groups join groups_members on groups.id=groups_members.group_id join members on "
+ "members.id=groups_members.member_id join users on users.id=members.user_id where users.id=?)", AUTHZROLE_MAPPER, user.getId(), user.getId());
for (Pair<Role, Map<String, Set<Integer>>> pair : authzRolesPairs) {
authzRoles.putAuthzRoles(pair.getLeft(), pair.getRight());
}
// Get service users for user
List<Integer> authzServiceUsers = jdbc.query("select specific_user_users.specific_user_id as id from users, " +
"specific_user_users where users.id=specific_user_users.user_id and specific_user_users.status='0' and users.id=? " +
"and specific_user_users.type=?", Utils.ID_MAPPER ,user.getId(), SpecificUserType.SERVICE.getSpecificUserType());
for (Integer serviceUserId : authzServiceUsers) {
authzRoles.putAuthzRole(Role.SELF, User.class, serviceUserId);
}
// Get members for user
List<Integer> authzMember = jdbc.query("select members.id as id from members where members.user_id=?",
Utils.ID_MAPPER ,user.getId());
for (Integer memberId : authzMember) {
authzRoles.putAuthzRole(Role.SELF, Member.class, memberId);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
return authzRoles;
}
public void initialize() throws InternalErrorException {
if(perun.isPerunReadOnly()) log.debug("Loading authzresolver manager init in readOnly version.");
// Check if all roles defined in class Role exists in the DB
for (Role role: Role.values()) {
try {
if (0 == jdbc.queryForInt("select count(*) from roles where name=?", role.getRoleName())) {
//Skip creating not existing roles for read only Perun
if(perun.isPerunReadOnly()) {
throw new InternalErrorException("One of deafult roles not exists in DB - " + role);
} else {
int newId = Utils.getNewId(jdbc, "roles_id_seq");
jdbc.update("insert into roles (id, name) values (?,?)", newId, role.getRoleName());
}
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
}
public static List<Role> getRolesWhichCanWorkWithAttribute(PerunSession sess, ActionType actionType, AttributeDefinition attrDef) throws InternalErrorException {
String actType = actionType.getActionType().toLowerCase();
try {
return jdbc.query("select distinct roles.name from attributes_authz " +
"join roles on attributes_authz.role_id=roles.id " +
"join action_types on attributes_authz.action_type_id=action_types.id " +
"where attributes_authz.attr_id=? and action_types.action_type=?", AUTHZROLE_MAPPER_FOR_ATTRIBUTES, attrDef.getId(), actType);
} catch (EmptyResultDataAccessException e) {
return new ArrayList<Role>();
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeAllUserAuthz(PerunSession sess, User user) throws InternalErrorException {
try {
jdbc.update("delete from authz where user_id=?", user.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeAllSponsoredUserAuthz(PerunSession sess, User sponsoredUser) throws InternalErrorException {
try {
jdbc.update("delete from authz where sponsored_user_id=?", sponsoredUser.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeAllGroupAuthz(PerunSession sess, Group group) throws InternalErrorException {
try {
jdbc.update("delete from authz where authorized_group_id=?", group.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeAllAuthzForVo(PerunSession sess, Vo vo) throws InternalErrorException {
try {
jdbc.update("delete from authz where vo_id=?", vo.getId());
} catch (RuntimeException err) {
throw new InternalErrorException(err);
}
}
public void removeAllAuthzForGroup(PerunSession sess, Group group) throws InternalErrorException {
try {
jdbc.update("delete from authz where group_id=?", group.getId());
} catch (RuntimeException err) {
throw new InternalErrorException(err);
}
}
public void removeAllAuthzForFacility(PerunSession sess, Facility facility) throws InternalErrorException {
try {
jdbc.update("delete from authz where facility_id=?", facility.getId());
} catch (RuntimeException err) {
throw new InternalErrorException(err);
}
}
public void removeAllAuthzForResource(PerunSession sess, Resource resource) throws InternalErrorException {
try {
jdbc.update("delete from authz where resource_id=?", resource.getId());
} catch (RuntimeException err) {
throw new InternalErrorException(err);
}
}
public void removeAllAuthzForService(PerunSession sess, Service service) throws InternalErrorException {
try {
jdbc.update("delete from authz where service_id=?", service.getId());
} catch (RuntimeException err) {
throw new InternalErrorException(err);
}
}
@Override
public void removeAllAuthzForSecurityTeam(PerunSession sess, SecurityTeam securityTeam) throws InternalErrorException {
try {
jdbc.update("delete from authz where security_team_id=?", securityTeam.getId());
} catch (RuntimeException err) {
throw new InternalErrorException(err);
}
}
public void addAdmin(PerunSession sess, Facility facility, User user) throws InternalErrorException, AlreadyAdminException {
try {
jdbc.update("insert into authz (user_id, role_id, facility_id) values (?, (select id from roles where name=?), ?)", user.getId(), Role.FACILITYADMIN.getRoleName(), facility.getId());
} catch (DataIntegrityViolationException e) {
throw new AlreadyAdminException("User id=" + user.getId() + " is already admin of the facility " + facility, e, user, facility);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void addAdmin(PerunSession sess, Facility facility, Group group) throws InternalErrorException, AlreadyAdminException {
try {
jdbc.update("insert into authz (authorized_group_id, role_id, facility_id) values (?, (select id from roles where name=?), ?)", group.getId(), Role.FACILITYADMIN.getRoleName(), facility.getId());
} catch (DataIntegrityViolationException e) {
throw new AlreadyAdminException("Group id=" + group.getId() + " is already admin of the facility " + facility, e, group, facility);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeAdmin(PerunSession sess, Facility facility, User user) throws InternalErrorException, UserNotAdminException {
try {
if (0 == jdbc.update("delete from authz where user_id=? and facility_id=? and role_id=(select id from roles where name=?)", user.getId(), facility.getId(), Role.FACILITYADMIN.getRoleName())) {
throw new UserNotAdminException("User id=" + user.getId() + " is not admin of the facility " + facility);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeAdmin(PerunSession sess, Facility facility, Group group) throws InternalErrorException, GroupNotAdminException {
try {
if (0 == jdbc.update("delete from authz where authorized_group_id=? and facility_id=? and role_id=(select id from roles where name=?)", group.getId(), facility.getId(), Role.FACILITYADMIN.getRoleName())) {
throw new GroupNotAdminException("Group id=" + group.getId() + " is not admin of the facility " + facility);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void addAdmin(PerunSession sess, User sponsoredUser, User user) throws InternalErrorException, AlreadyAdminException {
try {
jdbc.update("insert into authz (user_id, role_id, sponsored_user_id) values (?, (select id from roles where name=?), ?)", user.getId(), Role.SPONSOR.getRoleName(), sponsoredUser.getId());
} catch (DataIntegrityViolationException e) {
throw new AlreadyAdminException("User id=" + user.getId() + " is already sponsor of the sponsoredUser " + sponsoredUser, e, user, sponsoredUser);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void addAdmin(PerunSession sess, User sponsoredUser, Group group) throws InternalErrorException, AlreadyAdminException {
try {
jdbc.update("insert into authz (authorized_group_id, role_id, sponsored_user_id) values (?, (select id from roles where name=?), ?)", group.getId(), Role.SPONSOR.getRoleName(), sponsoredUser.getId());
} catch (DataIntegrityViolationException e) {
throw new AlreadyAdminException("Group id=" + group.getId() + " is already sponsor of the sponsoredUser " + sponsoredUser, e, group, sponsoredUser);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeAdmin(PerunSession sess, User sponsoredUser, User user) throws InternalErrorException, UserNotAdminException {
try {
if (0 == jdbc.update("delete from authz where user_id=? and sponsored_user_id=? and role_id=(select id from roles where name=?)", user.getId(), sponsoredUser.getId(), Role.SPONSOR.getRoleName())) {
throw new UserNotAdminException("User id=" + user.getId() + " is not sponsor of the sponsored user " + sponsoredUser);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeAdmin(PerunSession sess, User sponsoredUser, Group group) throws InternalErrorException, GroupNotAdminException {
try {
if (0 == jdbc.update("delete from authz where authorized_group_id=? and sponsored_user_id=? and role_id=(select id from roles where name=?)", group.getId(), sponsoredUser.getId(), Role.SPONSOR.getRoleName())) {
throw new GroupNotAdminException("Group id=" + group.getId() + " is not sponsor of the sponsored user " + sponsoredUser);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void addAdmin(PerunSession sess, Group group, User user) throws InternalErrorException, AlreadyAdminException {
try {
// Add GROUPADMIN role + groupId and voId
jdbc.update("insert into authz (user_id, role_id, group_id, vo_id) values (?, (select id from roles where name=?), ?, ?)",
user.getId(), Role.GROUPADMIN.getRoleName(), group.getId(), group.getVoId());
} catch (DataIntegrityViolationException e) {
throw new AlreadyAdminException("User id=" + user.getId() + " is already admin in group " + group, e, user, group);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void addAdmin(PerunSession sess, Group group, Group authorizedGroup) throws InternalErrorException, AlreadyAdminException {
try {
jdbc.update("insert into authz (authorized_group_id, role_id, group_id, vo_id) values (?, (select id from roles where name=?), ?, ?)",
authorizedGroup.getId(), Role.GROUPADMIN.getRoleName(), group.getId(), group.getVoId());
} catch (DataIntegrityViolationException e) {
throw new AlreadyAdminException("Group id=" + authorizedGroup.getId() + " is already group admin in group " + group, e, authorizedGroup, group);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeAdmin(PerunSession sess, Group group, User user) throws InternalErrorException, UserNotAdminException {
try {
if (0 == jdbc.update("delete from authz where user_id=? and group_id=? and role_id=(select id from roles where name=?)",
user.getId(), group.getId(), Role.GROUPADMIN.getRoleName())) {
throw new UserNotAdminException("User id=" + user.getId() + " is not admin of the group " + group);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeAdmin(PerunSession sess, Group group, Group authorizedGroup) throws InternalErrorException, GroupNotAdminException {
try {
if (0 == jdbc.update("delete from authz where authorized_group_id=? and group_id=? and role_id=(select id from roles where name=?)",
authorizedGroup.getId(), group.getId(), Role.GROUPADMIN.getRoleName())) {
throw new GroupNotAdminException("Group id=" + authorizedGroup.getId() + " is not admin of the group " + group);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void addAdmin(PerunSession sess, Vo vo, User user) throws InternalErrorException, AlreadyAdminException {
try {
jdbc.update("insert into authz (user_id, role_id, vo_id) values (?, (select id from roles where name=?), ?)", user.getId(),
Role.VOADMIN.getRoleName(), vo.getId());
} catch (DataIntegrityViolationException e) {
throw new AlreadyAdminException("User id=" + user.getId() + " is already admin in vo " + vo, e, user, vo);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void addAdmin(PerunSession sess, Vo vo, Group group) throws InternalErrorException, AlreadyAdminException {
try {
jdbc.update("insert into authz (role_id, vo_id, authorized_group_id) values ((select id from roles where name=?), ?, ?)",
Role.VOADMIN.getRoleName(), vo.getId(), group.getId());
} catch (DataIntegrityViolationException e) {
throw new AlreadyAdminException("Group id=" + group.getId() + " is already admin in vo " + vo, e, group, vo);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public void addAdmin(PerunSession sess, SecurityTeam securityTeam, User user) throws AlreadyAdminException, InternalErrorException {
try {
jdbc.update("insert into authz (user_id, role_id, security_team_id) values (?, (select id from roles where name=?), ?)", user.getId(),
Role.SECURITYADMIN.getRoleName(), securityTeam.getId());
} catch (DataIntegrityViolationException e) {
throw new AlreadyAdminException("User id=" + user.getId() + " is already admin in securityTeam " + securityTeam, e, user, securityTeam);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public void addAdmin(PerunSession sess, SecurityTeam securityTeam, Group group) throws AlreadyAdminException, InternalErrorException {
try {
jdbc.update("insert into authz (authorized_group_id, role_id, security_team_id) values (?, (select id from roles where name=?), ?)", group.getId(),
Role.SECURITYADMIN.getRoleName(), securityTeam.getId());
} catch (DataIntegrityViolationException e) {
throw new AlreadyAdminException("Group id=" + group.getId() + " is already admin in securityTeam " + securityTeam, e, group, securityTeam);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void addObserver(PerunSession sess, Vo vo, User user) throws InternalErrorException, AlreadyAdminException {
try {
jdbc.update("insert into authz (user_id, role_id, vo_id) values (?, (select id from roles where name=?), ?)", user.getId(),
Role.VOOBSERVER.getRoleName(), vo.getId());
} catch (DataIntegrityViolationException e) {
throw new AlreadyAdminException("User id=" + user.getId() + " is already observer in vo " + vo, e, user, vo);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void addObserver(PerunSession sess, Vo vo, Group group) throws InternalErrorException, AlreadyAdminException {
try {
jdbc.update("insert into authz (role_id, vo_id, authorized_group_id) values ((select id from roles where name=?), ?, ?)",
Role.VOOBSERVER.getRoleName(), vo.getId(), group.getId());
} catch (DataIntegrityViolationException e) {
throw new AlreadyAdminException("Group id=" + group.getId() + " is already observer in vo " + vo, e, group, vo);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void addTopGroupCreator(PerunSession sess, Vo vo, User user) throws InternalErrorException, AlreadyAdminException {
try {
jdbc.update("insert into authz (user_id, role_id, vo_id) values (?, (select id from roles where name=?), ?)", user.getId(),
Role.TOPGROUPCREATOR.getRoleName(), vo.getId());
} catch (DataIntegrityViolationException e) {
throw new AlreadyAdminException("User id=" + user.getId() + " is already observer in vo " + vo, e, user, vo);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void addTopGroupCreator(PerunSession sess, Vo vo, Group group) throws InternalErrorException, AlreadyAdminException {
try {
jdbc.update("insert into authz (role_id, vo_id, authorized_group_id) values ((select id from roles where name=?), ?, ?)",
Role.TOPGROUPCREATOR.getRoleName(), vo.getId(), group.getId());
} catch (DataIntegrityViolationException e) {
throw new AlreadyAdminException("Group id=" + group.getId() + " is already observer in vo " + vo, e, group, vo);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeObserver(PerunSession sess, Vo vo, User user) throws InternalErrorException, UserNotAdminException {
try {
if (0 == jdbc.update("delete from authz where user_id=? and vo_id=? and role_id=(select id from roles where name=?)", user.getId(), vo.getId(), Role.VOOBSERVER.getRoleName())) {
throw new UserNotAdminException("User id=" + user.getId() + " is not observer of the vo " + vo);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeObserver(PerunSession sess, Vo vo, Group group) throws InternalErrorException, GroupNotAdminException {
try {
if (0 == jdbc.update("delete from authz where authorized_group_id=? and vo_id=? and role_id=(select id from roles where name=?)", group.getId(), vo.getId(), Role.VOOBSERVER.getRoleName())) {
throw new GroupNotAdminException("Group id=" + group.getId() + " is not observer of the vo " + vo);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeTopGroupCreator(PerunSession sess, Vo vo, User user) throws InternalErrorException, UserNotAdminException {
try {
if (0 == jdbc.update("delete from authz where user_id=? and vo_id=? and role_id=(select id from roles where name=?)", user.getId(), vo.getId(), Role.TOPGROUPCREATOR.getRoleName())) {
throw new UserNotAdminException("User id=" + user.getId() + " is not observer of the vo " + vo);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeTopGroupCreator(PerunSession sess, Vo vo, Group group) throws InternalErrorException, GroupNotAdminException {
try {
if (0 == jdbc.update("delete from authz where authorized_group_id=? and vo_id=? and role_id=(select id from roles where name=?)", group.getId(), vo.getId(), Role.TOPGROUPCREATOR.getRoleName())) {
throw new GroupNotAdminException("Group id=" + group.getId() + " is not observer of the vo " + vo);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeAdmin(PerunSession sess, Vo vo, User user) throws InternalErrorException, UserNotAdminException {
try {
if (0 == jdbc.update("delete from authz where user_id=? and vo_id=? and role_id=(select id from roles where name=?)", user.getId(), vo.getId(), Role.VOADMIN.getRoleName())) {
throw new UserNotAdminException("User id=" + user.getId() + " is not admin of the vo " + vo);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removeAdmin(PerunSession sess, Vo vo, Group group) throws InternalErrorException, GroupNotAdminException {
try {
if (0 == jdbc.update("delete from authz where authorized_group_id=? and vo_id=? and role_id=(select id from roles where name=?)", group.getId(), vo.getId(), Role.VOADMIN.getRoleName())) {
throw new GroupNotAdminException("Group id=" + group.getId() + " is not admin of the vo " + vo);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public void removeAdmin(PerunSession sess, SecurityTeam securityTeam, User user) throws UserNotAdminException, InternalErrorException {
try {
if (0 == jdbc.update("delete from authz where user_id=? and security_team_id=? and role_id=(select id from roles where name=?)", user.getId(), securityTeam.getId(), Role.SECURITYADMIN.getRoleName())) {
throw new UserNotAdminException("User id=" + user.getId() + " is not admin of the security team " + securityTeam);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
@Override
public void removeAdmin(PerunSession sess, SecurityTeam securityTeam, Group group) throws GroupNotAdminException, InternalErrorException {
try {
if (0 == jdbc.update("delete from authz where authorized_group_id=? and security_team_id=? and role_id=(select id from roles where name=?)", group.getId(), securityTeam.getId(), Role.SECURITYADMIN.getRoleName())) {
throw new GroupNotAdminException("Group id=" + group.getId() + " is not admin of the security team " + securityTeam);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void makeUserPerunAdmin(PerunSession sess, User user) throws InternalErrorException {
try {
jdbc.update("insert into authz (user_id, role_id) values (?, (select id from roles where name=?))", user.getId(), Role.PERUNADMIN.getRoleName());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void removePerunAdmin(PerunSession sess, User user) throws InternalErrorException, UserNotAdminException {
try {
if (0 == jdbc.update("delete from authz where user_id=? and role_id=(select id from roles where name=?)", user.getId(), Role.PERUNADMIN.getRoleName())) {
throw new UserNotAdminException("User id=" + user.getId() + " is not perun admin.");
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
public void setPerun(Perun perun) {
this.perun = perun;
}
}
| bsd-2-clause |
Moisan/homebrew-core | Formula/spatialite-tools.rb | 1740 | class SpatialiteTools < Formula
desc "CLI tools supporting SpatiaLite"
homepage "https://www.gaia-gis.it/fossil/spatialite-tools/index"
url "https://www.gaia-gis.it/gaia-sins/spatialite-tools-sources/spatialite-tools-5.0.1.tar.gz"
sha256 "9604c205e87f037789bc52302c66ccd1371c3e98c74e8ec4e29b0752de35171c"
license "GPL-3.0-or-later"
revision 2
livecheck do
url "https://www.gaia-gis.it/gaia-sins/spatialite-tools-sources/"
regex(/href=.*?spatialite-tools[._-]v?(\d+(?:\.\d+)+)\.(?:t|zip)/i)
end
bottle do
sha256 cellar: :any, arm64_big_sur: "1dc66a96910742c330fa90b8c547ce7d7693d7c3af118707b5a15b6d6e013ef9"
sha256 cellar: :any, big_sur: "1e4d449a6915bfe180238dd30ed93a2909661076a86f66cea306fda8dbdeb8c4"
sha256 cellar: :any, catalina: "362dd2c109f880d356d7f7e0359936717acfc1ca146277f0e2c456955c33492f"
sha256 cellar: :any, mojave: "ffdc8a4b476146b0f58965f3879f1418a4b151bcbe4a213a005cd5eae5ecc50f"
end
depends_on "pkg-config" => :build
depends_on "libspatialite"
depends_on "proj@7"
depends_on "readosm"
def install
# See: https://github.com/Homebrew/homebrew/issues/3328
ENV.append "LDFLAGS", "-liconv"
# Ensure Homebrew SQLite is found before system SQLite.
#
# spatialite-tools picks `proj` (instead of `proj@7`) if installed
sqlite = Formula["sqlite"]
proj = Formula["proj@7"]
ENV.prepend "LDFLAGS", "-L#{sqlite.opt_lib} -lsqlite3 -L#{proj.opt_lib}"
ENV.prepend "CFLAGS", "-I#{sqlite.opt_include} -I#{proj.opt_include}"
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
test do
system bin/"spatialite", "--version"
end
end
| bsd-2-clause |
gurghet/homebrew-cask | Casks/skyfonts.rb | 479 | cask 'skyfonts' do
version '4.10.0.0'
sha256 'a0186bdde3f1abccef35a9be32ce139bd5e61b428cf5efabaacc194a52a0d4b0'
# skyfonts.com is the official download host per the vendor homepage
url "http://cdn1.skyfonts.com/client/Monotype_SkyFonts_Mac64_#{version}.dmg"
name 'SkyFonts'
homepage 'https://www.fonts.com/web-fonts/google'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'SkyFonts.app'
end
| bsd-2-clause |
usami-k/homebrew-cask | Casks/cacher.rb | 462 | cask 'cacher' do
version '1.5.15'
sha256 'fbdf09e19bf03a36da432a72f29df221de602d5004095b429fdd2e8cf1e241ee'
# cacher-download.nyc3.digitaloceanspaces.com was verified as official when first introduced to the cask
url "https://cacher-download.nyc3.digitaloceanspaces.com/Cacher-#{version}-mac.zip"
appcast 'https://cacher-download.nyc3.digitaloceanspaces.com/latest-mac.json'
name 'Cacher'
homepage 'https://www.cacher.io/'
app 'Cacher.app'
end
| bsd-2-clause |
jabenninghoff/homebrew-core | Formula/signify-osx.rb | 962 | class SignifyOsx < Formula
desc "Cryptographically sign and verify files"
homepage "https://man.openbsd.org/signify.1"
url "https://github.com/jpouellet/signify-osx/archive/1.4.tar.gz"
sha256 "5aa954fe6c54f2fc939771779e5bb64298e46d0a4ae3d08637df44c7ed8d2897"
license "ISC"
head "https://github.com/jpouellet/signify-osx.git"
bottle do
cellar :any_skip_relocation
sha256 "74a8c2fa3d258ad59a5ab7302411a194903ea5295fbf5ecd95a43c2ac28677f4" => :catalina
sha256 "842a6fb535ce56db38ca545fd229f184850e34211c7817879f707f71fe6b31d0" => :mojave
sha256 "cdb1896e5e480edfb6ad7f179d9a2b217cda774039fcf5922bc3eba9b6d3d1bb" => :high_sierra
sha256 "fdac23b07368d6c8ebad06c2b8451f0c8228f71f5c65b48d672cfd581b222509" => :sierra
end
def install
system "make"
system "make", "test"
system "make", "install", "PREFIX=#{prefix}"
end
test do
system "#{bin}/signify", "-G", "-n", "-p", "test.pub", "-s", "test.sec"
end
end
| bsd-2-clause |
sebastienros/jint | Jint.Tests.Test262/test/language/expressions/object/dstr-async-gen-meth-obj-ptrn-id-trailing-comma.js | 1419 | // This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-ptrn-id-trailing-comma.case
// - src/dstr-binding/default/async-gen-meth.template
/*---
description: Trailing comma is allowed following BindingPropertyList (async generator method)
esid: sec-asyncgenerator-definitions-propertydefinitionevaluation
features: [async-iteration]
flags: [generated, async]
info: |
AsyncGeneratorMethod :
async [no LineTerminator here] * PropertyName ( UniqueFormalParameters )
{ AsyncGeneratorBody }
1. Let propKey be the result of evaluating PropertyName.
2. ReturnIfAbrupt(propKey).
3. If the function code for this AsyncGeneratorMethod is strict mode code, let strict be true.
Otherwise let strict be false.
4. Let scope be the running execution context's LexicalEnvironment.
5. Let closure be ! AsyncGeneratorFunctionCreate(Method, UniqueFormalParameters,
AsyncGeneratorBody, scope, strict).
[...]
13.3.3 Destructuring Binding Patterns
ObjectBindingPattern[Yield] :
{ }
{ BindingPropertyList[?Yield] }
{ BindingPropertyList[?Yield] , }
---*/
var callCount = 0;
var obj = {
async *method({ x, }) {
assert.sameValue(x, 23);
callCount = callCount + 1;
}
};
obj.method({ x: 23 }).next().then(() => {
assert.sameValue(callCount, 1, 'invoked exactly once');
}).then($DONE, $DONE);
| bsd-2-clause |
zynga/saigon | modules/log4php/configurators/LoggerConfigurationAdapter.php | 1366 | <?php
/**
* 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 log4php
*/
/**
* The interface for configurator adapters.
*
* Adapters convert configuration in several formats such as XML, ini and PHP
* file to a PHP array.
*
* @package log4php
* @subpackage configurators
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @version $Revision$
* @since 2.2
*/
interface LoggerConfigurationAdapter
{
/** Converts the configuration file to PHP format usable by the configurator. */
public function convert($input);
}
?> | bsd-2-clause |
ajgarlag/zf1 | tests/Zend/Measure/AngleTest.php | 11675 | <?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 Zend
* @package Zend_Measure
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* Zend_Measure_Angle
*/
require_once 'Zend/Measure/Angle.php';
/**
* @category Zend
* @package Zend_Measure
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @group Zend_Measure
*/
class Zend_Measure_AngleTest extends PHPUnit_Framework_TestCase
{
/**
* test for Angle initialisation
* expected instance
*/
public function testAngleInit()
{
$value = new Zend_Measure_Angle('100',Zend_Measure_Angle::STANDARD,'de');
$this->assertTrue($value instanceof Zend_Measure_Angle,'Zend_Measure_Angle Object not returned');
}
/**
* test for exception unknown type
* expected exception
*/
public function testAngleUnknownType()
{
try {
$value = new Zend_Measure_Angle('100','Angle::UNKNOWN','de');
$this->fail('Exception expected because of unknown type');
} catch (Zend_Measure_Exception $e) {
// success
}
}
/**
* test for exception unknown value
* expected exception
*/
public function testAngleUnknownValue()
{
try {
$value = new Zend_Measure_Angle('novalue',Zend_Measure_Angle::STANDARD,'de');
$this->fail('Exception expected because of empty value');
} catch (Zend_Measure_Exception $e) {
// success
}
}
/**
* test for exception unknown locale
* expected root value
*/
public function testAngleUnknownLocale()
{
try {
$value = new Zend_Measure_Angle('100',Zend_Measure_Angle::STANDARD,'nolocale');
$this->fail('Exception expected because of unknown locale');
} catch (Zend_Measure_Exception $e) {
// success
}
}
/**
* test for standard locale
* expected integer
*/
public function testAngleNoLocale()
{
$value = new Zend_Measure_Angle('100',Zend_Measure_Angle::STANDARD);
$this->assertEquals(100, $value->getValue(),'Zend_Measure_Angle value expected');
}
/**
* test for positive value
* expected integer
*/
public function testAngleValuePositive()
{
$value = new Zend_Measure_Angle('100',Zend_Measure_Angle::STANDARD,'de');
$this->assertEquals(100, $value->getValue(), 'Zend_Measure_Angle value expected to be a positive integer');
}
/**
* test for negative value
* expected integer
*/
public function testAngleValueNegative()
{
$value = new Zend_Measure_Angle('-100',Zend_Measure_Angle::STANDARD,'de');
$this->assertEquals(-100, $value->getValue(), 'Zend_Measure_Angle value expected to be a negative integer');
}
/**
* test for decimal value
* expected float
*/
public function testAngleValueDecimal()
{
$value = new Zend_Measure_Angle('-100,200',Zend_Measure_Angle::STANDARD,'de');
$this->assertEquals(-100.200, $value->getValue(), 'Zend_Measure_Angle value expected to be a decimal value');
}
/**
* test for decimal seperated value
* expected float
*/
public function testAngleValueDecimalSeperated()
{
$value = new Zend_Measure_Angle('-100.100,200',Zend_Measure_Angle::STANDARD,'de');
$this->assertEquals(-100100.200, $value->getValue(),'Zend_Measure_Angle Object not returned');
}
/**
* test for string with integrated value
* expected float
*/
public function testAngleValueString()
{
$value = new Zend_Measure_Angle('-100.100,200',Zend_Measure_Angle::STANDARD,'de');
$this->assertEquals(-100100.200, $value->getValue(),'Zend_Measure_Angle Object not returned');
}
/**
* test for equality
* expected true
*/
public function testAngleEquality()
{
$value = new Zend_Measure_Angle('-100.100,200',Zend_Measure_Angle::STANDARD,'de');
$newvalue = new Zend_Measure_Angle('-100.100,200',Zend_Measure_Angle::STANDARD,'de');
$this->assertTrue($value->equals($newvalue),'Zend_Measure_Angle Object should be equal');
}
/**
* test for no equality
* expected false
*/
public function testAngleNoEquality()
{
$value = new Zend_Measure_Angle('-100.100,200',Zend_Measure_Angle::STANDARD,'de');
$newvalue = new Zend_Measure_Angle('-100,200',Zend_Measure_Angle::STANDARD,'de');
$this->assertFalse($value->equals($newvalue),'Zend_Measure_Angle Object should be not equal');
}
/**
* test for set positive value
* expected integer
*/
public function testAngleSetPositive()
{
$value = new Zend_Measure_Angle('100',Zend_Measure_Angle::STANDARD,'de');
$value->setValue('200',Zend_Measure_Angle::STANDARD,'de');
$this->assertEquals(200, $value->getValue(), 'Zend_Measure_Angle value expected to be a positive integer');
}
/**
* test for set negative value
* expected integer
*/
public function testAngleSetNegative()
{
$value = new Zend_Measure_Angle('-100',Zend_Measure_Angle::STANDARD,'de');
$value->setValue('-200',Zend_Measure_Angle::STANDARD,'de');
$this->assertEquals(-200, $value->getValue(), 'Zend_Measure_Angle value expected to be a negative integer');
}
/**
* test for set decimal value
* expected float
*/
public function testAngleSetDecimal()
{
$value = new Zend_Measure_Angle('-100,200',Zend_Measure_Angle::STANDARD,'de');
$value->setValue('-200,200',Zend_Measure_Angle::STANDARD,'de');
$this->assertEquals(-200.200, $value->getValue(), 'Zend_Measure_Angle value expected to be a decimal value');
}
/**
* test for set decimal seperated value
* expected float
*/
public function testAngleSetDecimalSeperated()
{
$value = new Zend_Measure_Angle('-100.100,200',Zend_Measure_Angle::STANDARD,'de');
$value->setValue('-200.200,200',Zend_Measure_Angle::STANDARD,'de');
$this->assertEquals(-200200.200, $value->getValue(),'Zend_Measure_Angle Object not returned');
}
/**
* test for set string with integrated value
* expected float
*/
public function testAngleSetString()
{
$value = new Zend_Measure_Angle('-100.100,200',Zend_Measure_Angle::STANDARD,'de');
$value->setValue('-200.200,200',Zend_Measure_Angle::STANDARD,'de');
$this->assertEquals(-200200.200, $value->getValue(),'Zend_Measure_Angle Object not returned');
}
/**
* test for exception unknown type
* expected exception
*/
public function testAngleSetUnknownType()
{
try {
$value = new Zend_Measure_Angle('100',Zend_Measure_Angle::STANDARD,'de');
$value->setValue('-200.200,200','Angle::UNKNOWN','de');
$this->fail('Exception expected because of unknown type');
} catch (Zend_Measure_Exception $e) {
// success
}
}
/**
* test for exception unknown value
* expected exception
*/
public function testAngleSetUnknownValue()
{
try {
$value = new Zend_Measure_Angle('100',Zend_Measure_Angle::STANDARD,'de');
$value->setValue('novalue',Zend_Measure_Angle::STANDARD,'de');
$this->fail('Exception expected because of empty value');
} catch (Zend_Measure_Exception $e) {
// success
}
}
/**
* test for exception unknown locale
* expected exception
*/
public function testAngleSetUnknownLocale()
{
try {
$value = new Zend_Measure_Angle('100',Zend_Measure_Angle::STANDARD,'de');
$value->setValue('200',Zend_Measure_Angle::STANDARD,'nolocale');
$this->fail('Exception expected because of unknown locale');
} catch (Zend_Measure_Exception $e) {
// success
}
}
/**
* test for exception unknown locale
* expected exception
*/
public function testAngleSetWithNoLocale()
{
$value = new Zend_Measure_Angle('100', Zend_Measure_Angle::STANDARD, 'de');
$value->setValue('200', Zend_Measure_Angle::STANDARD);
$this->assertEquals(200, $value->getValue(), 'Zend_Measure_Angle value expected to be a positive integer');
}
/**
* test setting type
* expected new type
*/
public function testAngleSetType()
{
$value = new Zend_Measure_Angle('-100',Zend_Measure_Angle::STANDARD,'de');
$value->setType(Zend_Measure_Angle::GRAD);
$this->assertEquals(Zend_Measure_Angle::GRAD, $value->getType(), 'Zend_Measure_Angle type expected');
}
/**
* test setting computed type
* expected new type
*/
public function testAngleSetComputedType1()
{
$value = new Zend_Measure_Angle('-100',Zend_Measure_Angle::RADIAN,'de');
$value->setType(Zend_Measure_Angle::MINUTE);
$this->assertEquals(Zend_Measure_Angle::MINUTE, $value->getType(), 'Zend_Measure_Angle type expected');
}
/**
* test setting computed type
* expected new type
*/
public function testAngleSetComputedType2()
{
$value = new Zend_Measure_Angle('-100',Zend_Measure_Angle::MINUTE,'de');
$value->setType(Zend_Measure_Angle::RADIAN);
$this->assertEquals(Zend_Measure_Angle::RADIAN, $value->getType(), 'Zend_Measure_Angle type expected');
}
/**
* test setting unknown type
* expected new type
*/
public function testAngleSetTypeFailed()
{
try {
$value = new Zend_Measure_Angle('-100',Zend_Measure_Angle::STANDARD,'de');
$value->setType('Angle::UNKNOWN');
$this->fail('Exception expected because of unknown type');
} catch (Zend_Measure_Exception $e) {
// success
}
}
/**
* test toString
* expected string
*/
public function testAngleToString()
{
$value = new Zend_Measure_Angle('-100',Zend_Measure_Angle::STANDARD,'de');
$this->assertEquals('-100 rad', $value->toString(), 'Value -100 rad expected');
}
/**
* test __toString
* expected string
*/
public function testAngle_ToString()
{
$value = new Zend_Measure_Angle('-100',Zend_Measure_Angle::STANDARD,'de');
$this->assertEquals('-100 rad', $value->__toString(), 'Value -100 rad expected');
}
/**
* test getConversionList
* expected array
*/
public function testAngleConversionList()
{
$value = new Zend_Measure_Angle('-100',Zend_Measure_Angle::STANDARD,'de');
$unit = $value->getConversionList();
$this->assertTrue(is_array($unit), 'Array expected');
}
}
| bsd-3-clause |
dlodato/AliPhysics | PWGGA/GammaConv/macros/AddTask_GammaConvV1_pPb.C | 48134 | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: Friederike Bock, Annika Passfeld *
* Version 1.0 *
* *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//***************************************************************************************
//This AddTask is supposed to set up the main task
//($ALIPHYSICS/PWGGA/GammaConv/AliAnalysisTaskGammaConvV1.cxx) for
//pp together with all supporting classes
//***************************************************************************************
//***************************************************************************************
//CutHandler contains all cuts for a certain analysis and trainconfig,
//it automatically checks length of cutStrings and takes care of the number of added cuts,
//no specification of the variable 'numberOfCuts' needed anymore.
//***************************************************************************************
class CutHandlerConv{
public:
CutHandlerConv(Int_t nMax=10){
nCuts=0; nMaxCuts=nMax; validCuts = true;
eventCutArray = new TString[nMaxCuts]; photonCutArray = new TString[nMaxCuts]; mesonCutArray = new TString[nMaxCuts]; clusterCutArray = new TString[nMaxCuts];
for(Int_t i=0; i<nMaxCuts; i++) {eventCutArray[i] = ""; photonCutArray[i] = ""; mesonCutArray[i] = ""; clusterCutArray[i] = "";}
}
void AddCut(TString eventCut, TString photonCut, TString mesonCut){
if(nCuts>=nMaxCuts) {cout << "ERROR in CutHandlerConv: Exceeded maximum number of cuts!" << endl; validCuts = false; return;}
if( eventCut.Length()!=8 || photonCut.Length()!=26 || mesonCut.Length()!=16 ) {cout << "ERROR in CutHandlerConv: Incorrect length of cut string!" << endl; validCuts = false; return;}
eventCutArray[nCuts]=eventCut; photonCutArray[nCuts]=photonCut; mesonCutArray[nCuts]=mesonCut; clusterCutArray[nCuts]="";
nCuts++;
return;
}
void AddCut(TString eventCut, TString photonCut, TString mesonCut, TString clusterCut){
if(nCuts>=nMaxCuts) {cout << "ERROR in CutHandlerConv: Exceeded maximum number of cuts!" << endl; validCuts = false; return;}
if( eventCut.Length()!=8 || photonCut.Length()!=26 || mesonCut.Length()!=16 || clusterCut.Length()!=19 ) {cout << "ERROR in CutHandlerConv: Incorrect length of cut string!" << endl; validCuts = false; return;}
eventCutArray[nCuts]=eventCut; photonCutArray[nCuts]=photonCut; mesonCutArray[nCuts]=mesonCut; clusterCutArray[nCuts]=clusterCut;
nCuts++;
return;
}
Bool_t AreValid(){return validCuts;}
Int_t GetNCuts(){if(validCuts) return nCuts; else return 0;}
TString GetEventCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return eventCutArray[i]; else{cout << "ERROR in CutHandlerConv: GetEventCut wrong index i" << endl;return "";}}
TString GetPhotonCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return photonCutArray[i]; else {cout << "ERROR in CutHandlerConv: GetPhotonCut wrong index i" << endl;return "";}}
TString GetMesonCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return mesonCutArray[i]; else {cout << "ERROR in CutHandlerConv: GetMesonCut wrong index i" << endl;return "";}}
TString GetClusterCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return clusterCutArray[i]; else {cout << "ERROR in CutHandlerConv: GetClusterCut wrong index i" << endl;return "";}}
private:
Bool_t validCuts;
Int_t nCuts; Int_t nMaxCuts;
TString* eventCutArray;
TString* photonCutArray;
TString* mesonCutArray;
TString* clusterCutArray;
};
void AddTask_GammaConvV1_pPb( Int_t trainConfig = 1, // change different set of cuts
Int_t isMC = 0, // run MC
Int_t enableQAMesonTask = 0, // enable QA in AliAnalysisTaskGammaConvV1
Int_t enableQAPhotonTask = 0, // enable additional QA task
TString fileNameInputForWeighting = "MCSpectraInput.root", // path to file for weigting input
Int_t doWeightingPart = 0, // enable Weighting
TString generatorName = "DPMJET", // generator Name
TString cutnumberAODBranch = "800000006008400000150000000", // cutnumber for AOD branch
Bool_t enableV0findingEffi = kFALSE, // enables V0finding efficiency histograms
Bool_t enablePlotVsCentrality = kFALSE,
Bool_t enableTriggerMimicking = kFALSE, // enable trigger mimicking
Bool_t enableTriggerOverlapRej = kFALSE, // enable trigger overlap rejection
Float_t maxFacPtHard = 3., // maximum factor between hardest jet and ptHard generated
TString periodNameV0Reader = "",
Bool_t doMultiplicityWeighting = kFALSE, //
TString fileNameInputForMultWeighing = "Multiplicity.root", //
TString periodNameAnchor = "", //
Bool_t runLightOutput = kFALSE, // switch to run light output (only essential histograms for afterburner)
Bool_t runTHnSparse = kTRUE, // switch on THNsparse
Int_t enableMatBudWeightsPi0 = 0, // 1 = three radial bins, 2 = 10 radial bins
TString filenameMatBudWeights = "MCInputFileMaterialBudgetWeights.root",
Int_t debugLevel = 0, // introducing debug levels for grid running
TString additionalTrainConfig = "0" // additional counter for trainconfig, this has to be always the last parameter
) {
//parse additionalTrainConfig flag
TObjArray *rAddConfigArr = additionalTrainConfig.Tokenize("_");
if(rAddConfigArr->GetEntries()<1){cout << "ERROR: AddTask_GammaConvV1_pPb during parsing of additionalTrainConfig String '" << additionalTrainConfig.Data() << "'" << endl; return;}
TObjString* rAdditionalTrainConfig;
for(Int_t i = 0; i<rAddConfigArr->GetEntries() ; i++){
if(i==0) rAdditionalTrainConfig = (TObjString*)rAddConfigArr->At(i);
else{
TObjString* temp = (TObjString*) rAddConfigArr->At(i);
TString tempStr = temp->GetString();
cout<< tempStr.Data()<<endl;
if(tempStr.Contains("MaterialBudgetWeights") && enableMatBudWeightsPi0 > 0){
TObjArray *fileNameMatBudWeightsArr = filenameMatBudWeights.Tokenize("/");
if(fileNameMatBudWeightsArr->GetEntries()<1 ){cout<<"ERROR: AddTask_GammaConvV1_pPb when reading material budget weights file name" << filenameMatBudWeights.Data()<< "'" << endl; return;}
TObjString * oldMatObjStr = (TObjString*)fileNameMatBudWeightsArr->At( fileNameMatBudWeightsArr->GetEntries()-1);
TString oldfileName = oldMatObjStr->GetString();
TString newFileName = Form("MCInputFile%s.root",tempStr.Data());
cout<<newFileName.Data()<<endl;
if( oldfileName.EqualTo(newFileName.Data()) == 0 ){
filenameMatBudWeights.ReplaceAll(oldfileName.Data(),newFileName.Data());
cout << "INFO: AddTask_GammaConvV1_pPb the material budget weights file has been change to " <<filenameMatBudWeights.Data()<<"'"<< endl;
}
}
}
}
TString sAdditionalTrainConfig = rAdditionalTrainConfig->GetString();
if (sAdditionalTrainConfig.Atoi() > 0){
trainConfig = trainConfig + sAdditionalTrainConfig.Atoi();
cout << "INFO: AddTask_GammaConvV1_pPb running additionalTrainConfig '" << sAdditionalTrainConfig.Atoi() << "', train config: '" << trainConfig << "'" << endl;
}
cout << endl << endl;
cout << "************************************************************************" << endl;
cout << "************************************************************************" << endl;
cout << "INFO: Initializing GammaConvV1 for pPb - config: " << trainConfig << endl;
cout << "************************************************************************" << endl;
cout << "************************************************************************" << endl;
Int_t isHeavyIon = 2;
if (debugLevel > 0){
cout << "enabled debugging for trainconfig: " << debugLevel << endl;
}
// ================== GetAnalysisManager ===============================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error(Form("AddTask_GammaConvV1_%i",trainConfig), "No analysis manager found.");
return ;
}
// ================== GetInputEventHandler =============================
AliVEventHandler *inputHandler=mgr->GetInputEventHandler();
Bool_t isMCForOtherSettings = 0;
if (isMC > 0) isMCForOtherSettings = 1;
//========= Add PID Reponse to ANALYSIS manager ====
if(!(AliPIDResponse*)mgr->GetTask("PIDResponseTask")){
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
AddTaskPIDResponse(isMCForOtherSettings);
}
//========= Set Cutnumber for V0Reader ================================
TString cutnumberPhoton = "06000008000100001500000000";
TString cutnumberEvent = "80000003";
Bool_t doEtaShift = kFALSE;
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
//========= Add V0 Reader to ANALYSIS manager if not yet existent =====
TString V0ReaderName = Form("V0ReaderV1_%s_%s",cutnumberEvent.Data(),cutnumberPhoton.Data());
if( !(AliV0ReaderV1*)mgr->GetTask(V0ReaderName.Data()) ){
AliV0ReaderV1 *fV0ReaderV1 = new AliV0ReaderV1(V0ReaderName.Data());
if (periodNameV0Reader.CompareTo("") != 0) fV0ReaderV1->SetPeriodName(periodNameV0Reader);
fV0ReaderV1->SetUseOwnXYZCalculation(kTRUE);
fV0ReaderV1->SetCreateAODs(kFALSE);// AOD Output
fV0ReaderV1->SetUseAODConversionPhoton(kTRUE);
fV0ReaderV1->SetProduceV0FindingEfficiency(enableV0findingEffi);
if (!mgr) {
Error("AddTask_V0ReaderV1", "No analysis manager found.");
return;
}
AliConvEventCuts *fEventCuts=NULL;
if(cutnumberEvent!=""){
fEventCuts= new AliConvEventCuts(cutnumberEvent.Data(),cutnumberEvent.Data());
fEventCuts->SetPreSelectionCutFlag(kTRUE);
fEventCuts->SetV0ReaderName(V0ReaderName);
if (debugLevel > 0) fEventCuts->SetDebugLevel(debugLevel);
if (periodNameV0Reader.CompareTo("") != 0) fEventCuts->SetPeriodEnum(periodNameV0Reader);
fEventCuts->SetLightOutput(runLightOutput);
if(fEventCuts->InitializeCutsFromCutString(cutnumberEvent.Data())){
fEventCuts->DoEtaShift(doEtaShift);
fV0ReaderV1->SetEventCuts(fEventCuts);
fEventCuts->SetFillCutHistograms("",kTRUE);
}
}
// Set AnalysisCut Number
AliConversionPhotonCuts *fCuts=NULL;
if(cutnumberPhoton!=""){
fCuts= new AliConversionPhotonCuts(cutnumberPhoton.Data(),cutnumberPhoton.Data());
fCuts->SetPreSelectionCutFlag(kTRUE);
fCuts->SetIsHeavyIon(isHeavyIon);
fCuts->SetV0ReaderName(V0ReaderName);
fCuts->SetLightOutput(runLightOutput);
if(trainConfig==193 || trainConfig==194 || trainConfig==195 || trainConfig==196){
fCuts->SetDodEdxSigmaCut(kFALSE);
}
if(fCuts->InitializeCutsFromCutString(cutnumberPhoton.Data())){
fV0ReaderV1->SetConversionCuts(fCuts);
fCuts->SetFillCutHistograms("",kTRUE);
}
}
if(inputHandler->IsA()==AliAODInputHandler::Class()){
// AOD mode
cout << "AOD handler: adding " << cutnumberAODBranch.Data() << " as conversion branch" << endl;
fV0ReaderV1->SetDeltaAODBranchName(Form("GammaConv_%s_gamma",cutnumberAODBranch.Data()));
}
fV0ReaderV1->Init();
AliLog::SetGlobalLogLevel(AliLog::kInfo);
//connect input V0Reader
mgr->AddTask(fV0ReaderV1);
mgr->ConnectInput(fV0ReaderV1,0,cinput);
}
//================================================
//========= Add task to the ANALYSIS manager =====
//================================================
// find input container
AliAnalysisTaskGammaConvV1 *task=NULL;
task= new AliAnalysisTaskGammaConvV1(Form("GammaConvV1_%i",trainConfig));
task->SetIsHeavyIon(isHeavyIon);
task->SetIsMC(isMC);
task->SetV0ReaderName(V0ReaderName);
task->SetLightOutput(runLightOutput);
// Cut Numbers to use in Analysis
CutHandlerConv cuts;
Bool_t doEtaShiftIndCuts = kFALSE;
TString stringShift = "";
// new standard configurations MB
if(trainConfig == 1){
cuts.AddCut("80000113", "00200009327000008250404000", "0162103500900000"); // new default
cuts.AddCut("80000113", "00200009327000008250400000", "0162103500900000"); // new default, no to close
} else if (trainConfig == 2){
cuts.AddCut("80000113", "00200009327000008250404000", "0162103500000000"); // new default
cuts.AddCut("80000113", "00200009327000008250400000", "0162103500000000"); // new default, no to close
} else if (trainConfig == 3){
cuts.AddCut("80000123", "00200009327000008250404000", "0162103500900000"); // new default
cuts.AddCut("80000123", "00200009327000008250400000", "0162103500900000"); // new default, no to close
} else if (trainConfig == 4){
cuts.AddCut("80000123", "00200009327000008250404000", "0162103500000000"); // new default
cuts.AddCut("80000123", "00200009327000008250400000", "0162103500000000"); // new default, no to close
} else if (trainConfig == 5){ // past-future protection
cuts.AddCut("80000213", "00200009327000008250404000", "0162103500900000"); // new default, +-2.225\mus no other interaction
cuts.AddCut("80000213", "00200009327000008250400000", "0162103500900000"); // new default, no to close, +-2.225\mus no other interaction
cuts.AddCut("80000513", "00200009327000008250404000", "0162103500900000"); // new default, +-1.075\mus no other interaction
cuts.AddCut("80000513", "00200009327000008250400000", "0162103500900000"); // new default, no to close, +-1.075\mus no other interaction
} else if (trainConfig == 6){ // past-future protection
cuts.AddCut("80000213", "00200009327000008250404000", "0162103500000000"); // new default, +-2.225\mus no other interaction
cuts.AddCut("80000213", "00200009327000008250400000", "0162103500000000"); // new default, no to close, +-2.225\mus no other interaction
cuts.AddCut("80000513", "00200009327000008250404000", "0162103500000000"); // new default, +-1.075\mus no other interaction
cuts.AddCut("80000513", "00200009327000008250400000", "0162103500000000"); // new default, no to close, +-1.075\mus no other interaction
// default cut all cents without smearing and to close V0
} else if (trainConfig == 10) {
cuts.AddCut("80200113", "00200009327000008250400000", "0162103500000000"); // 0-20%
cuts.AddCut("82400113", "00200009327000008250400000", "0162103500000000"); // 20-40%
cuts.AddCut("84600113", "00200009327000008250400000", "0162103500000000"); // 40-60%
cuts.AddCut("86000113", "00200009327000008250400000", "0162103500000000"); // 60-100%
} else if (trainConfig == 11) { // past future protection: +-2.225\mus no other interaction
cuts.AddCut("80200213", "00200009327000008250400000", "0162103500000000"); // 0-20%
cuts.AddCut("82400213", "00200009327000008250400000", "0162103500000000"); // 20-40%
cuts.AddCut("84600213", "00200009327000008250400000", "0162103500000000"); // 40-60%
cuts.AddCut("86000213", "00200009327000008250400000", "0162103500000000"); // 60-100%
} else if (trainConfig == 12) { // past future protection: +-1.075\mus no other interaction
cuts.AddCut("80200513", "00200009327000008250400000", "0162103500000000"); // 0-20%
cuts.AddCut("82400513", "00200009327000008250400000", "0162103500000000"); // 20-40%
cuts.AddCut("84600513", "00200009327000008250400000", "0162103500000000"); // 40-60%
cuts.AddCut("86000513", "00200009327000008250400000", "0162103500000000"); // 60-100%
// new standard configurations 0-20
} else if (trainConfig == 20){
cuts.AddCut("80200113", "00200009327000008250404000", "0162103500900000"); //new default
cuts.AddCut("80200113", "00200009327000008250400000", "0162103500900000"); //new default, no to close
} else if (trainConfig == 21){
cuts.AddCut("80200113", "00200009327000008250404000", "0162103500000000"); //new default
cuts.AddCut("80200113", "00200009327000008250400000", "0162103500000000"); //new default, no to close
} else if (trainConfig == 22){
cuts.AddCut("80200123", "00200009327000008250404000", "0162103500900000"); //new default
cuts.AddCut("80200123", "00200009327000008250400000", "0162103500900000"); //new default, no to close
} else if (trainConfig == 23){
cuts.AddCut("80200123", "00200009327000008250404000", "0162103500000000"); //new default
cuts.AddCut("80200123", "00200009327000008250400000", "0162103500000000"); //new default, no to close
// new standard configurations 20-40
} else if (trainConfig == 30){
cuts.AddCut("82400113", "00200009327000008250404000", "0162103500900000"); //new default
cuts.AddCut("82400113", "00200009327000008250400000", "0162103500900000"); //new default, no to close
} else if (trainConfig == 31){
cuts.AddCut("82400113", "00200009327000008250404000", "0162103500000000"); //new default
cuts.AddCut("82400113", "00200009327000008250400000", "0162103500000000"); //new default, no to close
} else if (trainConfig == 32){
cuts.AddCut("82400123", "00200009327000008250404000", "0162103500900000"); //new default
cuts.AddCut("82400123", "00200009327000008250400000", "0162103500900000"); //new default, no to close
} else if (trainConfig == 33){
cuts.AddCut("82400123", "00200009327000008250404000", "0162103500000000"); //new default
cuts.AddCut("82400123", "00200009327000008250400000", "0162103500000000"); //new default, no to close
// new standard configurations 40-60
} else if (trainConfig == 40){
cuts.AddCut("84600113", "00200009327000008250404000", "0162103500900000"); //new default
cuts.AddCut("84600113", "00200009327000008250400000", "0162103500900000"); //new default, no to close
} else if (trainConfig == 41){
cuts.AddCut("84600113", "00200009327000008250404000", "0162103500000000"); //new default
cuts.AddCut("84600113", "00200009327000008250400000", "0162103500000000"); //new default, no to close
} else if (trainConfig == 42){
cuts.AddCut("84600123", "00200009327000008250404000", "0162103500900000"); //new default
cuts.AddCut("84600123", "00200009327000008250400000", "0162103500900000"); //new default, no to close
} else if (trainConfig == 43){
cuts.AddCut("84600123", "00200009327000008250404000", "0162103500000000"); //new default
cuts.AddCut("84600123", "00200009327000008250400000", "0162103500000000"); //new default, no to close
// new standard configurations 60-80
} else if (trainConfig == 50){
cuts.AddCut("86000113", "00200009327000008250404000", "0162103500900000"); //new default
cuts.AddCut("86000113", "00200009327000008250400000", "0162103500900000"); //new default, no to close
} else if (trainConfig == 51){
cuts.AddCut("86000113", "00200009327000008250404000", "0162103500000000"); //new default
cuts.AddCut("86000113", "00200009327000008250400000", "0162103500000000"); //new default, no to close
} else if (trainConfig == 52){
cuts.AddCut("86000123", "00200009327000008250404000", "0162103500900000"); //new default
cuts.AddCut("86000123", "00200009327000008250400000", "0162103500900000"); //new default, no to close
} else if (trainConfig == 53){
cuts.AddCut("86000123", "00200009327000008250404000", "0162103500000000"); //new default
cuts.AddCut("86000123", "00200009327000008250400000", "0162103500000000"); //new default, no to close
//--------------------------------------------------------------------------
// Systematics variations for standard ana w/o to close V0, wo smearing
//--------------------------------------------------------------------------
} else if (trainConfig == 100) { //default + dEdx Variation
cuts.AddCut("80000113", "00200009327000008250400000", "0162103500000000"); // new default
cuts.AddCut("80000113", "00200009217000008260400000", "0162103500000000"); // old standard cut
cuts.AddCut("80000113", "00200009327000008250404000", "0162103500000000"); // new default w/ to clos v0
} else if (trainConfig == 101) { // gamma eta & meson rap var
cuts.AddCut("80000113", "03200009327000008250400000", "0162303500000000"); // |eta| < 0.65, |y| < 0.6
cuts.AddCut("80000113", "04200009327000008250400000", "0162203500000000"); // |eta| < 0.75, |y| < 0.7
cuts.AddCut("80000113", "01200009327000008250400000", "0162403500000000"); // |eta| < 0.6, |y| < 0.5
} else if (trainConfig == 102) { // minR and single pt var
cuts.AddCut("80000113", "00100009327000008250400000", "0162103500000000"); // minR 2.8
cuts.AddCut("80000113", "00900009327000008250400000", "0162103500000000"); // minR 7.5
cuts.AddCut("80000113", "00200079327000008250400000", "0162103500000000"); // single pT 0. GeV/c
cuts.AddCut("80000113", "00200019327000008250400000", "0162103500000000"); // single pT 0.1 GeV/c
} else if (trainConfig == 103) { // TPC cluster & edEdx var
cuts.AddCut("80000113", "00200008327000008250400000", "0162103500000000"); // TPC Cluster 0.35
cuts.AddCut("80000113", "00200006327000008250400000", "0162103500000000"); // TPC Cluster 0.7
cuts.AddCut("80000113", "00200009227000008250400000", "0162103500000000"); // edEdx -4,5
cuts.AddCut("80000113", "00200009627000008250400000", "0162103500000000"); // edEdx -2.5,4
cuts.AddCut("80000113", "00200009127000008250400000", "0162103500000000"); // edEdx 5,5
} else if (trainConfig == 104) { //PidEdx Variation
cuts.AddCut("80000113", "00200009357000008250400000", "0162103500000000"); // PidEdx(2, >0.4GeV)
cuts.AddCut("80000113", "00200009387300008250400000", "0162103500000000"); // PidEdx(2, >0.4GeV; 1>3.5GeV)
cuts.AddCut("80000113", "00200009320000008250400000", "0162103500000000"); // PidEdx(1, >0.5GeV)
cuts.AddCut("80000113", "00200009325000008250400000", "0162103500000000"); // PidEdx(1, >0.3GeV)
} else if (trainConfig == 105) { //PidEdx Variation 2
cuts.AddCut("80000113", "00200009327300008250400000", "0162103500000000"); // PidEdx(1, >0.4GeV; -10>3.5GeV)
cuts.AddCut("80000113", "00200009326000008250400000", "0162103500000000"); // PidEdx(1, >0.25GeV)
cuts.AddCut("80000113", "00200009326200008250400000", "0162103500000000"); // PidEdx(1, >0.25GeV; -10>4GeV)
cuts.AddCut("80000113", "00200009327200008250400000", "0162103500000000"); // PidEdx(1, >0.4GeV; -10>4GeV)
} else if (trainConfig == 106) { // qt & psipair variation
cuts.AddCut("80000113", "00200009327000003250400000", "0162103500000000"); // qT 0.05 1D
cuts.AddCut("80000113", "00200009327000009250400000", "0162103500000000"); // qT 0.03 2D
cuts.AddCut("80000113", "00200009327000002250400000", "0162103500000000"); // qT 0.07 1D
cuts.AddCut("80000113", "00200009327000008240400000", "0162103500000000"); // Psi Pair: 1D 0.2
} else if (trainConfig == 107) { // PsiPair Variation
cuts.AddCut("80000113", "00200009327000008210400000", "0162103500000000"); // Psi Pair: 1D 0.1
cuts.AddCut("80000113", "00200009327000008150400000", "0162103500000000"); // chi2 50 2D
cuts.AddCut("80000113", "00200009327000008850400000", "0162103500000000"); // chi2 20 2D
cuts.AddCut("80000113", "00200009327000008260400000", "0162103500000000"); // psi pair 0.05
} else if (trainConfig == 108) { // cos point & meson alpha variation
cuts.AddCut("80000113", "00200009327000008250300000", "0162103500000000"); // cos pointing angle 0.75
cuts.AddCut("80000113", "00200009327000008250600000", "0162103500000000"); // cos pointing angle 0.9
cuts.AddCut("80000113", "00200009327000008250400000", "0162106500000000"); // alpha meson cut 0.8
} else if (trainConfig == 109) { // BG mixing & smear variations
cuts.AddCut("80000113", "00200009327000008250400000", "0262103500000000"); // BG track multiplicity
cuts.AddCut("80000113", "00200009327000008250400000", "0162103500800000"); // fPSigSmearingCte=0.014;
cuts.AddCut("80000113", "00200009327000008250400000", "0162103500900000"); // fPSigSmearingCte=0.014;
//--------------------------------------------------------------------------
// Systematics variations for standard ana w/o to close V0, wo smearing added signals
//--------------------------------------------------------------------------
} else if (trainConfig == 120) { //default + dEdx Variation added sig
cuts.AddCut("80000123", "00200009327000008250400000", "0162103500000000"); // new default
cuts.AddCut("80000123", "00200009217000008260400000", "0162103500000000"); // old standard cut
cuts.AddCut("80000123", "00200009327000008250404000", "0162103500000000"); // new default w/ to close V0
} else if (trainConfig == 121) { // gamma eta & meson rap var added sig
cuts.AddCut("80000123", "03200009327000008250400000", "0162303500000000"); // |eta| < 0.65, |y| < 0.6
cuts.AddCut("80000123", "04200009327000008250400000", "0162203500000000"); // |eta| < 0.75, |y| < 0.7
cuts.AddCut("80000123", "01200009327000008250400000", "0162403500000000"); // |eta| < 0.6, |y| < 0.5
} else if (trainConfig == 122) { // minR and single pt var added sig
cuts.AddCut("80000123", "00100009327000008250400000", "0162103500000000"); // minR 2.8
cuts.AddCut("80000123", "00900009327000008250400000", "0162103500000000"); // minR 7.5
cuts.AddCut("80000123", "00200079327000008250400000", "0162103500000000"); // single pT 0. GeV/c
cuts.AddCut("80000123", "00200019327000008250400000", "0162103500000000"); // single pT 0.1 GeV/c
} else if (trainConfig == 123) { // TPC cluster & edEdx var add sig
cuts.AddCut("80000123", "00200008327000008250400000", "0162103500000000"); // TPC Cluster 0.35
cuts.AddCut("80000123", "00200006327000008250400000", "0162103500000000"); // TPC Cluster 0.7
cuts.AddCut("80000123", "00200009227000008250400000", "0162103500000000"); // edEdx -3,5
cuts.AddCut("80000123", "00200009627000008250400000", "0162103500000000"); // edEdx -2.5,4
cuts.AddCut("80000123", "00200009127000008250400000", "0162103500000000"); // edEdx -5,5
} else if (trainConfig == 124) { //PidEdx Variation
cuts.AddCut("80000123", "00200009357000008250400000", "0162103500000000"); // PidEdx(2, >0.4GeV)
cuts.AddCut("80000123", "00200009387300008250400000", "0162103500000000"); // PidEdx(2, >0.4GeV; 1>3.5GeV)
cuts.AddCut("80000123", "00200009320000008250400000", "0162103500000000"); // PidEdx(1, >0.5GeV)
cuts.AddCut("80000123", "00200009325000008250400000", "0162103500000000"); // PidEdx(1, >0.3GeV)
} else if (trainConfig == 125) { //PidEdx Variation 2
cuts.AddCut("80000123", "00200009327300008250400000", "0162103500000000"); // PidEdx(1, >0.4GeV; -10>3.5GeV)
cuts.AddCut("80000123", "00200009326000008250400000", "0162103500000000"); // PidEdx(1, >0.25GeV)
cuts.AddCut("80000123", "00200009326200008250400000", "0162103500000000"); // PidEdx(1, >0.25GeV; -10>4GeV)
cuts.AddCut("80000123", "00200009327200008250400000", "0162103500000000"); // PidEdx(1, >0.4GeV; -10>4GeV)
} else if (trainConfig == 126) { // qt & psipair variation
cuts.AddCut("80000123", "00200009327000003250400000", "0162103500000000"); // qT 0.05 1D
cuts.AddCut("80000123", "00200009327000009250400000", "0162103500000000"); // qT 0.03 2D
cuts.AddCut("80000123", "00200009327000002250400000", "0162103500000000"); // qT 0.07 1D
cuts.AddCut("80000123", "00200009327000008240400000", "0162103500000000"); // Psi Pair: 1D 0.2
} else if (trainConfig == 127) { // PsiPair Variation
cuts.AddCut("80000123", "00200009327000008210400000", "0162103500000000"); // Psi Pair: 1D 0.1
cuts.AddCut("80000123", "00200009327000008150400000", "0162103500000000"); // chi2 50 2D
cuts.AddCut("80000123", "00200009327000008850400000", "0162103500000000"); // chi2 20 2D
cuts.AddCut("80000123", "00200009327000008260400000", "0162103500000000"); // psi pair 0.05
} else if (trainConfig == 128) { // cos point & meson alpha variation
cuts.AddCut("80000123", "00200009327000008250300000", "0162103500000000"); // cos pointing angle 0.75
cuts.AddCut("80000123", "00200009327000008250600000", "0162103500000000"); // cos pointing angle 0.9
cuts.AddCut("80000123", "00200009327000008250400000", "0162106500000000"); // alpha meson cut 0.8
} else if (trainConfig == 129) { // BG mixing & smear variations
cuts.AddCut("80000123", "00200009327000008250400000", "0262103500000000"); // BG track multiplicity
cuts.AddCut("80000123", "00200009327000008250400000", "0162103500800000"); // fPSigSmearingCte=0.014;
cuts.AddCut("80000123", "00200009327000008250400000", "0162103500900000"); // fPSigSmearingCte=0.014;
// pseudorapidity studies
//-----------------------------------------------------------------------
} else if (trainConfig == 130) {
cuts.AddCut("80000113", "0a200009327000008250400000", "0162103500000000"); //Eta cut -0.9 - -0.2 and 0.2 - 0.9
cuts.AddCut("80000113", "0b200009327000008250400000", "0162103500000000"); //Eta cut -0.9 - -0.2 and 0.2 - 0.9 with LineCut
} else if (trainConfig == 131) {
cuts.AddCut("80000123", "0a200009327000008250400000", "0162103500000000"); //Eta cut -0.9 - -0.2 and 0.2 - 0.9 Added Signals
cuts.AddCut("80000123", "0b200009327000008250400000", "0162103500000000"); //Eta cut -0.9 - -0.2 and 0.2 - 0.9 Added Signals
//--------------------------------------------------------------------------
// purity studies (kappa cut)
//--------------------------------------------------------------------------
} else if (trainConfig == 150) {
cuts.AddCut("80000113", "00200009300000008250400000", "0162103500000000"); // -3 < kappa < 5
cuts.AddCut("80000113", "00200009500000008250400000", "0162103500000000"); // -5 < kappa < 10
cuts.AddCut("80000113", "00200009600000008250400000", "0162103500000000"); // -3 < kappa < 10
cuts.AddCut("80000113", "00200009700000008250400000", "0162103500000000"); // 0 < kappa < 10
} else if (trainConfig == 152) {
cuts.AddCut("80200113", "00200009300000008250400000", "0162103500000000"); // -3 < kappa < 5
cuts.AddCut("80200113", "00200009500000008250400000", "0162103500000000"); // -5 < kappa < 10
cuts.AddCut("80200113", "00200009600000008250400000", "0162103500000000"); // -3 < kappa < 10
cuts.AddCut("80200113", "00200009700000008250400000", "0162103500000000"); // 0 < kappa < 10
} else if (trainConfig == 153) {
cuts.AddCut("82400113", "00200009300000008250400000", "0162103500000000"); // -3 < kappa < 5
cuts.AddCut("82400113", "00200009500000008250400000", "0162103500000000"); // -5 < kappa < 10
cuts.AddCut("82400113", "00200009600000008250400000", "0162103500000000"); // -3 < kappa < 10
cuts.AddCut("82400113", "00200009700000008250400000", "0162103500000000"); // 0 < kappa < 10
} else if (trainConfig == 154) {
cuts.AddCut("84600113", "00200009300000008250400000", "0162103500000000"); // -3 < kappa < 5
cuts.AddCut("84600113", "00200009500000008250400000", "0162103500000000"); // -5 < kappa < 10
cuts.AddCut("84600113", "00200009600000008250400000", "0162103500000000"); // -3 < kappa < 10
cuts.AddCut("84600113", "00200009700000008250400000", "0162103500000000"); // 0 < kappa < 10
} else if (trainConfig == 155) {
cuts.AddCut("86000113", "00200009300000008250400000", "0162103500000000"); // -3 < kappa < 5
cuts.AddCut("86000113", "00200009500000008250400000", "0162103500000000"); // -5 < kappa < 10
cuts.AddCut("86000113", "00200009600000008250400000", "0162103500000000"); // -3 < kappa < 10
cuts.AddCut("86000113", "00200009700000008250400000", "0162103500000000"); // 0 < kappa < 10
//--------------------------------------------------------------------------
// Material weight studies
//--------------------------------------------------------------------------
// standard cuts
} else if (trainConfig == 200) {
cuts.AddCut("80000113", "00200009327000008250404000", "0162103500000000");
} else if (trainConfig == 201) {
cuts.AddCut("80000113", "00200009327000008250404000", "0162103500000000");
} else if (trainConfig == 202) {
cuts.AddCut("80000113", "00200009327000008250404000", "0162103500000000");
// standard cuts added signals
} else if (trainConfig == 210) {
cuts.AddCut("80000123", "00200009327000008250404000", "0162103500000000");
} else if (trainConfig == 211) {
cuts.AddCut("80000123", "00200009327000008250404000", "0162103500000000");
} else if (trainConfig == 212) {
cuts.AddCut("80000123", "00200009327000008250404000", "0162103500000000");
//--------------------------------------------------------------------------
// 2016 pPb w/o past future protection
//--------------------------------------------------------------------------
// Min Bias
} else if (trainConfig == 300) {
cuts.AddCut("80010113", "00200009397302001280004000", "0162103500000000"); // Min Bias
cuts.AddCut("80010113", "00200009397302001280004000", "0162101500000000"); // Min Bias , alpha pT dependent
// TRD trigger
} else if (trainConfig == 301) {
cuts.AddCut("80047113", "00200009397302001280004000", "0162103500000000"); // TRD trigger HQU for 8TeV
cuts.AddCut("80043113", "00200009397302001280004000", "0162103500000000"); // TRD trigger HSE for 8TeV
// Calo triggers
} else if (trainConfig == 302) { // EMC triggers
cuts.AddCut("80000113", "00200009327000008250404000", "0162103500000000", "1111100007032230000"); // Min Bias
cuts.AddCut("80052113", "00200009327000008250404000", "0162103500000000", "1111100007032230000"); // EMC7
cuts.AddCut("80085113", "00200009327000008250404000", "0162103500000000", "1111100007032230000"); // EG2
cuts.AddCut("80083113", "00200009327000008250404000", "0162103500000000", "1111100007032230000"); // EG1
} else if (trainConfig == 303) { // PHOS triggers
cuts.AddCut("80000113", "00200009327000008250404000", "0162103500000000", "2444400041013200000"); // MinBias
cuts.AddCut("80052113", "00200009327000008250404000", "0162103500000000", "2444400041013200000"); // PHI7
//
} else if (trainConfig == 304) {
cuts.AddCut("80010113", "00200009327000008250404000", "0162103500000000"); // new default for 5TeV
cuts.AddCut("80110113", "00200009327000008250404000", "0162103500000000"); // 0-10
cuts.AddCut("81210113", "00200009327000008250404000", "0162103500000000"); // 0-20
cuts.AddCut("82410113", "00200009327000008250404000", "0162103500000000"); // 20-40
cuts.AddCut("84610113", "00200009327000008250404000", "0162103500000000"); // 40-60
cuts.AddCut("86810113", "00200009327000008250404000", "0162103500000000"); // 60-80
cuts.AddCut("88010113", "00200009327000008250404000", "0162103500000000"); // 80-100
} else if (trainConfig == 305){ // pPb 2013 TeV defaults
cuts.AddCut("80010113", "00200009327000008250400000", "0162103500000000"); // 0-100
cuts.AddCut("80110113", "00200009327000008250400000", "0162103500000000"); // 0-10
cuts.AddCut("81210113", "00200009327000008250400000", "0162103500000000"); // 10-20
cuts.AddCut("82410113", "00200009327000008250400000", "0162103500000000"); // 20-40
cuts.AddCut("84610113", "00200009327000008250400000", "0162103500000000"); // 40-60
cuts.AddCut("86810113", "00200009327000008250400000", "0162103500000000"); // 60-80
cuts.AddCut("88010113", "00200009327000008250400000", "0162103500000000"); // 80-100
//--------------------------------------------------------------------------
// 2016 pPb w/ past future protection 2.24 \mus protected
//--------------------------------------------------------------------------
// Min Bias
} else if (trainConfig == 310) {
cuts.AddCut("80010213", "00200009397302001280004000", "0162103500000000"); // Min Bias
cuts.AddCut("80010213", "00200009397302001280004000", "0162101500000000"); // Min Bias , alpha pT dependent
// TRD trigger
} else if (trainConfig == 311) {
cuts.AddCut("80047213", "00200009397302001280004000", "0162103500000000"); // TRD trigger HQU for 8TeV
cuts.AddCut("80043213", "00200009397302001280004000", "0162103500000000"); // TRD trigger HSE for 8TeV
// Calo triggers
} else if (trainConfig == 312) { // EMC triggers
cuts.AddCut("80000213", "00200009327000008250404000", "0162103500000000", "1111100007032230000"); // Min Bias
cuts.AddCut("80052213", "00200009327000008250404000", "0162103500000000", "1111100007032230000"); // EMC7
cuts.AddCut("80085213", "00200009327000008250404000", "0162103500000000", "1111100007032230000"); // EG2
cuts.AddCut("80083213", "00200009327000008250404000", "0162103500000000", "1111100007032230000"); // EG1
} else if (trainConfig == 313) { // PHOS triggers
cuts.AddCut("80000213", "00200009327000008250404000", "0162103500000000", "2444400041013200000"); // MinBias
cuts.AddCut("80052213", "00200009327000008250404000", "0162103500000000", "2444400041013200000"); // PHI7
} else if (trainConfig == 314) {
cuts.AddCut("80010213", "00200009327000008250404000", "0162103500000000"); // new default for 5TeV
cuts.AddCut("80010213", "00200009327000008250404000", "0162101500000000"); // new default, alpha pT dependent for 5TeV
} else {
Error(Form("GammaConvV1_%i",trainConfig), "wrong trainConfig variable no cuts have been specified for the configuration");
return;
}
if(!cuts.AreValid()){
cout << "\n\n****************************************************" << endl;
cout << "ERROR: No valid cuts stored in CutHandlerConv! Returning..." << endl;
cout << "****************************************************\n\n" << endl;
return;
}
Int_t numberOfCuts = cuts.GetNCuts();
TList *EventCutList = new TList();
TList *ConvCutList = new TList();
TList *MesonCutList = new TList();
TList *ClusterCutList = new TList();
TList *HeaderList = new TList();
if (doWeightingPart==1) {
TObjString *Header1 = new TObjString("pi0_1");
HeaderList->Add(Header1);
}
if (doWeightingPart==2){
TObjString *Header3 = new TObjString("eta_2");
HeaderList->Add(Header3);
}
if (doWeightingPart==3) {
TObjString *Header1 = new TObjString("pi0_1");
HeaderList->Add(Header1);
TObjString *Header3 = new TObjString("eta_2");
HeaderList->Add(Header3);
}
Bool_t doWeighting = kFALSE;
if (doWeightingPart == 1 || doWeightingPart == 2 || doWeightingPart == 3) doWeighting = kTRUE;
EventCutList->SetOwner(kTRUE);
AliConvEventCuts **analysisEventCuts = new AliConvEventCuts*[numberOfCuts];
ConvCutList->SetOwner(kTRUE);
AliConversionPhotonCuts **analysisCuts = new AliConversionPhotonCuts*[numberOfCuts];
MesonCutList->SetOwner(kTRUE);
AliConversionMesonCuts **analysisMesonCuts = new AliConversionMesonCuts*[numberOfCuts];
ClusterCutList->SetOwner(kTRUE);
AliCaloPhotonCuts **analysisClusterCuts = new AliCaloPhotonCuts*[numberOfCuts];
Bool_t enableClustersForTrigger = kFALSE;
Bool_t initializedMatBudWeigths_existing = kFALSE;
if (doWeighting) Printf("weighting has been switched on");
for(Int_t i = 0; i<numberOfCuts; i++){
cout << "initialization of cutnumber: " << i << endl;
analysisEventCuts[i] = new AliConvEventCuts();
if ( trainConfig == 1 || trainConfig == 2 || trainConfig == 5 || trainConfig == 6 ||
( trainConfig > 99 && trainConfig < 120 ) ||
( trainConfig > 199 && trainConfig < 210 ) ){
if (doWeighting){
if (generatorName.CompareTo("DPMJET")==0){
analysisEventCuts[i]->SetUseReweightingWithHistogramFromFile(kTRUE, kTRUE, kFALSE, fileNameInputForWeighting, "Pi0_DPMJET_LHC13b2_efix_pPb_5023GeV_MBV0A",
"Eta_DPMJET_LHC13b2_efix_pPb_5023GeV_MBV0A", "","Pi0_Fit_Data_pPb_5023GeV_MBV0A","Eta_Fit_Data_pPb_5023GeV_MBV0A");
} else if (generatorName.CompareTo("HIJING")==0){
analysisEventCuts[i]->SetUseReweightingWithHistogramFromFile(kTRUE, kTRUE, kFALSE, fileNameInputForWeighting, "Pi0_Hijing_LHC13e7_pPb_5023GeV_MBV0A",
"Eta_Hijing_LHC13e7_pPb_5023GeV_MBV0A", "","Pi0_Fit_Data_pPb_5023GeV_MBV0A","Eta_Fit_Data_pPb_5023GeV_MBV0A");
}
}
}
if ( trainConfig == 3 || trainConfig == 4 ||
( trainConfig > 119 && trainConfig < 140 ) ||
( trainConfig > 209 && trainConfig < 220 ) ){
if (doWeighting){
analysisEventCuts[i]->SetUseReweightingWithHistogramFromFile(kTRUE, kTRUE, kFALSE, fileNameInputForWeighting, "Pi0_Hijing_LHC13e7_addSig_pPb_5023GeV_MBV0A",
"Eta_Hijing_LHC13e7_addSig_pPb_5023GeV_MBV0A", "","Pi0_Fit_Data_pPb_5023GeV_MBV0A","Eta_Fit_Data_pPb_5023GeV_MBV0A");
}
}
TString dataInputMultHisto = "";
TString mcInputMultHisto = "";
TString triggerString = (cuts.GetEventCut(i)).Data();
triggerString = triggerString(3,2);
dataInputMultHisto = Form("%s_%s", periodNameAnchor.Data(), triggerString.Data());
mcInputMultHisto = Form("%s_%s", periodNameV0Reader.Data(), triggerString.Data());
if (doMultiplicityWeighting){
cout << "enabling mult weighting" << endl;
analysisEventCuts[i]->SetUseWeightMultiplicityFromFile( kTRUE, fileNameInputForMultWeighing, dataInputMultHisto, mcInputMultHisto );
}
if (debugLevel > 0) analysisEventCuts[i]->SetDebugLevel(debugLevel);
analysisEventCuts[i]->SetTriggerMimicking(enableTriggerMimicking);
analysisEventCuts[i]->SetTriggerOverlapRejecion(enableTriggerOverlapRej);
analysisEventCuts[i]->SetMaxFacPtHard(maxFacPtHard);
analysisEventCuts[i]->SetV0ReaderName(V0ReaderName);
if (periodNameV0Reader.CompareTo("") != 0) analysisEventCuts[i]->SetPeriodEnum(periodNameV0Reader);
analysisEventCuts[i]->SetLightOutput(runLightOutput);
analysisEventCuts[i]->InitializeCutsFromCutString((cuts.GetEventCut(i)).Data());
if (doEtaShiftIndCuts) {
analysisEventCuts[i]->DoEtaShift(doEtaShiftIndCuts);
analysisEventCuts[i]->SetEtaShift(stringShift);
}
EventCutList->Add(analysisEventCuts[i]);
analysisEventCuts[i]->SetFillCutHistograms("",kFALSE);
cout << "initialized event cut: " << (cuts.GetEventCut(i)).Data() << endl;
if ( trainConfig == 302 || trainConfig == 303 || trainConfig == 312 || trainConfig == 313 ){
TString caloCutPos = cuts.GetClusterCut(i);
caloCutPos.Resize(1);
TString TrackMatcherName = Form("CaloTrackMatcher_%s",caloCutPos.Data());
if( !(AliCaloTrackMatcher*)mgr->GetTask(TrackMatcherName.Data()) ){
AliCaloTrackMatcher* fTrackMatcher = new AliCaloTrackMatcher(TrackMatcherName.Data(),caloCutPos.Atoi());
fTrackMatcher->SetV0ReaderName(V0ReaderName);
mgr->AddTask(fTrackMatcher);
mgr->ConnectInput(fTrackMatcher,0,cinput);
}
enableClustersForTrigger = kTRUE;
analysisClusterCuts[i] = new AliCaloPhotonCuts();
analysisClusterCuts[i]->SetV0ReaderName(V0ReaderName);
analysisClusterCuts[i]->SetLightOutput(runLightOutput);
analysisClusterCuts[i]->InitializeCutsFromCutString((cuts.GetClusterCut(i)).Data());
ClusterCutList->Add(analysisClusterCuts[i]);
analysisClusterCuts[i]->SetFillCutHistograms("");
}
analysisCuts[i] = new AliConversionPhotonCuts();
if ( trainConfig > 149 && trainConfig < 156 ){
analysisCuts[i]->SetSwitchToKappaInsteadOfNSigdEdxTPC(kTRUE);
}
if (enableMatBudWeightsPi0 > 0){
if (isMC > 0){
if (analysisCuts[i]->InitializeMaterialBudgetWeights(enableMatBudWeightsPi0,filenameMatBudWeights)){
initializedMatBudWeigths_existing = kTRUE;}
else {cout << "ERROR The initialization of the materialBudgetWeights did not work out." << endl;}
} else {cout << "ERROR 'enableMatBudWeightsPi0'-flag was set > 0 even though this is not a MC task. It was automatically reset to 0." << endl;}
}
analysisCuts[i]->SetV0ReaderName(V0ReaderName);
analysisCuts[i]->SetLightOutput(runLightOutput);
analysisCuts[i]->InitializeCutsFromCutString((cuts.GetPhotonCut(i)).Data());
analysisCuts[i]->SetIsHeavyIon(isHeavyIon);
ConvCutList->Add(analysisCuts[i]);
analysisCuts[i]->SetFillCutHistograms("",kFALSE);
cout << "initialized photon cut: " << (cuts.GetPhotonCut(i)).Data() << endl;
analysisMesonCuts[i] = new AliConversionMesonCuts();
analysisMesonCuts[i]->SetLightOutput(runLightOutput);
analysisMesonCuts[i]->InitializeCutsFromCutString((cuts.GetMesonCut(i)).Data());
MesonCutList->Add(analysisMesonCuts[i]);
analysisMesonCuts[i]->SetFillCutHistograms("");
analysisEventCuts[i]->SetAcceptedHeader(HeaderList);
cout << "initialized meson cut: " << (cuts.GetMesonCut(i)).Data() << endl;
}
task->SetDoTHnSparse(runTHnSparse);
task->SetEventCutList(numberOfCuts,EventCutList);
task->SetConversionCutList(numberOfCuts,ConvCutList);
task->SetMesonCutList(numberOfCuts,MesonCutList);
task->SetMoveParticleAccordingToVertex(kTRUE);
task->SetDoMesonAnalysis(kTRUE);
task->SetDoMesonQA(enableQAMesonTask); //Attention new switch for Pi0 QA
task->SetDoPhotonQA(enableQAPhotonTask); //Attention new switch small for Photon QA
task->SetDoPlotVsCentrality(enablePlotVsCentrality);
if (enableClustersForTrigger){
task->SetDoClusterSelectionForTriggerNorm(enableClustersForTrigger);
task->SetClusterCutList(numberOfCuts,ClusterCutList);
}
if (initializedMatBudWeigths_existing) {
task->SetDoMaterialBudgetWeightingOfGammasForTrueMesons(kTRUE);
}
//connect containers
AliAnalysisDataContainer *coutput =
mgr->CreateContainer(Form("GammaConvV1_%i",trainConfig), TList::Class(),
AliAnalysisManager::kOutputContainer,Form("GammaConvV1_%i.root",trainConfig));
mgr->AddTask(task);
mgr->ConnectInput(task,0,cinput);
mgr->ConnectOutput(task,1,coutput);
return;
}
| bsd-3-clause |
chromium/chromium | media/mojo/services/mojo_audio_output_stream_provider.cc | 3396 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/mojo/services/mojo_audio_output_stream_provider.h"
#include <utility>
#include "base/bind.h"
#include "build/build_config.h"
#include "media/mojo/mojom/audio_data_pipe.mojom.h"
#include "mojo/public/cpp/bindings/message.h"
namespace media {
MojoAudioOutputStreamProvider::MojoAudioOutputStreamProvider(
mojo::PendingReceiver<mojom::AudioOutputStreamProvider> pending_receiver,
CreateDelegateCallback create_delegate_callback,
DeleterCallback deleter_callback,
std::unique_ptr<media::mojom::AudioOutputStreamObserver> observer)
: receiver_(this, std::move(pending_receiver)),
create_delegate_callback_(std::move(create_delegate_callback)),
deleter_callback_(std::move(deleter_callback)),
observer_(std::move(observer)),
observer_receiver_(observer_.get()) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Unretained is safe since |this| owns |receiver_|.
receiver_.set_disconnect_handler(
base::BindOnce(&MojoAudioOutputStreamProvider::CleanUp,
base::Unretained(this), /*had_error*/ false));
DCHECK(create_delegate_callback_);
DCHECK(deleter_callback_);
}
MojoAudioOutputStreamProvider::~MojoAudioOutputStreamProvider() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}
void MojoAudioOutputStreamProvider::Acquire(
const AudioParameters& params,
mojo::PendingRemote<mojom::AudioOutputStreamProviderClient>
provider_client) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// |processing_id| gets dropped here. It's not supported outside of the audio
// service. As this class is slated for removal, it will not be updated to
// support audio processing.
#if !BUILDFLAG(IS_ANDROID)
if (params.IsBitstreamFormat()) {
// Bitstream streams are only supported on Android.
BadMessage(
"Attempted to acquire a bitstream audio stream on a platform where "
"it's not supported");
return;
}
#endif
if (audio_output_) {
BadMessage("Output acquired twice.");
return;
}
provider_client_.Bind(std::move(provider_client));
mojo::PendingRemote<mojom::AudioOutputStreamObserver> pending_observer;
observer_receiver_.Bind(pending_observer.InitWithNewPipeAndPassReceiver());
// Unretained is safe since |this| owns |audio_output_|.
audio_output_.emplace(
base::BindOnce(std::move(create_delegate_callback_), params,
std::move(pending_observer)),
base::BindOnce(&mojom::AudioOutputStreamProviderClient::Created,
base::Unretained(provider_client_.get())),
base::BindOnce(&MojoAudioOutputStreamProvider::CleanUp,
base::Unretained(this)));
}
void MojoAudioOutputStreamProvider::CleanUp(bool had_error) {
if (had_error) {
provider_client_.ResetWithReason(
static_cast<uint32_t>(media::mojom::AudioOutputStreamObserver::
DisconnectReason::kPlatformError),
std::string());
}
std::move(deleter_callback_).Run(this);
}
void MojoAudioOutputStreamProvider::BadMessage(const std::string& error) {
receiver_.ReportBadMessage(error);
std::move(deleter_callback_).Run(this); // deletes |this|.
}
} // namespace media
| bsd-3-clause |
chromium/chromium | third_party/tflite_support/src/tensorflow_lite_support/java/src/native/task/text/nlclassifier/nl_classifier_jni.cc | 6929 | /* Copyright 2020 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.
==============================================================================*/
#include <jni.h>
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/op_resolver.h"
#include "tensorflow_lite_support/cc/task/core/proto/base_options_proto_inc.h"
#include "tensorflow_lite_support/cc/task/text/nlclassifier/nl_classifier.h"
#include "tensorflow_lite_support/cc/utils/jni_utils.h"
#include "tensorflow_lite_support/java/src/native/task/text/nlclassifier/nl_classifier_jni_utils.h"
namespace tflite {
namespace task {
// To be provided by a link-time library
extern std::unique_ptr<OpResolver> CreateOpResolver();
} // namespace task
} // namespace tflite
namespace {
using ::tflite::support::utils::GetExceptionClassNameForStatusCode;
using ::tflite::support::utils::GetMappedFileBuffer;
using ::tflite::support::utils::JStringToString;
using ::tflite::support::utils::kInvalidPointer;
using ::tflite::support::utils::ThrowException;
using ::tflite::task::core::BaseOptions;
using ::tflite::task::text::NLClassifierOptions;
using ::tflite::task::text::nlclassifier::NLClassifier;
using ::tflite::task::text::nlclassifier::RunClassifier;
NLClassifierOptions ConvertToProtoOptions(JNIEnv* env,
jobject java_nl_classifier_options,
jlong base_options_handle) {
jclass nl_classifier_options_class = env->FindClass(
"org/tensorflow/lite/task/text/nlclassifier/"
"NLClassifier$NLClassifierOptions");
jmethodID input_tensor_index_method_id = env->GetMethodID(
nl_classifier_options_class, "getInputTensorIndex", "()I");
jmethodID output_score_tensor_index_method_id = env->GetMethodID(
nl_classifier_options_class, "getOutputScoreTensorIndex", "()I");
jmethodID output_label_tensor_index_method_id = env->GetMethodID(
nl_classifier_options_class, "getOutputLabelTensorIndex", "()I");
jmethodID input_tensor_name_method_id =
env->GetMethodID(nl_classifier_options_class, "getInputTensorName",
"()Ljava/lang/String;");
jmethodID output_score_tensor_name_method_id =
env->GetMethodID(nl_classifier_options_class, "getOutputScoreTensorName",
"()Ljava/lang/String;");
jmethodID output_label_tensor_name_method_id =
env->GetMethodID(nl_classifier_options_class, "getOutputLabelTensorName",
"()Ljava/lang/String;");
NLClassifierOptions proto_options;
if (base_options_handle != kInvalidPointer) {
// proto_options will free the previous base_options and set the new one.
proto_options.set_allocated_base_options(
reinterpret_cast<BaseOptions*>(base_options_handle));
}
proto_options.set_input_tensor_index(env->CallIntMethod(
java_nl_classifier_options, input_tensor_index_method_id));
proto_options.set_output_score_tensor_index(env->CallIntMethod(
java_nl_classifier_options, output_score_tensor_index_method_id));
proto_options.set_output_label_tensor_index(env->CallIntMethod(
java_nl_classifier_options, output_label_tensor_index_method_id));
proto_options.set_input_tensor_name(JStringToString(
env, (jstring)env->CallObjectMethod(java_nl_classifier_options,
input_tensor_name_method_id)));
proto_options.set_output_score_tensor_name(JStringToString(
env, (jstring)env->CallObjectMethod(java_nl_classifier_options,
output_score_tensor_name_method_id)));
proto_options.set_output_label_tensor_name(JStringToString(
env, (jstring)env->CallObjectMethod(java_nl_classifier_options,
output_label_tensor_name_method_id)));
return proto_options;
}
} // namespace
extern "C" JNIEXPORT void JNICALL
Java_org_tensorflow_lite_task_text_nlclassifier_NLClassifier_deinitJni(
JNIEnv* env,
jobject thiz,
jlong native_handle) {
delete reinterpret_cast<NLClassifier*>(native_handle);
}
extern "C" JNIEXPORT jlong JNICALL
Java_org_tensorflow_lite_task_text_nlclassifier_NLClassifier_initJniWithByteBuffer(
JNIEnv* env,
jclass thiz,
jobject nl_classifier_options,
jobject model_buffer,
jlong base_options_handle) {
auto model = GetMappedFileBuffer(env, model_buffer);
tflite::support::StatusOr<std::unique_ptr<NLClassifier>> classifier_or;
NLClassifierOptions proto_options =
ConvertToProtoOptions(env, nl_classifier_options, base_options_handle);
proto_options.mutable_base_options()->mutable_model_file()->set_file_content(
model.data(), model.size());
classifier_or = NLClassifier::CreateFromOptions(
proto_options, tflite::task::CreateOpResolver());
if (classifier_or.ok()) {
return reinterpret_cast<jlong>(classifier_or->release());
} else {
ThrowException(
env, GetExceptionClassNameForStatusCode(classifier_or.status().code()),
"Error occurred when initializing NLClassifier: %s",
classifier_or.status().message().data());
return kInvalidPointer;
}
}
extern "C" JNIEXPORT jlong JNICALL
Java_org_tensorflow_lite_task_text_nlclassifier_NLClassifier_initJniWithFileDescriptor(
JNIEnv* env,
jclass thiz,
jobject nl_classifier_options,
jint fd,
jlong base_options_handle) {
tflite::support::StatusOr<std::unique_ptr<NLClassifier>> classifier_or;
NLClassifierOptions proto_options =
ConvertToProtoOptions(env, nl_classifier_options, base_options_handle);
proto_options.mutable_base_options()
->mutable_model_file()
->mutable_file_descriptor_meta()
->set_fd(fd);
classifier_or = NLClassifier::CreateFromOptions(
proto_options, tflite::task::CreateOpResolver());
if (classifier_or.ok()) {
return reinterpret_cast<jlong>(classifier_or->release());
} else {
ThrowException(
env, GetExceptionClassNameForStatusCode(classifier_or.status().code()),
"Error occurred when initializing NLClassifier: %s",
classifier_or.status().message().data());
return kInvalidPointer;
}
}
extern "C" JNIEXPORT jobject JNICALL
Java_org_tensorflow_lite_task_text_nlclassifier_NLClassifier_classifyNative(
JNIEnv* env,
jclass thiz,
jlong native_handle,
jstring text) {
return RunClassifier(env, native_handle, text);
}
| bsd-3-clause |
Bysmyyr/blink-crosswalk | Source/core/page/PrintContextTest.cpp | 9353 | // 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 "config.h"
#include "core/page/PrintContext.h"
#include "core/dom/Document.h"
#include "core/frame/FrameHost.h"
#include "core/frame/FrameView.h"
#include "core/html/HTMLElement.h"
#include "core/html/HTMLIFrameElement.h"
#include "core/loader/EmptyClients.h"
#include "core/testing/DummyPageHolder.h"
#include "platform/graphics/GraphicsContext.h"
#include "platform/testing/SkiaForCoreTesting.h"
#include "platform/text/TextStream.h"
#include <gtest/gtest.h>
namespace blink {
const int kPageWidth = 800;
const int kPageHeight = 600;
class MockPrintContext : public PrintContext {
public:
MockPrintContext(LocalFrame* frame) : PrintContext(frame) { }
void outputLinkAndLinkedDestinations(GraphicsContext& context, const IntRect& pageRect)
{
PrintContext::outputLinkAndLinkedDestinations(context, pageRect);
}
};
class MockCanvas : public SkCanvas {
public:
enum OperationType {
DrawRect,
DrawPoint
};
struct Operation {
OperationType type;
SkRect rect;
};
MockCanvas() : SkCanvas(kPageWidth, kPageHeight) { }
virtual void onDrawRect(const SkRect& rect, const SkPaint& paint) override
{
ASSERT_TRUE(paint.getAnnotation());
Operation operation = { DrawRect, rect };
m_recordedOperations.append(operation);
}
virtual void onDrawPoints(PointMode mode, size_t count, const SkPoint pts[], const SkPaint& paint) override
{
ASSERT_EQ(1u, count); // Only called from drawPoint().
ASSERT_TRUE(paint.getAnnotation());
Operation operation = { DrawPoint, SkRect::MakeXYWH(pts[0].x(), pts[0].y(), 0, 0) };
m_recordedOperations.append(operation);
}
const Vector<Operation>& recordedOperations() const { return m_recordedOperations; }
private:
Vector<Operation> m_recordedOperations;
};
class PrintContextTest : public testing::Test {
protected:
PrintContextTest(PassOwnPtr<FrameLoaderClient> frameLoaderClient = PassOwnPtr<FrameLoaderClient>())
: m_pageHolder(DummyPageHolder::create(IntSize(kPageWidth, kPageHeight), nullptr, frameLoaderClient))
, m_printContext(adoptPtrWillBeNoop(new MockPrintContext(document().frame()))) { }
Document& document() const { return m_pageHolder->document(); }
MockPrintContext& printContext() { return *m_printContext.get(); }
void setBodyInnerHTML(String bodyContent)
{
document().body()->setInnerHTML(bodyContent, ASSERT_NO_EXCEPTION);
}
void printSinglePage(SkCanvas& canvas)
{
IntRect pageRect(0, 0, kPageWidth, kPageHeight);
OwnPtr<GraphicsContext> context = GraphicsContext::deprecatedCreateWithCanvas(&canvas);
printContext().begin(kPageWidth, kPageHeight);
printContext().outputLinkAndLinkedDestinations(*context, pageRect);
printContext().end();
}
static String htmlForLink(int x, int y, int width, int height, const char* url, const char* children = nullptr)
{
TextStream ts;
ts << "<a style='position: absolute; left: " << x << "px; top: " << y << "px; width: " << width << "px; height: " << height
<< "px' href='" << url << "'>" << (children ? children : url) << "</a>";
return ts.release();
}
static String htmlForAnchor(int x, int y, const char* name)
{
TextStream ts;
ts << "<a name='" << name << "' style='position: absolute; left: " << x << "px; top: " << y << "px'>" << name << "</a>";
return ts.release();
}
private:
OwnPtr<DummyPageHolder> m_pageHolder;
OwnPtrWillBePersistent<MockPrintContext> m_printContext;
};
class SingleChildFrameLoaderClient : public EmptyFrameLoaderClient {
public:
SingleChildFrameLoaderClient() : m_child(nullptr) { }
virtual Frame* firstChild() const override { return m_child; }
virtual Frame* lastChild() const override { return m_child; }
void setChild(Frame* child) { m_child = child; }
private:
Frame* m_child;
};
class FrameLoaderClientWithParent : public EmptyFrameLoaderClient {
public:
FrameLoaderClientWithParent(Frame* parent) : m_parent(parent) { }
virtual Frame* parent() const override { return m_parent; }
private:
Frame* m_parent;
};
class PrintContextFrameTest : public PrintContextTest {
public:
PrintContextFrameTest() : PrintContextTest(adoptPtr(new SingleChildFrameLoaderClient())) { }
};
#define EXPECT_SKRECT_EQ(expectedX, expectedY, expectedWidth, expectedHeight, actualRect) \
EXPECT_EQ(expectedX, actualRect.x()); \
EXPECT_EQ(expectedY, actualRect.y()); \
EXPECT_EQ(expectedWidth, actualRect.width()); \
EXPECT_EQ(expectedHeight, actualRect.height());
TEST_F(PrintContextTest, LinkTarget)
{
MockCanvas canvas;
setBodyInnerHTML(htmlForLink(50, 60, 70, 80, "http://www.google.com")
+ htmlForLink(150, 160, 170, 180, "http://www.google.com#fragment"));
printSinglePage(canvas);
const Vector<MockCanvas::Operation>& operations = canvas.recordedOperations();
ASSERT_EQ(2u, operations.size());
// The items in the result can be in any sequence.
size_t firstIndex = operations[0].rect.x() == 50 ? 0 : 1;
EXPECT_EQ(MockCanvas::DrawRect, operations[firstIndex].type);
EXPECT_SKRECT_EQ(50, 60, 70, 80, operations[firstIndex].rect);
// We should also check if the annotation is correct but Skia doesn't export
// SkAnnotation API.
size_t secondIndex = firstIndex == 0 ? 1 : 0;
EXPECT_EQ(MockCanvas::DrawRect, operations[secondIndex].type);
EXPECT_SKRECT_EQ(150, 160, 170, 180, operations[secondIndex].rect);
}
TEST_F(PrintContextTest, LinkedTarget)
{
MockCanvas canvas;
document().setBaseURLOverride(KURL(ParsedURLString, "http://a.com/"));
setBodyInnerHTML(htmlForLink(50, 60, 70, 80, "#fragment") // Generates a Link_Named_Dest_Key annotation
+ htmlForLink(150, 160, 170, 180, "#not-found") // Generates no annotation
+ htmlForAnchor(250, 260, "fragment") // Generates a Define_Named_Dest_Key annotation
+ htmlForAnchor(350, 360, "fragment-not-used")); // Generates no annotation
printSinglePage(canvas);
const Vector<MockCanvas::Operation>& operations = canvas.recordedOperations();
ASSERT_EQ(2u, operations.size());
size_t firstIndex = operations[0].rect.x() == 50 ? 0 : 1;
EXPECT_EQ(MockCanvas::DrawRect, operations[firstIndex].type);
EXPECT_SKRECT_EQ(50, 60, 70, 80, operations[firstIndex].rect);
size_t secondIndex = firstIndex == 0 ? 1 : 0;
EXPECT_EQ(MockCanvas::DrawPoint, operations[secondIndex].type);
EXPECT_SKRECT_EQ(250, 260, 0, 0, operations[secondIndex].rect);
}
TEST_F(PrintContextTest, LinkTargetBoundingBox)
{
MockCanvas canvas;
setBodyInnerHTML(htmlForLink(50, 60, 70, 20, "http://www.google.com", "<img style='width: 200px; height: 100px'>"));
printSinglePage(canvas);
const Vector<MockCanvas::Operation>& operations = canvas.recordedOperations();
ASSERT_EQ(1u, operations.size());
EXPECT_EQ(MockCanvas::DrawRect, operations[0].type);
EXPECT_SKRECT_EQ(50, 60, 200, 100, operations[0].rect);
}
TEST_F(PrintContextFrameTest, WithSubframe)
{
MockCanvas canvas;
document().setBaseURLOverride(KURL(ParsedURLString, "http://a.com/"));
setBodyInnerHTML("<iframe id='frame' src='http://b.com/' width='500' height='500'"
" style='border-width: 5px; margin: 5px; position: absolute; top: 90px; left: 90px'></iframe>");
HTMLIFrameElement& iframe = *toHTMLIFrameElement(document().getElementById("frame"));
OwnPtr<FrameLoaderClient> frameLoaderClient = adoptPtr(new FrameLoaderClientWithParent(document().frame()));
RefPtrWillBePersistent<LocalFrame> subframe = LocalFrame::create(frameLoaderClient.get(), document().frame()->host(), &iframe);
subframe->setView(FrameView::create(subframe.get(), IntSize(500, 500)));
subframe->init();
static_cast<SingleChildFrameLoaderClient*>(document().frame()->client())->setChild(subframe.get());
document().frame()->host()->incrementSubframeCount();
Document& frameDocument = *iframe.contentDocument();
frameDocument.setBaseURLOverride(KURL(ParsedURLString, "http://b.com/"));
frameDocument.body()->setInnerHTML(htmlForLink(50, 60, 70, 80, "#fragment")
+ htmlForLink(150, 160, 170, 180, "http://www.google.com")
+ htmlForLink(250, 260, 270, 280, "http://www.google.com#fragment"),
ASSERT_NO_EXCEPTION);
printSinglePage(canvas);
const Vector<MockCanvas::Operation>& operations = canvas.recordedOperations();
ASSERT_EQ(2u, operations.size());
size_t firstIndex = operations[0].rect.x() == 250 ? 0 : 1;
EXPECT_EQ(MockCanvas::DrawRect, operations[firstIndex].type);
EXPECT_SKRECT_EQ(250, 260, 170, 180, operations[firstIndex].rect);
size_t secondIndex = firstIndex == 0 ? 1 : 0;
EXPECT_EQ(MockCanvas::DrawRect, operations[secondIndex].type);
EXPECT_SKRECT_EQ(350, 360, 270, 280, operations[secondIndex].rect);
subframe->detach();
static_cast<SingleChildFrameLoaderClient*>(document().frame()->client())->setChild(nullptr);
document().frame()->host()->decrementSubframeCount();
}
} // namespace blink
| bsd-3-clause |
mbeccati/phpunit | src/Framework/TestSize/Known.php | 641 | <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\TestSize;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
* @psalm-immutable
*/
abstract class Known extends TestSize
{
/**
* @psalm-assert-if-true Known $this
*/
public function isKnown(): bool
{
return true;
}
abstract public function isGreaterThan(self $other): bool;
}
| bsd-3-clause |
Hankuo/color-emoji.skia | src/gpu/GrPathUtils.cpp | 17813 |
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrPathUtils.h"
#include "GrPoint.h"
#include "SkGeometry.h"
SkScalar GrPathUtils::scaleToleranceToSrc(SkScalar devTol,
const SkMatrix& viewM,
const GrRect& pathBounds) {
// In order to tesselate the path we get a bound on how much the matrix can
// stretch when mapping to screen coordinates.
SkScalar stretch = viewM.getMaxStretch();
SkScalar srcTol = devTol;
if (stretch < 0) {
// take worst case mapRadius amoung four corners.
// (less than perfect)
for (int i = 0; i < 4; ++i) {
SkMatrix mat;
mat.setTranslate((i % 2) ? pathBounds.fLeft : pathBounds.fRight,
(i < 2) ? pathBounds.fTop : pathBounds.fBottom);
mat.postConcat(viewM);
stretch = SkMaxScalar(stretch, mat.mapRadius(SK_Scalar1));
}
}
srcTol = SkScalarDiv(srcTol, stretch);
return srcTol;
}
static const int MAX_POINTS_PER_CURVE = 1 << 10;
static const SkScalar gMinCurveTol = SkFloatToScalar(0.0001f);
uint32_t GrPathUtils::quadraticPointCount(const GrPoint points[],
SkScalar tol) {
if (tol < gMinCurveTol) {
tol = gMinCurveTol;
}
GrAssert(tol > 0);
SkScalar d = points[1].distanceToLineSegmentBetween(points[0], points[2]);
if (d <= tol) {
return 1;
} else {
// Each time we subdivide, d should be cut in 4. So we need to
// subdivide x = log4(d/tol) times. x subdivisions creates 2^(x)
// points.
// 2^(log4(x)) = sqrt(x);
int temp = SkScalarCeil(SkScalarSqrt(SkScalarDiv(d, tol)));
int pow2 = GrNextPow2(temp);
// Because of NaNs & INFs we can wind up with a degenerate temp
// such that pow2 comes out negative. Also, our point generator
// will always output at least one pt.
if (pow2 < 1) {
pow2 = 1;
}
return GrMin(pow2, MAX_POINTS_PER_CURVE);
}
}
uint32_t GrPathUtils::generateQuadraticPoints(const GrPoint& p0,
const GrPoint& p1,
const GrPoint& p2,
SkScalar tolSqd,
GrPoint** points,
uint32_t pointsLeft) {
if (pointsLeft < 2 ||
(p1.distanceToLineSegmentBetweenSqd(p0, p2)) < tolSqd) {
(*points)[0] = p2;
*points += 1;
return 1;
}
GrPoint q[] = {
{ SkScalarAve(p0.fX, p1.fX), SkScalarAve(p0.fY, p1.fY) },
{ SkScalarAve(p1.fX, p2.fX), SkScalarAve(p1.fY, p2.fY) },
};
GrPoint r = { SkScalarAve(q[0].fX, q[1].fX), SkScalarAve(q[0].fY, q[1].fY) };
pointsLeft >>= 1;
uint32_t a = generateQuadraticPoints(p0, q[0], r, tolSqd, points, pointsLeft);
uint32_t b = generateQuadraticPoints(r, q[1], p2, tolSqd, points, pointsLeft);
return a + b;
}
uint32_t GrPathUtils::cubicPointCount(const GrPoint points[],
SkScalar tol) {
if (tol < gMinCurveTol) {
tol = gMinCurveTol;
}
GrAssert(tol > 0);
SkScalar d = GrMax(
points[1].distanceToLineSegmentBetweenSqd(points[0], points[3]),
points[2].distanceToLineSegmentBetweenSqd(points[0], points[3]));
d = SkScalarSqrt(d);
if (d <= tol) {
return 1;
} else {
int temp = SkScalarCeil(SkScalarSqrt(SkScalarDiv(d, tol)));
int pow2 = GrNextPow2(temp);
// Because of NaNs & INFs we can wind up with a degenerate temp
// such that pow2 comes out negative. Also, our point generator
// will always output at least one pt.
if (pow2 < 1) {
pow2 = 1;
}
return GrMin(pow2, MAX_POINTS_PER_CURVE);
}
}
uint32_t GrPathUtils::generateCubicPoints(const GrPoint& p0,
const GrPoint& p1,
const GrPoint& p2,
const GrPoint& p3,
SkScalar tolSqd,
GrPoint** points,
uint32_t pointsLeft) {
if (pointsLeft < 2 ||
(p1.distanceToLineSegmentBetweenSqd(p0, p3) < tolSqd &&
p2.distanceToLineSegmentBetweenSqd(p0, p3) < tolSqd)) {
(*points)[0] = p3;
*points += 1;
return 1;
}
GrPoint q[] = {
{ SkScalarAve(p0.fX, p1.fX), SkScalarAve(p0.fY, p1.fY) },
{ SkScalarAve(p1.fX, p2.fX), SkScalarAve(p1.fY, p2.fY) },
{ SkScalarAve(p2.fX, p3.fX), SkScalarAve(p2.fY, p3.fY) }
};
GrPoint r[] = {
{ SkScalarAve(q[0].fX, q[1].fX), SkScalarAve(q[0].fY, q[1].fY) },
{ SkScalarAve(q[1].fX, q[2].fX), SkScalarAve(q[1].fY, q[2].fY) }
};
GrPoint s = { SkScalarAve(r[0].fX, r[1].fX), SkScalarAve(r[0].fY, r[1].fY) };
pointsLeft >>= 1;
uint32_t a = generateCubicPoints(p0, q[0], r[0], s, tolSqd, points, pointsLeft);
uint32_t b = generateCubicPoints(s, r[1], q[2], p3, tolSqd, points, pointsLeft);
return a + b;
}
int GrPathUtils::worstCasePointCount(const SkPath& path, int* subpaths,
SkScalar tol) {
if (tol < gMinCurveTol) {
tol = gMinCurveTol;
}
GrAssert(tol > 0);
int pointCount = 0;
*subpaths = 1;
bool first = true;
SkPath::Iter iter(path, false);
SkPath::Verb verb;
GrPoint pts[4];
while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
switch (verb) {
case SkPath::kLine_Verb:
pointCount += 1;
break;
case SkPath::kQuad_Verb:
pointCount += quadraticPointCount(pts, tol);
break;
case SkPath::kCubic_Verb:
pointCount += cubicPointCount(pts, tol);
break;
case SkPath::kMove_Verb:
pointCount += 1;
if (!first) {
++(*subpaths);
}
break;
default:
break;
}
first = false;
}
return pointCount;
}
void GrPathUtils::QuadUVMatrix::set(const GrPoint qPts[3]) {
// can't make this static, no cons :(
SkMatrix UVpts;
#ifndef SK_SCALAR_IS_FLOAT
GrCrash("Expected scalar is float.");
#endif
SkMatrix m;
// We want M such that M * xy_pt = uv_pt
// We know M * control_pts = [0 1/2 1]
// [0 0 1]
// [1 1 1]
// We invert the control pt matrix and post concat to both sides to get M.
UVpts.setAll(0, SK_ScalarHalf, SK_Scalar1,
0, 0, SK_Scalar1,
SkScalarToPersp(SK_Scalar1),
SkScalarToPersp(SK_Scalar1),
SkScalarToPersp(SK_Scalar1));
m.setAll(qPts[0].fX, qPts[1].fX, qPts[2].fX,
qPts[0].fY, qPts[1].fY, qPts[2].fY,
SkScalarToPersp(SK_Scalar1),
SkScalarToPersp(SK_Scalar1),
SkScalarToPersp(SK_Scalar1));
if (!m.invert(&m)) {
// The quad is degenerate. Hopefully this is rare. Find the pts that are
// farthest apart to compute a line (unless it is really a pt).
SkScalar maxD = qPts[0].distanceToSqd(qPts[1]);
int maxEdge = 0;
SkScalar d = qPts[1].distanceToSqd(qPts[2]);
if (d > maxD) {
maxD = d;
maxEdge = 1;
}
d = qPts[2].distanceToSqd(qPts[0]);
if (d > maxD) {
maxD = d;
maxEdge = 2;
}
// We could have a tolerance here, not sure if it would improve anything
if (maxD > 0) {
// Set the matrix to give (u = 0, v = distance_to_line)
GrVec lineVec = qPts[(maxEdge + 1)%3] - qPts[maxEdge];
// when looking from the point 0 down the line we want positive
// distances to be to the left. This matches the non-degenerate
// case.
lineVec.setOrthog(lineVec, GrPoint::kLeft_Side);
lineVec.dot(qPts[0]);
// first row
fM[0] = 0;
fM[1] = 0;
fM[2] = 0;
// second row
fM[3] = lineVec.fX;
fM[4] = lineVec.fY;
fM[5] = -lineVec.dot(qPts[maxEdge]);
} else {
// It's a point. It should cover zero area. Just set the matrix such
// that (u, v) will always be far away from the quad.
fM[0] = 0; fM[1] = 0; fM[2] = 100.f;
fM[3] = 0; fM[4] = 0; fM[5] = 100.f;
}
} else {
m.postConcat(UVpts);
// The matrix should not have perspective.
SkDEBUGCODE(static const SkScalar gTOL = SkFloatToScalar(1.f / 100.f));
GrAssert(SkScalarAbs(m.get(SkMatrix::kMPersp0)) < gTOL);
GrAssert(SkScalarAbs(m.get(SkMatrix::kMPersp1)) < gTOL);
// It may not be normalized to have 1.0 in the bottom right
float m33 = m.get(SkMatrix::kMPersp2);
if (1.f != m33) {
m33 = 1.f / m33;
fM[0] = m33 * m.get(SkMatrix::kMScaleX);
fM[1] = m33 * m.get(SkMatrix::kMSkewX);
fM[2] = m33 * m.get(SkMatrix::kMTransX);
fM[3] = m33 * m.get(SkMatrix::kMSkewY);
fM[4] = m33 * m.get(SkMatrix::kMScaleY);
fM[5] = m33 * m.get(SkMatrix::kMTransY);
} else {
fM[0] = m.get(SkMatrix::kMScaleX);
fM[1] = m.get(SkMatrix::kMSkewX);
fM[2] = m.get(SkMatrix::kMTransX);
fM[3] = m.get(SkMatrix::kMSkewY);
fM[4] = m.get(SkMatrix::kMScaleY);
fM[5] = m.get(SkMatrix::kMTransY);
}
}
}
namespace {
// a is the first control point of the cubic.
// ab is the vector from a to the second control point.
// dc is the vector from the fourth to the third control point.
// d is the fourth control point.
// p is the candidate quadratic control point.
// this assumes that the cubic doesn't inflect and is simple
bool is_point_within_cubic_tangents(const SkPoint& a,
const SkVector& ab,
const SkVector& dc,
const SkPoint& d,
SkPath::Direction dir,
const SkPoint p) {
SkVector ap = p - a;
SkScalar apXab = ap.cross(ab);
if (SkPath::kCW_Direction == dir) {
if (apXab > 0) {
return false;
}
} else {
GrAssert(SkPath::kCCW_Direction == dir);
if (apXab < 0) {
return false;
}
}
SkVector dp = p - d;
SkScalar dpXdc = dp.cross(dc);
if (SkPath::kCW_Direction == dir) {
if (dpXdc < 0) {
return false;
}
} else {
GrAssert(SkPath::kCCW_Direction == dir);
if (dpXdc > 0) {
return false;
}
}
return true;
}
void convert_noninflect_cubic_to_quads(const SkPoint p[4],
SkScalar toleranceSqd,
bool constrainWithinTangents,
SkPath::Direction dir,
SkTArray<SkPoint, true>* quads,
int sublevel = 0) {
// Notation: Point a is always p[0]. Point b is p[1] unless p[1] == p[0], in which case it is
// p[2]. Point d is always p[3]. Point c is p[2] unless p[2] == p[3], in which case it is p[1].
SkVector ab = p[1] - p[0];
SkVector dc = p[2] - p[3];
if (ab.isZero()) {
if (dc.isZero()) {
SkPoint* degQuad = quads->push_back_n(3);
degQuad[0] = p[0];
degQuad[1] = p[0];
degQuad[2] = p[3];
return;
}
ab = p[2] - p[0];
}
if (dc.isZero()) {
dc = p[1] - p[3];
}
// When the ab and cd tangents are nearly parallel with vector from d to a the constraint that
// the quad point falls between the tangents becomes hard to enforce and we are likely to hit
// the max subdivision count. However, in this case the cubic is approaching a line and the
// accuracy of the quad point isn't so important. We check if the two middle cubic control
// points are very close to the baseline vector. If so then we just pick quadratic points on the
// control polygon.
if (constrainWithinTangents) {
SkVector da = p[0] - p[3];
SkScalar invDALengthSqd = da.lengthSqd();
if (invDALengthSqd > SK_ScalarNearlyZero) {
invDALengthSqd = SkScalarInvert(invDALengthSqd);
// cross(ab, da)^2/length(da)^2 == sqd distance from b to line from d to a.
// same goed for point c using vector cd.
SkScalar detABSqd = ab.cross(da);
detABSqd = SkScalarSquare(detABSqd);
SkScalar detDCSqd = dc.cross(da);
detDCSqd = SkScalarSquare(detDCSqd);
if (SkScalarMul(detABSqd, invDALengthSqd) < toleranceSqd &&
SkScalarMul(detDCSqd, invDALengthSqd) < toleranceSqd) {
SkPoint b = p[0] + ab;
SkPoint c = p[3] + dc;
SkPoint mid = b + c;
mid.scale(SK_ScalarHalf);
// Insert two quadratics to cover the case when ab points away from d and/or dc
// points away from a.
if (SkVector::DotProduct(da, dc) < 0 || SkVector::DotProduct(ab,da) > 0) {
SkPoint* qpts = quads->push_back_n(6);
qpts[0] = p[0];
qpts[1] = b;
qpts[2] = mid;
qpts[3] = mid;
qpts[4] = c;
qpts[5] = p[3];
} else {
SkPoint* qpts = quads->push_back_n(3);
qpts[0] = p[0];
qpts[1] = mid;
qpts[2] = p[3];
}
return;
}
}
}
static const SkScalar kLengthScale = 3 * SK_Scalar1 / 2;
static const int kMaxSubdivs = 10;
ab.scale(kLengthScale);
dc.scale(kLengthScale);
// e0 and e1 are extrapolations along vectors ab and dc.
SkVector c0 = p[0];
c0 += ab;
SkVector c1 = p[3];
c1 += dc;
SkScalar dSqd = sublevel > kMaxSubdivs ? 0 : c0.distanceToSqd(c1);
if (dSqd < toleranceSqd) {
SkPoint cAvg = c0;
cAvg += c1;
cAvg.scale(SK_ScalarHalf);
bool subdivide = false;
if (constrainWithinTangents &&
!is_point_within_cubic_tangents(p[0], ab, dc, p[3], dir, cAvg)) {
// choose a new cAvg that is the intersection of the two tangent lines.
ab.setOrthog(ab);
SkScalar z0 = -ab.dot(p[0]);
dc.setOrthog(dc);
SkScalar z1 = -dc.dot(p[3]);
cAvg.fX = SkScalarMul(ab.fY, z1) - SkScalarMul(z0, dc.fY);
cAvg.fY = SkScalarMul(z0, dc.fX) - SkScalarMul(ab.fX, z1);
SkScalar z = SkScalarMul(ab.fX, dc.fY) - SkScalarMul(ab.fY, dc.fX);
z = SkScalarInvert(z);
cAvg.fX *= z;
cAvg.fY *= z;
if (sublevel <= kMaxSubdivs) {
SkScalar d0Sqd = c0.distanceToSqd(cAvg);
SkScalar d1Sqd = c1.distanceToSqd(cAvg);
// We need to subdivide if d0 + d1 > tolerance but we have the sqd values. We know
// the distances and tolerance can't be negative.
// (d0 + d1)^2 > toleranceSqd
// d0Sqd + 2*d0*d1 + d1Sqd > toleranceSqd
SkScalar d0d1 = SkScalarSqrt(SkScalarMul(d0Sqd, d1Sqd));
subdivide = 2 * d0d1 + d0Sqd + d1Sqd > toleranceSqd;
}
}
if (!subdivide) {
SkPoint* pts = quads->push_back_n(3);
pts[0] = p[0];
pts[1] = cAvg;
pts[2] = p[3];
return;
}
}
SkPoint choppedPts[7];
SkChopCubicAtHalf(p, choppedPts);
convert_noninflect_cubic_to_quads(choppedPts + 0,
toleranceSqd,
constrainWithinTangents,
dir,
quads,
sublevel + 1);
convert_noninflect_cubic_to_quads(choppedPts + 3,
toleranceSqd,
constrainWithinTangents,
dir,
quads,
sublevel + 1);
}
}
void GrPathUtils::convertCubicToQuads(const GrPoint p[4],
SkScalar tolScale,
bool constrainWithinTangents,
SkPath::Direction dir,
SkTArray<SkPoint, true>* quads) {
SkPoint chopped[10];
int count = SkChopCubicAtInflections(p, chopped);
// base tolerance is 1 pixel.
static const SkScalar kTolerance = SK_Scalar1;
const SkScalar tolSqd = SkScalarSquare(SkScalarMul(tolScale, kTolerance));
for (int i = 0; i < count; ++i) {
SkPoint* cubic = chopped + 3*i;
convert_noninflect_cubic_to_quads(cubic, tolSqd, constrainWithinTangents, dir, quads);
}
}
| bsd-3-clause |
jondelmil/cookiecutter-django | {{cookiecutter.repo_name}}/Gruntfile.js | 3281 | module.exports = function (grunt) {
var appConfig = grunt.file.readJSON('package.json');
// Load grunt tasks automatically
// see: https://github.com/sindresorhus/load-grunt-tasks
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
// see: https://npmjs.org/package/time-grunt
require('time-grunt')(grunt);
var pathsConfig = function (appName) {
this.app = appName || appConfig.name;
return {
app: this.app,
templates: this.app + '/templates',
css: this.app + '/static/css',
sass: this.app + '/static/sass',
fonts: this.app + '/static/fonts',
images: this.app + '/static/images',
js: this.app + '/static/js',
manageScript: 'manage.py',
}
};
grunt.initConfig({
paths: pathsConfig(),
pkg: appConfig,
// see: https://github.com/gruntjs/grunt-contrib-watch
watch: {
gruntfile: {
files: ['Gruntfile.js']
},
sass: {
files: ['<%= paths.sass %>/**/*.{scss,sass}'],
tasks: ['sass:dev'],
options: {
atBegin: true
}
},
livereload: {
files: [
'<%= paths.js %>/**/*.js',
'<%= paths.sass %>/**/*.{scss,sass}',
'<%= paths.app %>/**/*.html'
],
options: {
spawn: false,
livereload: true,
},
},
},
// see: https://github.com/sindresorhus/grunt-sass
sass: {
dev: {
options: {
outputStyle: 'nested',
sourceMap: false,
precision: 10
},
files: {
'<%= paths.css %>/project.css': '<%= paths.sass %>/project.scss'
},
},
dist: {
options: {
outputStyle: 'compressed',
sourceMap: false,
precision: 10
},
files: {
'<%= paths.css %>/project.css': '<%= paths.sass %>/project.scss'
},
}
},
//see https://github.com/nDmitry/grunt-postcss
postcss: {
options: {
map: true, // inline sourcemaps
processors: [
require('pixrem')(), // add fallbacks for rem units
require('autoprefixer-core')({browsers: [
'Android 2.3',
'Android >= 4',
'Chrome >= 20',
'Firefox >= 24',
'Explorer >= 8',
'iOS >= 6',
'Opera >= 12',
'Safari >= 6'
]}), // add vendor prefixes
require('cssnano')() // minify the result
]
},
dist: {
src: '<%= paths.css %>/*.css'
}
},
// see: https://npmjs.org/package/grunt-bg-shell
bgShell: {
_defaults: {
bg: true
},
runDjango: {
cmd: 'python <%= paths.manageScript %> runserver'
},
{% if cookiecutter.use_mailhog == "y" -%}runMailHog: {
cmd: './mailhog'
},{%- endif %}
}
});
grunt.registerTask('serve', [
{% if cookiecutter.use_mailhog == "y" -%}
'bgShell:runMailHog',
{%- endif %}
'bgShell:runDjango',
'watch'
]);
grunt.registerTask('build', [
'sass:dist',
'postcss'
]);
grunt.registerTask('default', [
'build'
]);
};
| bsd-3-clause |
jp2masa/Cosmos | source/Archive/Cosmos.Kernel.Plugs/Interlocked.cs | 785 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cosmos.IL2CPU.Plugs;
namespace Cosmos.Kernel.Plugs
{
[Plug(Target = typeof(System.Threading.Interlocked))]
public static class Interlocked
{
public static object CompareExchange(ref object location1, object value, object comparand)
{
object xResult = null;
CPU.DisableInterrupts();
try
{
xResult = location1;
if (Object.ReferenceEquals(location1, comparand))
{
location1 = value;
}
}
finally
{
CPU.EnableInterrupts();
}
return xResult;
}
}
} | bsd-3-clause |
mkouhei/golang-ugorji-go-debian | codec/codecs_test.go | 27633 | // Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a BSD-style license found in the LICENSE file.
package codec
// Test works by using a slice of interfaces.
// It can test for encoding/decoding into/from a nil interface{}
// or passing the object to encode/decode into.
//
// There are basically 2 main tests here.
// First test internally encodes and decodes things and verifies that
// the artifact was as expected.
// Second test will use python msgpack to create a bunch of golden files,
// read those files, and compare them to what it should be. It then
// writes those files back out and compares the byte streams.
//
// Taken together, the tests are pretty extensive.
import (
"bytes"
"encoding/gob"
"flag"
"fmt"
"io/ioutil"
"math"
"net"
"net/rpc"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strconv"
"sync/atomic"
"testing"
"time"
)
type testVerifyArg int
const (
testVerifyMapTypeSame testVerifyArg = iota
testVerifyMapTypeStrIntf
testVerifyMapTypeIntfIntf
// testVerifySliceIntf
testVerifyForPython
)
var (
testInitDebug bool
testUseIoEncDec bool
testStructToArray bool
testWriteNoSymbols bool
_ = fmt.Printf
skipVerifyVal interface{} = &(struct{}{})
// For Go Time, do not use a descriptive timezone.
// It's unnecessary, and makes it harder to do a reflect.DeepEqual.
// The Offset already tells what the offset should be, if not on UTC and unknown zone name.
timeLoc = time.FixedZone("", -8*60*60) // UTC-08:00 //time.UTC-8
timeToCompare1 = time.Date(2012, 2, 2, 2, 2, 2, 2000, timeLoc)
timeToCompare2 = time.Date(1900, 2, 2, 2, 2, 2, 2000, timeLoc)
timeToCompare3 = time.Unix(0, 0).UTC()
timeToCompare4 = time.Time{}.UTC()
table []interface{} // main items we encode
tableVerify []interface{} // we verify encoded things against this after decode
tableTestNilVerify []interface{} // for nil interface, use this to verify (rules are different)
tablePythonVerify []interface{} // for verifying for python, since Python sometimes
// will encode a float32 as float64, or large int as uint
testRpcInt = new(TestRpcInt)
testMsgpackH = &MsgpackHandle{}
testBincH = &BincHandle{}
)
func testInitFlags() {
// delete(testDecOpts.ExtFuncs, timeTyp)
flag.BoolVar(&testInitDebug, "tg", false, "Test Debug")
flag.BoolVar(&testUseIoEncDec, "ti", false, "Use IO Reader/Writer for Marshal/Unmarshal")
flag.BoolVar(&testStructToArray, "ts", false, "Set StructToArray option")
flag.BoolVar(&testWriteNoSymbols, "tn", false, "Set NoSymbols option")
}
type AnonInTestStruc struct {
AS string
AI64 int64
AI16 int16
AUi64 uint64
ASslice []string
AI64slice []int64
}
type TestStruc struct {
S string
I64 int64
I16 int16
Ui64 uint64
Ui8 uint8
B bool
By byte
Sslice []string
I64slice []int64
I16slice []int16
Ui64slice []uint64
Ui8slice []uint8
Bslice []bool
Byslice []byte
Islice []interface{}
Iptrslice []*int64
AnonInTestStruc
//M map[interface{}]interface{} `json:"-",bson:"-"`
Ms map[string]interface{}
Msi64 map[string]int64
Nintf interface{} //don't set this, so we can test for nil
T time.Time
Nmap map[string]bool //don't set this, so we can test for nil
Nslice []byte //don't set this, so we can test for nil
Nint64 *int64 //don't set this, so we can test for nil
Mtsptr map[string]*TestStruc
Mts map[string]TestStruc
Its []*TestStruc
Nteststruc *TestStruc
}
type TestABC struct {
A, B, C string
}
type TestRpcInt struct {
i int
}
func (r *TestRpcInt) Update(n int, res *int) error { r.i = n; *res = r.i; return nil }
func (r *TestRpcInt) Square(ignore int, res *int) error { *res = r.i * r.i; return nil }
func (r *TestRpcInt) Mult(n int, res *int) error { *res = r.i * n; return nil }
func (r *TestRpcInt) EchoStruct(arg TestABC, res *string) error {
*res = fmt.Sprintf("%#v", arg)
return nil
}
func (r *TestRpcInt) Echo123(args []string, res *string) error {
*res = fmt.Sprintf("%#v", args)
return nil
}
func testVerifyVal(v interface{}, arg testVerifyArg) (v2 interface{}) {
//for python msgpack,
// - all positive integers are unsigned 64-bit ints
// - all floats are float64
switch iv := v.(type) {
case int8:
if iv > 0 {
v2 = uint64(iv)
} else {
v2 = int64(iv)
}
case int16:
if iv > 0 {
v2 = uint64(iv)
} else {
v2 = int64(iv)
}
case int32:
if iv > 0 {
v2 = uint64(iv)
} else {
v2 = int64(iv)
}
case int64:
if iv > 0 {
v2 = uint64(iv)
} else {
v2 = int64(iv)
}
case uint8:
v2 = uint64(iv)
case uint16:
v2 = uint64(iv)
case uint32:
v2 = uint64(iv)
case uint64:
v2 = uint64(iv)
case float32:
v2 = float64(iv)
case float64:
v2 = float64(iv)
case []interface{}:
m2 := make([]interface{}, len(iv))
for j, vj := range iv {
m2[j] = testVerifyVal(vj, arg)
}
v2 = m2
case map[string]bool:
switch arg {
case testVerifyMapTypeSame:
m2 := make(map[string]bool)
for kj, kv := range iv {
m2[kj] = kv
}
v2 = m2
case testVerifyMapTypeStrIntf, testVerifyForPython:
m2 := make(map[string]interface{})
for kj, kv := range iv {
m2[kj] = kv
}
v2 = m2
case testVerifyMapTypeIntfIntf:
m2 := make(map[interface{}]interface{})
for kj, kv := range iv {
m2[kj] = kv
}
v2 = m2
}
case map[string]interface{}:
switch arg {
case testVerifyMapTypeSame:
m2 := make(map[string]interface{})
for kj, kv := range iv {
m2[kj] = testVerifyVal(kv, arg)
}
v2 = m2
case testVerifyMapTypeStrIntf, testVerifyForPython:
m2 := make(map[string]interface{})
for kj, kv := range iv {
m2[kj] = testVerifyVal(kv, arg)
}
v2 = m2
case testVerifyMapTypeIntfIntf:
m2 := make(map[interface{}]interface{})
for kj, kv := range iv {
m2[kj] = testVerifyVal(kv, arg)
}
v2 = m2
}
case map[interface{}]interface{}:
m2 := make(map[interface{}]interface{})
for kj, kv := range iv {
m2[testVerifyVal(kj, arg)] = testVerifyVal(kv, arg)
}
v2 = m2
case time.Time:
switch arg {
case testVerifyForPython:
if iv2 := iv.UnixNano(); iv2 > 0 {
v2 = uint64(iv2)
} else {
v2 = int64(iv2)
}
default:
v2 = v
}
default:
v2 = v
}
return
}
func testInit() {
gob.Register(new(TestStruc))
if testInitDebug {
ts0 := newTestStruc(2, false)
fmt.Printf("====> depth: %v, ts: %#v\n", 2, ts0)
}
testBincH.StructToArray = testStructToArray
if testWriteNoSymbols {
testBincH.AsSymbols = AsSymbolNone
} else {
testBincH.AsSymbols = AsSymbolAll
}
testMsgpackH.StructToArray = testStructToArray
testMsgpackH.RawToString = true
// testMsgpackH.AddExt(byteSliceTyp, 0, testMsgpackH.BinaryEncodeExt, testMsgpackH.BinaryDecodeExt)
// testMsgpackH.AddExt(timeTyp, 1, testMsgpackH.TimeEncodeExt, testMsgpackH.TimeDecodeExt)
testMsgpackH.AddExt(timeTyp, 1,
func(rv reflect.Value) ([]byte, error) {
return encodeTime(rv.Interface().(time.Time)), nil
},
func(rv reflect.Value, bs []byte) error {
tt, err := decodeTime(bs)
if err == nil {
rv.Set(reflect.ValueOf(tt))
}
return err
},
)
primitives := []interface{}{
int8(-8),
int16(-1616),
int32(-32323232),
int64(-6464646464646464),
uint8(192),
uint16(1616),
uint32(32323232),
uint64(6464646464646464),
byte(192),
float32(-3232.0),
float64(-6464646464.0),
float32(3232.0),
float64(6464646464.0),
false,
true,
nil,
"someday",
"",
"bytestring",
timeToCompare1,
timeToCompare2,
timeToCompare3,
timeToCompare4,
}
mapsAndStrucs := []interface{}{
map[string]bool{
"true": true,
"false": false,
},
map[string]interface{}{
"true": "True",
"false": false,
"uint16(1616)": uint16(1616),
},
//add a complex combo map in here. (map has list which has map)
//note that after the first thing, everything else should be generic.
map[string]interface{}{
"list": []interface{}{
int16(1616),
int32(32323232),
true,
float32(-3232.0),
map[string]interface{}{
"TRUE": true,
"FALSE": false,
},
[]interface{}{true, false},
},
"int32": int32(32323232),
"bool": true,
"LONG STRING": "123456789012345678901234567890123456789012345678901234567890",
"SHORT STRING": "1234567890",
},
map[interface{}]interface{}{
true: "true",
uint8(138): false,
"false": uint8(200),
},
newTestStruc(0, false),
}
table = []interface{}{}
table = append(table, primitives...) //0-19 are primitives
table = append(table, primitives) //20 is a list of primitives
table = append(table, mapsAndStrucs...) //21-24 are maps. 25 is a *struct
tableVerify = make([]interface{}, len(table))
tableTestNilVerify = make([]interface{}, len(table))
tablePythonVerify = make([]interface{}, len(table))
lp := len(primitives)
av := tableVerify
for i, v := range table {
if i == lp+3 {
av[i] = skipVerifyVal
continue
}
//av[i] = testVerifyVal(v, testVerifyMapTypeSame)
switch v.(type) {
case []interface{}:
av[i] = testVerifyVal(v, testVerifyMapTypeSame)
case map[string]interface{}:
av[i] = testVerifyVal(v, testVerifyMapTypeSame)
case map[interface{}]interface{}:
av[i] = testVerifyVal(v, testVerifyMapTypeSame)
default:
av[i] = v
}
}
av = tableTestNilVerify
for i, v := range table {
if i > lp+3 {
av[i] = skipVerifyVal
continue
}
av[i] = testVerifyVal(v, testVerifyMapTypeStrIntf)
}
av = tablePythonVerify
for i, v := range table {
if i > lp+3 {
av[i] = skipVerifyVal
continue
}
av[i] = testVerifyVal(v, testVerifyForPython)
}
tablePythonVerify = tablePythonVerify[:24]
}
func testUnmarshal(v interface{}, data []byte, h Handle) error {
if testUseIoEncDec {
return NewDecoder(bytes.NewBuffer(data), h).Decode(v)
}
return NewDecoderBytes(data, h).Decode(v)
}
func testMarshal(v interface{}, h Handle) (bs []byte, err error) {
if testUseIoEncDec {
var buf bytes.Buffer
err = NewEncoder(&buf, h).Encode(v)
bs = buf.Bytes()
return
}
err = NewEncoderBytes(&bs, h).Encode(v)
return
}
func testMarshalErr(v interface{}, h Handle, t *testing.T, name string) (bs []byte, err error) {
if bs, err = testMarshal(v, h); err != nil {
logT(t, "Error encoding %s: %v, Err: %v", name, v, err)
t.FailNow()
}
return
}
func testUnmarshalErr(v interface{}, data []byte, h Handle, t *testing.T, name string) (err error) {
if err = testUnmarshal(v, data, h); err != nil {
logT(t, "Error Decoding into %s: %v, Err: %v", name, v, err)
t.FailNow()
}
return
}
func newTestStruc(depth int, bench bool) (ts *TestStruc) {
var i64a, i64b, i64c, i64d int64 = 64, 6464, 646464, 64646464
ts = &TestStruc{
S: "some string",
I64: math.MaxInt64 * 2 / 3, // 64,
I16: 16,
Ui64: uint64(int64(math.MaxInt64 * 2 / 3)), // 64, //don't use MaxUint64, as bson can't write it
Ui8: 160,
B: true,
By: 5,
Sslice: []string{"one", "two", "three"},
I64slice: []int64{1, 2, 3},
I16slice: []int16{4, 5, 6},
Ui64slice: []uint64{137, 138, 139},
Ui8slice: []uint8{210, 211, 212},
Bslice: []bool{true, false, true, false},
Byslice: []byte{13, 14, 15},
Islice: []interface{}{"true", true, "no", false, uint64(288), float64(0.4)},
Ms: map[string]interface{}{
"true": "true",
"int64(9)": false,
},
Msi64: map[string]int64{
"one": 1,
"two": 2,
},
T: timeToCompare1,
AnonInTestStruc: AnonInTestStruc{
AS: "A-String",
AI64: 64,
AI16: 16,
AUi64: 64,
ASslice: []string{"Aone", "Atwo", "Athree"},
AI64slice: []int64{1, 2, 3},
},
}
//For benchmarks, some things will not work.
if !bench {
//json and bson require string keys in maps
//ts.M = map[interface{}]interface{}{
// true: "true",
// int8(9): false,
//}
//gob cannot encode nil in element in array (encodeArray: nil element)
ts.Iptrslice = []*int64{nil, &i64a, nil, &i64b, nil, &i64c, nil, &i64d, nil}
// ts.Iptrslice = nil
}
if depth > 0 {
depth--
if ts.Mtsptr == nil {
ts.Mtsptr = make(map[string]*TestStruc)
}
if ts.Mts == nil {
ts.Mts = make(map[string]TestStruc)
}
ts.Mtsptr["0"] = newTestStruc(depth, bench)
ts.Mts["0"] = *(ts.Mtsptr["0"])
ts.Its = append(ts.Its, ts.Mtsptr["0"])
}
return
}
// doTestCodecTableOne allows us test for different variations based on arguments passed.
func doTestCodecTableOne(t *testing.T, testNil bool, h Handle,
vs []interface{}, vsVerify []interface{}) {
//if testNil, then just test for when a pointer to a nil interface{} is passed. It should work.
//Current setup allows us test (at least manually) the nil interface or typed interface.
logT(t, "================ TestNil: %v ================\n", testNil)
for i, v0 := range vs {
logT(t, "..............................................")
logT(t, " Testing: #%d:, %T, %#v\n", i, v0, v0)
b0, err := testMarshalErr(v0, h, t, "v0")
if err != nil {
continue
}
logT(t, " Encoded bytes: len: %v, %v\n", len(b0), b0)
var v1 interface{}
if testNil {
err = testUnmarshal(&v1, b0, h)
} else {
if v0 != nil {
v0rt := reflect.TypeOf(v0) // ptr
rv1 := reflect.New(v0rt)
err = testUnmarshal(rv1.Interface(), b0, h)
v1 = rv1.Elem().Interface()
// v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface()
}
}
logT(t, " v1 returned: %T, %#v", v1, v1)
// if v1 != nil {
// logT(t, " v1 returned: %T, %#v", v1, v1)
// //we always indirect, because ptr to typed value may be passed (if not testNil)
// v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface()
// }
if err != nil {
logT(t, "-------- Error: %v. Partial return: %v", err, v1)
failT(t)
continue
}
v0check := vsVerify[i]
if v0check == skipVerifyVal {
logT(t, " Nil Check skipped: Decoded: %T, %#v\n", v1, v1)
continue
}
if err = deepEqual(v0check, v1); err == nil {
logT(t, "++++++++ Before and After marshal matched\n")
} else {
logT(t, "-------- Before and After marshal do not match: Error: %v"+
" ====> GOLDEN: (%T) %#v, DECODED: (%T) %#v\n", err, v0check, v0check, v1, v1)
failT(t)
}
}
}
func testCodecTableOne(t *testing.T, h Handle) {
// func TestMsgpackAllExperimental(t *testing.T) {
// dopts := testDecOpts(nil, nil, false, true, true),
var oldWriteExt, oldRawToString bool
switch v := h.(type) {
case *MsgpackHandle:
oldWriteExt, v.WriteExt = v.WriteExt, true
oldRawToString, v.RawToString = v.RawToString, true
}
doTestCodecTableOne(t, false, h, table, tableVerify)
//if true { panic("") }
switch v := h.(type) {
case *MsgpackHandle:
v.WriteExt, v.RawToString = oldWriteExt, oldRawToString
}
// func TestMsgpackAll(t *testing.T) {
idxTime, numPrim, numMap := 19, 23, 4
//skip []interface{} containing time.Time
doTestCodecTableOne(t, false, h, table[:numPrim], tableVerify[:numPrim])
doTestCodecTableOne(t, false, h, table[numPrim+1:], tableVerify[numPrim+1:])
// func TestMsgpackNilStringMap(t *testing.T) {
var oldMapType reflect.Type
switch v := h.(type) {
case *MsgpackHandle:
oldMapType, v.MapType = v.MapType, mapStrIntfTyp
case *BincHandle:
oldMapType, v.MapType = v.MapType, mapStrIntfTyp
}
//skip time.Time, []interface{} containing time.Time, last map, and newStruc
doTestCodecTableOne(t, true, h, table[:idxTime], tableTestNilVerify[:idxTime])
doTestCodecTableOne(t, true, h, table[numPrim+1:numPrim+numMap], tableTestNilVerify[numPrim+1:numPrim+numMap])
switch v := h.(type) {
case *MsgpackHandle:
v.MapType = oldMapType
case *BincHandle:
v.MapType = oldMapType
}
// func TestMsgpackNilIntf(t *testing.T) {
//do newTestStruc and last element of map
doTestCodecTableOne(t, true, h, table[numPrim+numMap:], tableTestNilVerify[numPrim+numMap:])
//TODO? What is this one?
//doTestCodecTableOne(t, true, h, table[17:18], tableTestNilVerify[17:18])
}
func testCodecMiscOne(t *testing.T, h Handle) {
b, err := testMarshalErr(32, h, t, "32")
// Cannot do this nil one, because faster type assertion decoding will panic
// var i *int32
// if err = testUnmarshal(b, i, nil); err == nil {
// logT(t, "------- Expecting error because we cannot unmarshal to int32 nil ptr")
// t.FailNow()
// }
var i2 int32 = 0
err = testUnmarshalErr(&i2, b, h, t, "int32-ptr")
if i2 != int32(32) {
logT(t, "------- didn't unmarshal to 32: Received: %d", i2)
t.FailNow()
}
// func TestMsgpackDecodePtr(t *testing.T) {
ts := newTestStruc(0, false)
b, err = testMarshalErr(ts, h, t, "pointer-to-struct")
if len(b) < 40 {
logT(t, "------- Size must be > 40. Size: %d", len(b))
t.FailNow()
}
logT(t, "------- b: %v", b)
ts2 := new(TestStruc)
err = testUnmarshalErr(ts2, b, h, t, "pointer-to-struct")
if ts2.I64 != math.MaxInt64*2/3 {
logT(t, "------- Unmarshal wrong. Expect I64 = 64. Got: %v", ts2.I64)
t.FailNow()
}
// func TestMsgpackIntfDecode(t *testing.T) {
m := map[string]int{"A": 2, "B": 3}
p := []interface{}{m}
bs, err := testMarshalErr(p, h, t, "p")
m2 := map[string]int{}
p2 := []interface{}{m2}
err = testUnmarshalErr(&p2, bs, h, t, "&p2")
if m2["A"] != 2 || m2["B"] != 3 {
logT(t, "m2 not as expected: expecting: %v, got: %v", m, m2)
t.FailNow()
}
// log("m: %v, m2: %v, p: %v, p2: %v", m, m2, p, p2)
checkEqualT(t, p, p2, "p=p2")
checkEqualT(t, m, m2, "m=m2")
if err = deepEqual(p, p2); err == nil {
logT(t, "p and p2 match")
} else {
logT(t, "Not Equal: %v. p: %v, p2: %v", err, p, p2)
t.FailNow()
}
if err = deepEqual(m, m2); err == nil {
logT(t, "m and m2 match")
} else {
logT(t, "Not Equal: %v. m: %v, m2: %v", err, m, m2)
t.FailNow()
}
// func TestMsgpackDecodeStructSubset(t *testing.T) {
// test that we can decode a subset of the stream
mm := map[string]interface{}{"A": 5, "B": 99, "C": 333}
bs, err = testMarshalErr(mm, h, t, "mm")
type ttt struct {
A uint8
C int32
}
var t2 ttt
testUnmarshalErr(&t2, bs, h, t, "t2")
t3 := ttt{5, 333}
checkEqualT(t, t2, t3, "t2=t3")
// println(">>>>>")
// test simple arrays, non-addressable arrays, slices
type tarr struct {
A int64
B [3]int64
C []byte
D [3]byte
}
var tarr0 = tarr{1, [3]int64{2, 3, 4}, []byte{4, 5, 6}, [3]byte{7, 8, 9}}
// test both pointer and non-pointer (value)
for _, tarr1 := range []interface{}{tarr0, &tarr0} {
bs, err = testMarshalErr(tarr1, h, t, "tarr1")
var tarr2 tarr
testUnmarshalErr(&tarr2, bs, h, t, "tarr2")
checkEqualT(t, tarr0, tarr2, "tarr0=tarr2")
// fmt.Printf(">>>> err: %v. tarr1: %v, tarr2: %v\n", err, tarr0, tarr2)
}
// test byte array, even if empty (msgpack only)
if h == testMsgpackH {
type ystruct struct {
Anarray []byte
}
var ya = ystruct{}
testUnmarshalErr(&ya, []byte{0x91, 0x90}, h, t, "ya")
}
}
func testCodecEmbeddedPointer(t *testing.T, h Handle) {
type Z int
type A struct {
AnInt int
}
type B struct {
*Z
*A
MoreInt int
}
var z Z = 4
x1 := &B{&z, &A{5}, 6}
bs, err := testMarshalErr(x1, h, t, "x1")
// fmt.Printf("buf: len(%v): %x\n", buf.Len(), buf.Bytes())
var x2 = new(B)
err = testUnmarshalErr(x2, bs, h, t, "x2")
err = checkEqualT(t, x1, x2, "x1=x2")
_ = err
}
func doTestRpcOne(t *testing.T, rr Rpc, h Handle, doRequest bool, exitSleepMs time.Duration,
) (port int) {
// rpc needs EOF, which is sent via a panic, and so must be recovered.
if !recoverPanicToErr {
logT(t, "EXPECTED. set recoverPanicToErr=true, since rpc needs EOF")
t.FailNow()
}
srv := rpc.NewServer()
srv.Register(testRpcInt)
ln, err := net.Listen("tcp", "127.0.0.1:0")
// log("listener: %v", ln.Addr())
checkErrT(t, err)
port = (ln.Addr().(*net.TCPAddr)).Port
// var opts *DecoderOptions
// opts := testDecOpts
// opts.MapType = mapStrIntfTyp
// opts.RawToString = false
serverExitChan := make(chan bool, 1)
var serverExitFlag uint64 = 0
serverFn := func() {
for {
conn1, err1 := ln.Accept()
// if err1 != nil {
// //fmt.Printf("accept err1: %v\n", err1)
// continue
// }
if atomic.LoadUint64(&serverExitFlag) == 1 {
serverExitChan <- true
conn1.Close()
return // exit serverFn goroutine
}
if err1 == nil {
var sc rpc.ServerCodec = rr.ServerCodec(conn1, h)
srv.ServeCodec(sc)
}
}
}
clientFn := func(cc rpc.ClientCodec) {
cl := rpc.NewClientWithCodec(cc)
defer cl.Close()
var up, sq, mult int
var rstr string
// log("Calling client")
checkErrT(t, cl.Call("TestRpcInt.Update", 5, &up))
// log("Called TestRpcInt.Update")
checkEqualT(t, testRpcInt.i, 5, "testRpcInt.i=5")
checkEqualT(t, up, 5, "up=5")
checkErrT(t, cl.Call("TestRpcInt.Square", 1, &sq))
checkEqualT(t, sq, 25, "sq=25")
checkErrT(t, cl.Call("TestRpcInt.Mult", 20, &mult))
checkEqualT(t, mult, 100, "mult=100")
checkErrT(t, cl.Call("TestRpcInt.EchoStruct", TestABC{"Aa", "Bb", "Cc"}, &rstr))
checkEqualT(t, rstr, fmt.Sprintf("%#v", TestABC{"Aa", "Bb", "Cc"}), "rstr=")
checkErrT(t, cl.Call("TestRpcInt.Echo123", []string{"A1", "B2", "C3"}, &rstr))
checkEqualT(t, rstr, fmt.Sprintf("%#v", []string{"A1", "B2", "C3"}), "rstr=")
}
connFn := func() (bs net.Conn) {
// log("calling f1")
bs, err2 := net.Dial(ln.Addr().Network(), ln.Addr().String())
//fmt.Printf("f1. bs: %v, err2: %v\n", bs, err2)
checkErrT(t, err2)
return
}
exitFn := func() {
atomic.StoreUint64(&serverExitFlag, 1)
bs := connFn()
<-serverExitChan
bs.Close()
// serverExitChan <- true
}
go serverFn()
runtime.Gosched()
//time.Sleep(100 * time.Millisecond)
if exitSleepMs == 0 {
defer ln.Close()
defer exitFn()
}
if doRequest {
bs := connFn()
cc := rr.ClientCodec(bs, h)
clientFn(cc)
}
if exitSleepMs != 0 {
go func() {
defer ln.Close()
time.Sleep(exitSleepMs)
exitFn()
}()
}
return
}
// Comprehensive testing that generates data encoded from python msgpack,
// and validates that our code can read and write it out accordingly.
// We keep this unexported here, and put actual test in ext_dep_test.go.
// This way, it can be excluded by excluding file completely.
func doTestMsgpackPythonGenStreams(t *testing.T) {
logT(t, "TestPythonGenStreams")
tmpdir, err := ioutil.TempDir("", "golang-msgpack-test")
if err != nil {
logT(t, "-------- Unable to create temp directory\n")
t.FailNow()
}
defer os.RemoveAll(tmpdir)
logT(t, "tmpdir: %v", tmpdir)
cmd := exec.Command("python", "msgpack_test.py", "testdata", tmpdir)
//cmd.Stdin = strings.NewReader("some input")
//cmd.Stdout = &out
var cmdout []byte
if cmdout, err = cmd.CombinedOutput(); err != nil {
logT(t, "-------- Error running msgpack_test.py testdata. Err: %v", err)
logT(t, " %v", string(cmdout))
t.FailNow()
}
oldMapType := testMsgpackH.MapType
for i, v := range tablePythonVerify {
testMsgpackH.MapType = oldMapType
//load up the golden file based on number
//decode it
//compare to in-mem object
//encode it again
//compare to output stream
logT(t, "..............................................")
logT(t, " Testing: #%d: %T, %#v\n", i, v, v)
var bss []byte
bss, err = ioutil.ReadFile(filepath.Join(tmpdir, strconv.Itoa(i)+".golden"))
if err != nil {
logT(t, "-------- Error reading golden file: %d. Err: %v", i, err)
failT(t)
continue
}
testMsgpackH.MapType = mapStrIntfTyp
var v1 interface{}
if err = testUnmarshal(&v1, bss, testMsgpackH); err != nil {
logT(t, "-------- Error decoding stream: %d: Err: %v", i, err)
failT(t)
continue
}
if v == skipVerifyVal {
continue
}
//no need to indirect, because we pass a nil ptr, so we already have the value
//if v1 != nil { v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface() }
if err = deepEqual(v, v1); err == nil {
logT(t, "++++++++ Objects match")
} else {
logT(t, "-------- Objects do not match: %v. Source: %T. Decoded: %T", err, v, v1)
logT(t, "-------- AGAINST: %#v", v)
logT(t, "-------- DECODED: %#v <====> %#v", v1, reflect.Indirect(reflect.ValueOf(v1)).Interface())
failT(t)
}
bsb, err := testMarshal(v1, testMsgpackH)
if err != nil {
logT(t, "Error encoding to stream: %d: Err: %v", i, err)
failT(t)
continue
}
if err = deepEqual(bsb, bss); err == nil {
logT(t, "++++++++ Bytes match")
} else {
logT(t, "???????? Bytes do not match. %v.", err)
xs := "--------"
if reflect.ValueOf(v).Kind() == reflect.Map {
xs = " "
logT(t, "%s It's a map. Ok that they don't match (dependent on ordering).", xs)
} else {
logT(t, "%s It's not a map. They should match.", xs)
failT(t)
}
logT(t, "%s FROM_FILE: %4d] %v", xs, len(bss), bss)
logT(t, "%s ENCODED: %4d] %v", xs, len(bsb), bsb)
}
}
testMsgpackH.MapType = oldMapType
}
// To test MsgpackSpecRpc, we test 3 scenarios:
// - Go Client to Go RPC Service (contained within TestMsgpackRpcSpec)
// - Go client to Python RPC Service (contained within doTestMsgpackRpcSpecGoClientToPythonSvc)
// - Python Client to Go RPC Service (contained within doTestMsgpackRpcSpecPythonClientToGoSvc)
//
// This allows us test the different calling conventions
// - Go Service requires only one argument
// - Python Service allows multiple arguments
func doTestMsgpackRpcSpecGoClientToPythonSvc(t *testing.T) {
openPort := "6789"
cmd := exec.Command("python", "msgpack_test.py", "rpc-server", openPort, "2")
checkErrT(t, cmd.Start())
time.Sleep(100 * time.Millisecond) // time for python rpc server to start
bs, err2 := net.Dial("tcp", ":"+openPort)
checkErrT(t, err2)
cc := MsgpackSpecRpc.ClientCodec(bs, testMsgpackH)
cl := rpc.NewClientWithCodec(cc)
defer cl.Close()
var rstr string
checkErrT(t, cl.Call("EchoStruct", TestABC{"Aa", "Bb", "Cc"}, &rstr))
//checkEqualT(t, rstr, "{'A': 'Aa', 'B': 'Bb', 'C': 'Cc'}")
var mArgs MsgpackSpecRpcMultiArgs = []interface{}{"A1", "B2", "C3"}
checkErrT(t, cl.Call("Echo123", mArgs, &rstr))
checkEqualT(t, rstr, "1:A1 2:B2 3:C3", "rstr=")
}
func doTestMsgpackRpcSpecPythonClientToGoSvc(t *testing.T) {
port := doTestRpcOne(t, MsgpackSpecRpc, testMsgpackH, false, 1*time.Second)
//time.Sleep(1000 * time.Millisecond)
cmd := exec.Command("python", "msgpack_test.py", "rpc-client-go-service", strconv.Itoa(port))
var cmdout []byte
var err error
if cmdout, err = cmd.CombinedOutput(); err != nil {
logT(t, "-------- Error running msgpack_test.py rpc-client-go-service. Err: %v", err)
logT(t, " %v", string(cmdout))
t.FailNow()
}
checkEqualT(t, string(cmdout),
fmt.Sprintf("%#v\n%#v\n", []string{"A1", "B2", "C3"}, TestABC{"Aa", "Bb", "Cc"}), "cmdout=")
}
func TestMsgpackCodecsTable(t *testing.T) {
testCodecTableOne(t, testMsgpackH)
}
func TestMsgpackCodecsMisc(t *testing.T) {
testCodecMiscOne(t, testMsgpackH)
}
func TestMsgpackCodecsEmbeddedPointer(t *testing.T) {
testCodecEmbeddedPointer(t, testMsgpackH)
}
func TestBincCodecsTable(t *testing.T) {
testCodecTableOne(t, testBincH)
}
func TestBincCodecsMisc(t *testing.T) {
testCodecMiscOne(t, testBincH)
}
func TestBincCodecsEmbeddedPointer(t *testing.T) {
testCodecEmbeddedPointer(t, testBincH)
}
func TestMsgpackRpcGo(t *testing.T) {
doTestRpcOne(t, GoRpc, testMsgpackH, true, 0)
}
func TestMsgpackRpcSpec(t *testing.T) {
doTestRpcOne(t, MsgpackSpecRpc, testMsgpackH, true, 0)
}
func TestBincRpcGo(t *testing.T) {
doTestRpcOne(t, GoRpc, testBincH, true, 0)
}
// TODO:
// Add Tests for:
// - decoding empty list/map in stream into a nil slice/map
// - binary(M|Unm)arsher support for time.Time
| bsd-3-clause |
pozdnyakov/chromium-crosswalk | content/renderer/cpp_bound_class_unittest.cc | 7592 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Tests for CppBoundClass, in conjunction with CppBindingExample. Binds
// a CppBindingExample class into JavaScript in a custom test shell and tests
// the binding from the outside by loading JS into the shell.
#include "base/strings/utf_string_conversions.h"
#include "content/public/renderer/render_view_observer.h"
#include "content/public/test/render_view_test.h"
#include "third_party/WebKit/public/platform/WebURLRequest.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebElement.h"
#include "webkit/renderer/cpp_binding_example.h"
using webkit_glue::CppArgumentList;
using webkit_glue::CppBindingExample;
using webkit_glue::CppVariant;
namespace content {
class CppBindingExampleSubObject : public CppBindingExample {
public:
CppBindingExampleSubObject() {
sub_value_.Set("sub!");
BindProperty("sub_value", &sub_value_);
}
private:
CppVariant sub_value_;
};
class CppBindingExampleWithOptionalFallback : public CppBindingExample {
public:
CppBindingExampleWithOptionalFallback() {
BindProperty("sub_object", sub_object_.GetAsCppVariant());
}
void set_fallback_method_enabled(bool state) {
BindFallbackCallback(state ?
base::Bind(&CppBindingExampleWithOptionalFallback::fallbackMethod,
base::Unretained(this))
: CppBoundClass::Callback());
}
// The fallback method does nothing, but because of it the JavaScript keeps
// running when a nonexistent method is called on an object.
void fallbackMethod(const CppArgumentList& args, CppVariant* result) {
}
private:
CppBindingExampleSubObject sub_object_;
};
class TestObserver : public RenderViewObserver {
public:
explicit TestObserver(RenderView* render_view)
: RenderViewObserver(render_view) {}
virtual void DidClearWindowObject(WebKit::WebFrame* frame) OVERRIDE {
example_bound_class_.BindToJavascript(frame, "example");
}
void set_fallback_method_enabled(bool use_fallback) {
example_bound_class_.set_fallback_method_enabled(use_fallback);
}
private:
CppBindingExampleWithOptionalFallback example_bound_class_;
};
class CppBoundClassTest : public RenderViewTest {
public:
CppBoundClassTest() {}
virtual void SetUp() OVERRIDE {
RenderViewTest::SetUp();
observer_.reset(new TestObserver(view_));
observer_->set_fallback_method_enabled(useFallback());
WebKit::WebURLRequest url_request;
url_request.initialize();
url_request.setURL(GURL("about:blank"));
GetMainFrame()->loadRequest(url_request);
ProcessPendingMessages();
}
// Executes the specified JavaScript and checks that the resulting document
// text is empty.
void CheckJavaScriptFailure(const std::string& javascript) {
ExecuteJavaScript(javascript.c_str());
EXPECT_EQ(
"",
UTF16ToASCII(GetMainFrame()->document().documentElement().innerText()));
}
void CheckTrue(const std::string& expression) {
int was_page_a = -1;
string16 check_page_a =
ASCIIToUTF16(std::string("Number(") + expression + ")");
EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(check_page_a, &was_page_a));
EXPECT_EQ(1, was_page_a);
}
protected:
virtual bool useFallback() {
return false;
}
private:
scoped_ptr<TestObserver> observer_;
};
class CppBoundClassWithFallbackMethodTest : public CppBoundClassTest {
protected:
virtual bool useFallback() OVERRIDE {
return true;
}
};
// Ensures that the example object has been bound to JS.
TEST_F(CppBoundClassTest, ObjectExists) {
CheckTrue("typeof window.example == 'object'");
// An additional check to test our test.
CheckTrue("typeof window.invalid_object == 'undefined'");
}
TEST_F(CppBoundClassTest, PropertiesAreInitialized) {
CheckTrue("example.my_value == 10");
CheckTrue("example.my_other_value == 'Reinitialized!'");
}
TEST_F(CppBoundClassTest, SubOject) {
CheckTrue("typeof window.example.sub_object == 'object'");
CheckTrue("example.sub_object.sub_value == 'sub!'");
}
TEST_F(CppBoundClassTest, SetAndGetProperties) {
// The property on the left will be set to the value on the right, then
// checked to make sure it holds that same value.
static const std::string tests[] = {
"example.my_value", "7",
"example.my_value", "'test'",
"example.my_other_value", "3.14",
"example.my_other_value", "false",
"" // Array end marker: insert additional test pairs before this.
};
for (int i = 0; tests[i] != ""; i += 2) {
std::string left = tests[i];
std::string right = tests[i + 1];
// left = right;
std::string js = left;
js.append(" = ");
js.append(right);
js.append(";");
ExecuteJavaScript(js.c_str());
std::string expression = left;
expression += " == ";
expression += right;
CheckTrue(expression);
}
}
TEST_F(CppBoundClassTest, SetAndGetPropertiesWithCallbacks) {
// TODO(dglazkov): fix NPObject issues around failing property setters and
// getters and add tests for situations when GetProperty or SetProperty fail.
ExecuteJavaScript("example.my_value_with_callback = 10;");
CheckTrue("example.my_value_with_callback == 10");
ExecuteJavaScript("example.my_value_with_callback = 11;");
CheckTrue("example.my_value_with_callback == 11");
CheckTrue("example.same == 42");
ExecuteJavaScript("example.same = 24;");
CheckTrue("example.same == 42");
}
TEST_F(CppBoundClassTest, InvokeMethods) {
// The expression on the left is expected to return the value on the right.
static const std::string tests[] = {
"example.echoValue(true) == true",
"example.echoValue(13) == 13",
"example.echoValue(2.718) == 2.718",
"example.echoValue('yes') == 'yes'",
"example.echoValue() == null", // Too few arguments
"example.echoType(false) == true",
"example.echoType(19) == 3.14159",
"example.echoType(9.876) == 3.14159",
"example.echoType('test string') == 'Success!'",
"example.echoType() == null", // Too few arguments
// Comparing floats that aren't integer-valued is usually problematic due
// to rounding, but exact powers of 2 should also be safe.
"example.plus(2.5, 18.0) == 20.5",
"example.plus(2, 3.25) == 5.25",
"example.plus(2, 3) == 5",
"example.plus() == null", // Too few arguments
"example.plus(1) == null", // Too few arguments
"example.plus(1, 'test') == null", // Wrong argument type
"example.plus('test', 2) == null", // Wrong argument type
"example.plus('one', 'two') == null", // Wrong argument type
"" // Array end marker: insert additional test pairs before this.
};
for (int i = 0; tests[i] != ""; i++)
CheckTrue(tests[i]);
ExecuteJavaScript("example.my_value = 3.25; example.my_other_value = 1.25;");
CheckTrue("example.plus(example.my_value, example.my_other_value) == 4.5");
}
// Tests that invoking a nonexistent method with no fallback method stops the
// script's execution
TEST_F(CppBoundClassTest,
InvokeNonexistentMethodNoFallback) {
std::string js = "example.nonExistentMethod();document.writeln('SUCCESS');";
CheckJavaScriptFailure(js);
}
// Ensures existent methods can be invoked successfully when the fallback method
// is used
TEST_F(CppBoundClassWithFallbackMethodTest,
InvokeExistentMethodsWithFallback) {
CheckTrue("example.echoValue(34) == 34");
}
} // namespace content
| bsd-3-clause |
FieldFlux/orbit | actors/test/actor-tests/src/test/java/cloud/orbit/actors/test/samples/SimpleTest.java | 2671 | /*
Copyright (C) 2016 Electronic Arts Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Electronic Arts, Inc. ("EA") 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 ELECTRONIC ARTS AND ITS 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 ELECTRONIC ARTS OR ITS 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 cloud.orbit.actors.test.samples;
import cloud.orbit.actors.Actor;
import cloud.orbit.actors.Stage;
import cloud.orbit.actors.runtime.AbstractActor;
import cloud.orbit.actors.test.ActorBaseTest;
import cloud.orbit.concurrent.Task;
import org.junit.Test;
import java.util.concurrent.ExecutionException;
import static org.junit.Assert.assertEquals;
@SuppressWarnings("unused")
public class SimpleTest extends ActorBaseTest
{
public interface Hello extends Actor
{
Task<String> sayHello(String greeting);
}
public static class HelloActor extends AbstractActor implements Hello
{
@Override
public Task<String> sayHello(final String greeting)
{
getLogger().info("sayHello: " + greeting);
return Task.fromValue(greeting);
}
}
@Test()
public void singleActorSingleStageTest() throws ExecutionException, InterruptedException
{
Stage stage1 = createStage();
Hello hello = Actor.getReference(Hello.class, "1");
assertEquals("bla", hello.sayHello("bla").join());
dumpMessages();
}
}
| bsd-3-clause |
ayb/spree | backend/spec/controllers/spree/admin/general_settings_controller_spec.rb | 1008 | require 'spec_helper'
describe Spree::Admin::GeneralSettingsController, type: :controller do
let(:user) { create(:user) }
before do
allow(controller).to receive_messages spree_current_user: user
user.spree_roles << Spree::Role.find_or_create_by(name: 'admin')
end
describe '#clear_cache' do
subject { post :clear_cache }
shared_examples 'a HTTP 204 response' do
it 'grant access to users with an admin role' do
subject
expect(response.status).to eq(204)
end
end
context 'when no callback' do
it_behaves_like 'a HTTP 204 response'
end
context 'when callback implemented' do
Spree::Admin::GeneralSettingsController.class_eval do
custom_callback(:clear_cache).after :foo
def foo
# Make a call to Akamai, CloudFlare, etc invalidation....
end
end
before do
expect(controller).to receive(:foo).once
end
it_behaves_like 'a HTTP 204 response'
end
end
end
| bsd-3-clause |
youtube/cobalt | third_party/llvm-project/clang/test/OpenMP/target_teams_distribute_lastprivate_messages.cpp | 8852 | // RUN: %clang_cc1 -verify -fopenmp %s
// RUN: %clang_cc1 -verify -fopenmp-simd %s
void foo() {
}
bool foobool(int argc) {
return argc;
}
struct S1; // expected-note 2 {{declared here}} expected-note 2 {{forward declaration of 'S1'}}
extern S1 a;
class S2 {
mutable int a;
public:
S2() : a(0) {}
S2(S2 &s2) : a(s2.a) {}
const S2 &operator =(const S2&) const;
S2 &operator =(const S2&);
static float S2s; // expected-note {{static data member is predetermined as shared}}
static const float S2sc; // expected-note {{static data member is predetermined as shared}}
};
const float S2::S2sc = 0;
const S2 b;
const S2 ba[5];
class S3 {
int a;
S3 &operator=(const S3 &s3); // expected-note {{implicitly declared private here}}
public:
S3() : a(0) {}
S3(S3 &s3) : a(s3.a) {}
};
const S3 c; // expected-note {{global variable is predetermined as shared}}
const S3 ca[5]; // expected-note {{global variable is predetermined as shared}}
extern const int f; // expected-note {{global variable is predetermined as shared}}
class S4 {
int a;
S4(); // expected-note 3 {{implicitly declared private here}}
S4(const S4 &s4);
public:
S4(int v) : a(v) {}
};
class S5 {
int a;
S5() : a(0) {} // expected-note {{implicitly declared private here}}
public:
S5(const S5 &s5) : a(s5.a) {}
S5(int v) : a(v) {}
};
class S6 {
int a;
S6() : a(0) {} // expected-note {{implicitly declared private here}}
public:
S6(const S6 &s6) : a(s6.a) {}
S6(int v) : a(v) {}
};
S3 h;
#pragma omp threadprivate(h) // expected-note 2 {{defined as threadprivate or thread local}}
template <class I, class C>
int foomain(int argc, char **argv) {
I e(4);
I g(5);
int i;
int &j = i;
#pragma omp target teams distribute lastprivate // expected-error {{expected '(' after 'lastprivate'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute lastprivate( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute lastprivate() // expected-error {{expected expression}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute lastprivate(argc // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute lastprivate(argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute lastprivate(argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute lastprivate(argc)
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute lastprivate(S1) // expected-error {{'S1' does not refer to a value}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute lastprivate(a, b) // expected-error {{lastprivate variable with incomplete type 'S1'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute lastprivate(argv[1]) // expected-error {{expected variable name}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute lastprivate(e, g) // expected-error 2 {{calling a private constructor of class 'S4'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute lastprivate(h) // expected-error {{threadprivate or thread local variable cannot be lastprivate}}
for (int k = 0; k < argc; ++k) ++k;
int v = 0;
#pragma omp target teams distribute lastprivate(i)
for (int k = 0; k < argc; ++k) {
i = k;
v += i;
}
#pragma omp target teams distribute lastprivate(j) private(i)
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute lastprivate(i)
for (int k = 0; k < argc; ++k) ++k;
return 0;
}
void bar(S4 a[2]) {
#pragma omp target teams distribute lastprivate(a)
for (int i = 0; i < 2; ++i) foo();
}
namespace A {
double x;
#pragma omp threadprivate(x) // expected-note {{defined as threadprivate or thread local}}
}
namespace B {
using A::x;
}
int main(int argc, char **argv) {
const int d = 5; // expected-note {{constant variable is predetermined as shared}}
const int da[5] = {0}; // expected-note {{constant variable is predetermined as shared}}
S4 e(4);
S5 g(5);
S3 m;
S6 n(2);
int i;
int &j = i;
#pragma omp target teams distribute lastprivate // expected-error {{expected '(' after 'lastprivate'}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate() // expected-error {{expected expression}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(argc // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(argc)
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(S1) // expected-error {{'S1' does not refer to a value}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(a, b, c, d, f) // expected-error {{lastprivate variable with incomplete type 'S1'}} expected-error 3 {{shared variable cannot be lastprivate}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(argv[1]) // expected-error {{expected variable name}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(2 * 2) // expected-error {{expected variable name}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(ba)
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(ca) // expected-error {{shared variable cannot be lastprivate}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(da) // expected-error {{shared variable cannot be lastprivate}}
for (i = 0; i < argc; ++i) foo();
int xa;
#pragma omp target teams distribute lastprivate(xa) // OK
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(S2::S2s) // expected-error {{shared variable cannot be lastprivate}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(S2::S2sc) // expected-error {{shared variable cannot be lastprivate}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(e, g) // expected-error {{calling a private constructor of class 'S4'}} expected-error {{calling a private constructor of class 'S5'}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(m) // expected-error {{'operator=' is a private member of 'S3'}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(h) // expected-error {{threadprivate or thread local variable cannot be lastprivate}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(B::x) // expected-error {{threadprivate or thread local variable cannot be lastprivate}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute private(xa), lastprivate(xa) // expected-error {{private variable cannot be lastprivate}} expected-note {{defined as private}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(xa)
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute lastprivate(j)
for (i = 0; i < argc; ++i) foo();
// expected-error@+1 {{firstprivate variable cannot be lastprivate}} expected-note@+1 {{defined as firstprivate}}
#pragma omp target teams distribute firstprivate(m) lastprivate(m)
for (i = 0; i < argc; ++i) foo();
// expected-error@+1 {{lastprivate variable cannot be firstprivate}} expected-note@+1 {{defined as lastprivate}}
#pragma omp target teams distribute lastprivate(n) firstprivate(n) // expected-error {{calling a private constructor of class 'S6'}}
for (i = 0; i < argc; ++i) foo();
static int si;
#pragma omp target teams distribute lastprivate(si) // OK
for (i = 0; i < argc; ++i) si = i + 1;
return foomain<S4, S5>(argc, argv); // expected-note {{in instantiation of function template specialization 'foomain<S4, S5>' requested here}}
}
| bsd-3-clause |
endlessm/chromium-browser | third_party/catapult/third_party/gsutil/gslib/vendored/boto/boto/beanstalk/layer1.py | 56366 | # Copyright (c) 2012 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates.
# All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing 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 MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR 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.
#
import boto
import boto.jsonresponse
from boto.compat import json
from boto.regioninfo import RegionInfo
from boto.connection import AWSQueryConnection
class Layer1(AWSQueryConnection):
APIVersion = '2010-12-01'
DefaultRegionName = 'us-east-1'
DefaultRegionEndpoint = 'elasticbeanstalk.us-east-1.amazonaws.com'
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
is_secure=True, port=None,
proxy=None, proxy_port=None,
proxy_user=None, proxy_pass=None, debug=0,
https_connection_factory=None, region=None, path='/',
api_version=None, security_token=None, profile_name=None):
if not region:
region = RegionInfo(self, self.DefaultRegionName,
self.DefaultRegionEndpoint)
self.region = region
super(Layer1, self).__init__(aws_access_key_id,
aws_secret_access_key,
is_secure, port, proxy, proxy_port,
proxy_user, proxy_pass,
self.region.endpoint, debug,
https_connection_factory, path,
security_token, profile_name=profile_name)
def _required_auth_capability(self):
return ['hmac-v4']
def _encode_bool(self, v):
v = bool(v)
return {True: "true", False: "false"}[v]
def _get_response(self, action, params, path='/', verb='GET'):
params['ContentType'] = 'JSON'
response = self.make_request(action, params, path, verb)
body = response.read().decode('utf-8')
boto.log.debug(body)
if response.status == 200:
return json.loads(body)
else:
raise self.ResponseError(response.status, response.reason, body)
def check_dns_availability(self, cname_prefix):
"""Checks if the specified CNAME is available.
:type cname_prefix: string
:param cname_prefix: The prefix used when this CNAME is
reserved.
"""
params = {'CNAMEPrefix': cname_prefix}
return self._get_response('CheckDNSAvailability', params)
def create_application(self, application_name, description=None):
"""
Creates an application that has one configuration template
named default and no application versions.
:type application_name: string
:param application_name: The name of the application.
Constraint: This name must be unique within your account. If the
specified name already exists, the action returns an
InvalidParameterValue error.
:type description: string
:param description: Describes the application.
:raises: TooManyApplicationsException
"""
params = {'ApplicationName': application_name}
if description:
params['Description'] = description
return self._get_response('CreateApplication', params)
def create_application_version(self, application_name, version_label,
description=None, s3_bucket=None,
s3_key=None, auto_create_application=None):
"""Creates an application version for the specified application.
:type application_name: string
:param application_name: The name of the application. If no
application is found with this name, and AutoCreateApplication is
false, returns an InvalidParameterValue error.
:type version_label: string
:param version_label: A label identifying this version. Constraint:
Must be unique per application. If an application version already
exists with this label for the specified application, AWS Elastic
Beanstalk returns an InvalidParameterValue error.
:type description: string
:param description: Describes this version.
:type s3_bucket: string
:param s3_bucket: The Amazon S3 bucket where the data is located.
:type s3_key: string
:param s3_key: The Amazon S3 key where the data is located. Both
s3_bucket and s3_key must be specified in order to use a specific
source bundle. If both of these values are not specified the
sample application will be used.
:type auto_create_application: boolean
:param auto_create_application: Determines how the system behaves if
the specified application for this version does not already exist:
true: Automatically creates the specified application for this
version if it does not already exist. false: Returns an
InvalidParameterValue if the specified application for this version
does not already exist. Default: false Valid Values: true | false
:raises: TooManyApplicationsException,
TooManyApplicationVersionsException,
InsufficientPrivilegesException,
S3LocationNotInServiceRegionException
"""
params = {'ApplicationName': application_name,
'VersionLabel': version_label}
if description:
params['Description'] = description
if s3_bucket and s3_key:
params['SourceBundle.S3Bucket'] = s3_bucket
params['SourceBundle.S3Key'] = s3_key
if auto_create_application:
params['AutoCreateApplication'] = self._encode_bool(
auto_create_application)
return self._get_response('CreateApplicationVersion', params)
def create_configuration_template(self, application_name, template_name,
solution_stack_name=None,
source_configuration_application_name=None,
source_configuration_template_name=None,
environment_id=None, description=None,
option_settings=None):
"""Creates a configuration template.
Templates are associated with a specific application and are used to
deploy different versions of the application with the same
configuration settings.
:type application_name: string
:param application_name: The name of the application to associate with
this configuration template. If no application is found with this
name, AWS Elastic Beanstalk returns an InvalidParameterValue error.
:type template_name: string
:param template_name: The name of the configuration template.
Constraint: This name must be unique per application. Default: If
a configuration template already exists with this name, AWS Elastic
Beanstalk returns an InvalidParameterValue error.
:type solution_stack_name: string
:param solution_stack_name: The name of the solution stack used by this
configuration. The solution stack specifies the operating system,
architecture, and application server for a configuration template.
It determines the set of configuration options as well as the
possible and default values. Use ListAvailableSolutionStacks to
obtain a list of available solution stacks. Default: If the
SolutionStackName is not specified and the source configuration
parameter is blank, AWS Elastic Beanstalk uses the default solution
stack. If not specified and the source configuration parameter is
specified, AWS Elastic Beanstalk uses the same solution stack as
the source configuration template.
:type source_configuration_application_name: string
:param source_configuration_application_name: The name of the
application associated with the configuration.
:type source_configuration_template_name: string
:param source_configuration_template_name: The name of the
configuration template.
:type environment_id: string
:param environment_id: The ID of the environment used with this
configuration template.
:type description: string
:param description: Describes this configuration.
:type option_settings: list
:param option_settings: If specified, AWS Elastic Beanstalk sets the
specified configuration option to the requested value. The new
value overrides the value obtained from the solution stack or the
source configuration template.
:raises: InsufficientPrivilegesException,
TooManyConfigurationTemplatesException
"""
params = {'ApplicationName': application_name,
'TemplateName': template_name}
if solution_stack_name:
params['SolutionStackName'] = solution_stack_name
if source_configuration_application_name:
params['SourceConfiguration.ApplicationName'] = source_configuration_application_name
if source_configuration_template_name:
params['SourceConfiguration.TemplateName'] = source_configuration_template_name
if environment_id:
params['EnvironmentId'] = environment_id
if description:
params['Description'] = description
if option_settings:
self._build_list_params(params, option_settings,
'OptionSettings.member',
('Namespace', 'OptionName', 'Value'))
return self._get_response('CreateConfigurationTemplate', params)
def create_environment(self, application_name, environment_name,
version_label=None, template_name=None,
solution_stack_name=None, cname_prefix=None,
description=None, option_settings=None,
options_to_remove=None, tier_name=None,
tier_type=None, tier_version='1.0'):
"""Launches an environment for the application using a configuration.
:type application_name: string
:param application_name: The name of the application that contains the
version to be deployed. If no application is found with this name,
CreateEnvironment returns an InvalidParameterValue error.
:type environment_name: string
:param environment_name: A unique name for the deployment environment.
Used in the application URL. Constraint: Must be from 4 to 23
characters in length. The name can contain only letters, numbers,
and hyphens. It cannot start or end with a hyphen. This name must
be unique in your account. If the specified name already exists,
AWS Elastic Beanstalk returns an InvalidParameterValue error.
Default: If the CNAME parameter is not specified, the environment
name becomes part of the CNAME, and therefore part of the visible
URL for your application.
:type version_label: string
:param version_label: The name of the application version to deploy. If
the specified application has no associated application versions,
AWS Elastic Beanstalk UpdateEnvironment returns an
InvalidParameterValue error. Default: If not specified, AWS
Elastic Beanstalk attempts to launch the most recently created
application version.
:type template_name: string
:param template_name: The name of the configuration template to
use in deployment. If no configuration template is found with this
name, AWS Elastic Beanstalk returns an InvalidParameterValue error.
Condition: You must specify either this parameter or a
SolutionStackName, but not both. If you specify both, AWS Elastic
Beanstalk returns an InvalidParameterCombination error. If you do
not specify either, AWS Elastic Beanstalk returns a
MissingRequiredParameter error.
:type solution_stack_name: string
:param solution_stack_name: This is an alternative to specifying a
configuration name. If specified, AWS Elastic Beanstalk sets the
configuration values to the default values associated with the
specified solution stack. Condition: You must specify either this
or a TemplateName, but not both. If you specify both, AWS Elastic
Beanstalk returns an InvalidParameterCombination error. If you do
not specify either, AWS Elastic Beanstalk returns a
MissingRequiredParameter error.
:type cname_prefix: string
:param cname_prefix: If specified, the environment attempts to use this
value as the prefix for the CNAME. If not specified, the
environment uses the environment name.
:type description: string
:param description: Describes this environment.
:type option_settings: list
:param option_settings: If specified, AWS Elastic Beanstalk sets the
specified configuration options to the requested value in the
configuration set for the new environment. These override the
values obtained from the solution stack or the configuration
template. Each element in the list is a tuple of (Namespace,
OptionName, Value), for example::
[('aws:autoscaling:launchconfiguration',
'Ec2KeyName', 'mykeypair')]
:type options_to_remove: list
:param options_to_remove: A list of custom user-defined configuration
options to remove from the configuration set for this new
environment.
:type tier_name: string
:param tier_name: The name of the tier. Valid values are
"WebServer" and "Worker". Defaults to "WebServer".
The ``tier_name`` and a ``tier_type`` parameters are
related and the values provided must be valid.
The possible combinations are:
* "WebServer" and "Standard" (the default)
* "Worker" and "SQS/HTTP"
:type tier_type: string
:param tier_type: The type of the tier. Valid values are
"Standard" if ``tier_name`` is "WebServer" and "SQS/HTTP"
if ``tier_name`` is "Worker". Defaults to "Standard".
:type tier_version: string
:type tier_version: The version of the tier. Valid values
currently are "1.0". Defaults to "1.0".
:raises: TooManyEnvironmentsException, InsufficientPrivilegesException
"""
params = {'ApplicationName': application_name,
'EnvironmentName': environment_name}
if version_label:
params['VersionLabel'] = version_label
if template_name:
params['TemplateName'] = template_name
if solution_stack_name:
params['SolutionStackName'] = solution_stack_name
if cname_prefix:
params['CNAMEPrefix'] = cname_prefix
if description:
params['Description'] = description
if option_settings:
self._build_list_params(params, option_settings,
'OptionSettings.member',
('Namespace', 'OptionName', 'Value'))
if options_to_remove:
self.build_list_params(params, options_to_remove,
'OptionsToRemove.member')
if tier_name and tier_type and tier_version:
params['Tier.Name'] = tier_name
params['Tier.Type'] = tier_type
params['Tier.Version'] = tier_version
return self._get_response('CreateEnvironment', params)
def create_storage_location(self):
"""
Creates the Amazon S3 storage location for the account. This
location is used to store user log files.
:raises: TooManyBucketsException,
S3SubscriptionRequiredException,
InsufficientPrivilegesException
"""
return self._get_response('CreateStorageLocation', params={})
def delete_application(self, application_name,
terminate_env_by_force=None):
"""
Deletes the specified application along with all associated
versions and configurations. The application versions will not
be deleted from your Amazon S3 bucket.
:type application_name: string
:param application_name: The name of the application to delete.
:type terminate_env_by_force: boolean
:param terminate_env_by_force: When set to true, running
environments will be terminated before deleting the application.
:raises: OperationInProgressException
"""
params = {'ApplicationName': application_name}
if terminate_env_by_force:
params['TerminateEnvByForce'] = self._encode_bool(
terminate_env_by_force)
return self._get_response('DeleteApplication', params)
def delete_application_version(self, application_name, version_label,
delete_source_bundle=None):
"""Deletes the specified version from the specified application.
:type application_name: string
:param application_name: The name of the application to delete
releases from.
:type version_label: string
:param version_label: The label of the version to delete.
:type delete_source_bundle: boolean
:param delete_source_bundle: Indicates whether to delete the
associated source bundle from Amazon S3. Valid Values: true |
false
:raises: SourceBundleDeletionException,
InsufficientPrivilegesException,
OperationInProgressException,
S3LocationNotInServiceRegionException
"""
params = {'ApplicationName': application_name,
'VersionLabel': version_label}
if delete_source_bundle:
params['DeleteSourceBundle'] = self._encode_bool(
delete_source_bundle)
return self._get_response('DeleteApplicationVersion', params)
def delete_configuration_template(self, application_name, template_name):
"""Deletes the specified configuration template.
:type application_name: string
:param application_name: The name of the application to delete
the configuration template from.
:type template_name: string
:param template_name: The name of the configuration template to
delete.
:raises: OperationInProgressException
"""
params = {'ApplicationName': application_name,
'TemplateName': template_name}
return self._get_response('DeleteConfigurationTemplate', params)
def delete_environment_configuration(self, application_name,
environment_name):
"""
Deletes the draft configuration associated with the running
environment. Updating a running environment with any
configuration changes creates a draft configuration set. You can
get the draft configuration using DescribeConfigurationSettings
while the update is in progress or if the update fails. The
DeploymentStatus for the draft configuration indicates whether
the deployment is in process or has failed. The draft
configuration remains in existence until it is deleted with this
action.
:type application_name: string
:param application_name: The name of the application the
environment is associated with.
:type environment_name: string
:param environment_name: The name of the environment to delete
the draft configuration from.
"""
params = {'ApplicationName': application_name,
'EnvironmentName': environment_name}
return self._get_response('DeleteEnvironmentConfiguration', params)
def describe_application_versions(self, application_name=None,
version_labels=None):
"""Returns descriptions for existing application versions.
:type application_name: string
:param application_name: If specified, AWS Elastic Beanstalk restricts
the returned descriptions to only include ones that are associated
with the specified application.
:type version_labels: list
:param version_labels: If specified, restricts the returned
descriptions to only include ones that have the specified version
labels.
"""
params = {}
if application_name:
params['ApplicationName'] = application_name
if version_labels:
self.build_list_params(params, version_labels,
'VersionLabels.member')
return self._get_response('DescribeApplicationVersions', params)
def describe_applications(self, application_names=None):
"""Returns the descriptions of existing applications.
:type application_names: list
:param application_names: If specified, AWS Elastic Beanstalk restricts
the returned descriptions to only include those with the specified
names.
"""
params = {}
if application_names:
self.build_list_params(params, application_names,
'ApplicationNames.member')
return self._get_response('DescribeApplications', params)
def describe_configuration_options(self, application_name=None,
template_name=None,
environment_name=None,
solution_stack_name=None, options=None):
"""Describes configuration options used in a template or environment.
Describes the configuration options that are used in a
particular configuration template or environment, or that a
specified solution stack defines. The description includes the
values the options, their default values, and an indication of
the required action on a running environment if an option value
is changed.
:type application_name: string
:param application_name: The name of the application associated with
the configuration template or environment. Only needed if you want
to describe the configuration options associated with either the
configuration template or environment.
:type template_name: string
:param template_name: The name of the configuration template whose
configuration options you want to describe.
:type environment_name: string
:param environment_name: The name of the environment whose
configuration options you want to describe.
:type solution_stack_name: string
:param solution_stack_name: The name of the solution stack whose
configuration options you want to describe.
:type options: list
:param options: If specified, restricts the descriptions to only
the specified options.
"""
params = {}
if application_name:
params['ApplicationName'] = application_name
if template_name:
params['TemplateName'] = template_name
if environment_name:
params['EnvironmentName'] = environment_name
if solution_stack_name:
params['SolutionStackName'] = solution_stack_name
if options:
self.build_list_params(params, options, 'Options.member')
return self._get_response('DescribeConfigurationOptions', params)
def describe_configuration_settings(self, application_name,
template_name=None,
environment_name=None):
"""
Returns a description of the settings for the specified
configuration set, that is, either a configuration template or
the configuration set associated with a running environment.
When describing the settings for the configuration set
associated with a running environment, it is possible to receive
two sets of setting descriptions. One is the deployed
configuration set, and the other is a draft configuration of an
environment that is either in the process of deployment or that
failed to deploy.
:type application_name: string
:param application_name: The application for the environment or
configuration template.
:type template_name: string
:param template_name: The name of the configuration template to
describe. Conditional: You must specify either this parameter or
an EnvironmentName, but not both. If you specify both, AWS Elastic
Beanstalk returns an InvalidParameterCombination error. If you do
not specify either, AWS Elastic Beanstalk returns a
MissingRequiredParameter error.
:type environment_name: string
:param environment_name: The name of the environment to describe.
Condition: You must specify either this or a TemplateName, but not
both. If you specify both, AWS Elastic Beanstalk returns an
InvalidParameterCombination error. If you do not specify either,
AWS Elastic Beanstalk returns MissingRequiredParameter error.
"""
params = {'ApplicationName': application_name}
if template_name:
params['TemplateName'] = template_name
if environment_name:
params['EnvironmentName'] = environment_name
return self._get_response('DescribeConfigurationSettings', params)
def describe_environment_resources(self, environment_id=None,
environment_name=None):
"""Returns AWS resources for this environment.
:type environment_id: string
:param environment_id: The ID of the environment to retrieve AWS
resource usage data. Condition: You must specify either this or an
EnvironmentName, or both. If you do not specify either, AWS Elastic
Beanstalk returns MissingRequiredParameter error.
:type environment_name: string
:param environment_name: The name of the environment to retrieve
AWS resource usage data. Condition: You must specify either this
or an EnvironmentId, or both. If you do not specify either, AWS
Elastic Beanstalk returns MissingRequiredParameter error.
:raises: InsufficientPrivilegesException
"""
params = {}
if environment_id:
params['EnvironmentId'] = environment_id
if environment_name:
params['EnvironmentName'] = environment_name
return self._get_response('DescribeEnvironmentResources', params)
def describe_environments(self, application_name=None, version_label=None,
environment_ids=None, environment_names=None,
include_deleted=None,
included_deleted_back_to=None):
"""Returns descriptions for existing environments.
:type application_name: string
:param application_name: If specified, AWS Elastic Beanstalk restricts
the returned descriptions to include only those that are associated
with this application.
:type version_label: string
:param version_label: If specified, AWS Elastic Beanstalk restricts the
returned descriptions to include only those that are associated
with this application version.
:type environment_ids: list
:param environment_ids: If specified, AWS Elastic Beanstalk restricts
the returned descriptions to include only those that have the
specified IDs.
:type environment_names: list
:param environment_names: If specified, AWS Elastic Beanstalk restricts
the returned descriptions to include only those that have the
specified names.
:type include_deleted: boolean
:param include_deleted: Indicates whether to include deleted
environments: true: Environments that have been deleted after
IncludedDeletedBackTo are displayed. false: Do not include deleted
environments.
:type included_deleted_back_to: timestamp
:param included_deleted_back_to: If specified when IncludeDeleted is
set to true, then environments deleted after this date are
displayed.
"""
params = {}
if application_name:
params['ApplicationName'] = application_name
if version_label:
params['VersionLabel'] = version_label
if environment_ids:
self.build_list_params(params, environment_ids,
'EnvironmentIds.member')
if environment_names:
self.build_list_params(params, environment_names,
'EnvironmentNames.member')
if include_deleted:
params['IncludeDeleted'] = self._encode_bool(include_deleted)
if included_deleted_back_to:
params['IncludedDeletedBackTo'] = included_deleted_back_to
return self._get_response('DescribeEnvironments', params)
def describe_events(self, application_name=None, version_label=None,
template_name=None, environment_id=None,
environment_name=None, request_id=None, severity=None,
start_time=None, end_time=None, max_records=None,
next_token=None):
"""Returns event descriptions matching criteria up to the last 6 weeks.
:type application_name: string
:param application_name: If specified, AWS Elastic Beanstalk restricts
the returned descriptions to include only those associated with
this application.
:type version_label: string
:param version_label: If specified, AWS Elastic Beanstalk restricts the
returned descriptions to those associated with this application
version.
:type template_name: string
:param template_name: If specified, AWS Elastic Beanstalk restricts the
returned descriptions to those that are associated with this
environment configuration.
:type environment_id: string
:param environment_id: If specified, AWS Elastic Beanstalk restricts
the returned descriptions to those associated with this
environment.
:type environment_name: string
:param environment_name: If specified, AWS Elastic Beanstalk restricts
the returned descriptions to those associated with this
environment.
:type request_id: string
:param request_id: If specified, AWS Elastic Beanstalk restricts the
described events to include only those associated with this request
ID.
:type severity: string
:param severity: If specified, limits the events returned from this
call to include only those with the specified severity or higher.
:type start_time: timestamp
:param start_time: If specified, AWS Elastic Beanstalk restricts the
returned descriptions to those that occur on or after this time.
:type end_time: timestamp
:param end_time: If specified, AWS Elastic Beanstalk restricts the
returned descriptions to those that occur up to, but not including,
the EndTime.
:type max_records: integer
:param max_records: Specifies the maximum number of events that can be
returned, beginning with the most recent event.
:type next_token: string
:param next_token: Pagination token. If specified, the events return
the next batch of results.
"""
params = {}
if application_name:
params['ApplicationName'] = application_name
if version_label:
params['VersionLabel'] = version_label
if template_name:
params['TemplateName'] = template_name
if environment_id:
params['EnvironmentId'] = environment_id
if environment_name:
params['EnvironmentName'] = environment_name
if request_id:
params['RequestId'] = request_id
if severity:
params['Severity'] = severity
if start_time:
params['StartTime'] = start_time
if end_time:
params['EndTime'] = end_time
if max_records:
params['MaxRecords'] = max_records
if next_token:
params['NextToken'] = next_token
return self._get_response('DescribeEvents', params)
def list_available_solution_stacks(self):
"""Returns a list of the available solution stack names."""
return self._get_response('ListAvailableSolutionStacks', params={})
def rebuild_environment(self, environment_id=None, environment_name=None):
"""
Deletes and recreates all of the AWS resources (for example:
the Auto Scaling group, load balancer, etc.) for a specified
environment and forces a restart.
:type environment_id: string
:param environment_id: The ID of the environment to rebuild.
Condition: You must specify either this or an EnvironmentName, or
both. If you do not specify either, AWS Elastic Beanstalk returns
MissingRequiredParameter error.
:type environment_name: string
:param environment_name: The name of the environment to rebuild.
Condition: You must specify either this or an EnvironmentId, or
both. If you do not specify either, AWS Elastic Beanstalk returns
MissingRequiredParameter error.
:raises InvalidParameterValue: If environment_name doesn't refer to a currently active environment
:raises: InsufficientPrivilegesException
"""
params = {}
if environment_id:
params['EnvironmentId'] = environment_id
if environment_name:
params['EnvironmentName'] = environment_name
return self._get_response('RebuildEnvironment', params)
def request_environment_info(self, info_type='tail', environment_id=None,
environment_name=None):
"""
Initiates a request to compile the specified type of
information of the deployed environment. Setting the InfoType
to tail compiles the last lines from the application server log
files of every Amazon EC2 instance in your environment. Use
RetrieveEnvironmentInfo to access the compiled information.
:type info_type: string
:param info_type: The type of information to request.
:type environment_id: string
:param environment_id: The ID of the environment of the
requested data. If no such environment is found,
RequestEnvironmentInfo returns an InvalidParameterValue error.
Condition: You must specify either this or an EnvironmentName, or
both. If you do not specify either, AWS Elastic Beanstalk returns
MissingRequiredParameter error.
:type environment_name: string
:param environment_name: The name of the environment of the
requested data. If no such environment is found,
RequestEnvironmentInfo returns an InvalidParameterValue error.
Condition: You must specify either this or an EnvironmentId, or
both. If you do not specify either, AWS Elastic Beanstalk returns
MissingRequiredParameter error.
"""
params = {'InfoType': info_type}
if environment_id:
params['EnvironmentId'] = environment_id
if environment_name:
params['EnvironmentName'] = environment_name
return self._get_response('RequestEnvironmentInfo', params)
def restart_app_server(self, environment_id=None, environment_name=None):
"""
Causes the environment to restart the application container
server running on each Amazon EC2 instance.
:type environment_id: string
:param environment_id: The ID of the environment to restart the server
for. Condition: You must specify either this or an
EnvironmentName, or both. If you do not specify either, AWS Elastic
Beanstalk returns MissingRequiredParameter error.
:type environment_name: string
:param environment_name: The name of the environment to restart the
server for. Condition: You must specify either this or an
EnvironmentId, or both. If you do not specify either, AWS Elastic
Beanstalk returns MissingRequiredParameter error.
"""
params = {}
if environment_id:
params['EnvironmentId'] = environment_id
if environment_name:
params['EnvironmentName'] = environment_name
return self._get_response('RestartAppServer', params)
def retrieve_environment_info(self, info_type='tail', environment_id=None,
environment_name=None):
"""
Retrieves the compiled information from a RequestEnvironmentInfo
request.
:type info_type: string
:param info_type: The type of information to retrieve.
:type environment_id: string
:param environment_id: The ID of the data's environment. If no such
environment is found, returns an InvalidParameterValue error.
Condition: You must specify either this or an EnvironmentName, or
both. If you do not specify either, AWS Elastic Beanstalk returns
MissingRequiredParameter error.
:type environment_name: string
:param environment_name: The name of the data's environment. If no such
environment is found, returns an InvalidParameterValue error.
Condition: You must specify either this or an EnvironmentId, or
both. If you do not specify either, AWS Elastic Beanstalk returns
MissingRequiredParameter error.
"""
params = {'InfoType': info_type}
if environment_id:
params['EnvironmentId'] = environment_id
if environment_name:
params['EnvironmentName'] = environment_name
return self._get_response('RetrieveEnvironmentInfo', params)
def swap_environment_cnames(self, source_environment_id=None,
source_environment_name=None,
destination_environment_id=None,
destination_environment_name=None):
"""Swaps the CNAMEs of two environments.
:type source_environment_id: string
:param source_environment_id: The ID of the source environment.
Condition: You must specify at least the SourceEnvironmentID or the
SourceEnvironmentName. You may also specify both. If you specify
the SourceEnvironmentId, you must specify the
DestinationEnvironmentId.
:type source_environment_name: string
:param source_environment_name: The name of the source environment.
Condition: You must specify at least the SourceEnvironmentID or the
SourceEnvironmentName. You may also specify both. If you specify
the SourceEnvironmentName, you must specify the
DestinationEnvironmentName.
:type destination_environment_id: string
:param destination_environment_id: The ID of the destination
environment. Condition: You must specify at least the
DestinationEnvironmentID or the DestinationEnvironmentName. You may
also specify both. You must specify the SourceEnvironmentId with
the DestinationEnvironmentId.
:type destination_environment_name: string
:param destination_environment_name: The name of the destination
environment. Condition: You must specify at least the
DestinationEnvironmentID or the DestinationEnvironmentName. You may
also specify both. You must specify the SourceEnvironmentName with
the DestinationEnvironmentName.
"""
params = {}
if source_environment_id:
params['SourceEnvironmentId'] = source_environment_id
if source_environment_name:
params['SourceEnvironmentName'] = source_environment_name
if destination_environment_id:
params['DestinationEnvironmentId'] = destination_environment_id
if destination_environment_name:
params['DestinationEnvironmentName'] = destination_environment_name
return self._get_response('SwapEnvironmentCNAMEs', params)
def terminate_environment(self, environment_id=None, environment_name=None,
terminate_resources=None):
"""Terminates the specified environment.
:type environment_id: string
:param environment_id: The ID of the environment to terminate.
Condition: You must specify either this or an EnvironmentName, or
both. If you do not specify either, AWS Elastic Beanstalk returns
MissingRequiredParameter error.
:type environment_name: string
:param environment_name: The name of the environment to terminate.
Condition: You must specify either this or an EnvironmentId, or
both. If you do not specify either, AWS Elastic Beanstalk returns
MissingRequiredParameter error.
:type terminate_resources: boolean
:param terminate_resources: Indicates whether the associated AWS
resources should shut down when the environment is terminated:
true: (default) The user AWS resources (for example, the Auto
Scaling group, LoadBalancer, etc.) are terminated along with the
environment. false: The environment is removed from the AWS
Elastic Beanstalk but the AWS resources continue to operate. For
more information, see the AWS Elastic Beanstalk User Guide.
Default: true Valid Values: true | false
:raises: InsufficientPrivilegesException
"""
params = {}
if environment_id:
params['EnvironmentId'] = environment_id
if environment_name:
params['EnvironmentName'] = environment_name
if terminate_resources:
params['TerminateResources'] = self._encode_bool(
terminate_resources)
return self._get_response('TerminateEnvironment', params)
def update_application(self, application_name, description=None):
"""
Updates the specified application to have the specified
properties.
:type application_name: string
:param application_name: The name of the application to update.
If no such application is found, UpdateApplication returns an
InvalidParameterValue error.
:type description: string
:param description: A new description for the application. Default: If
not specified, AWS Elastic Beanstalk does not update the
description.
"""
params = {'ApplicationName': application_name}
if description:
params['Description'] = description
return self._get_response('UpdateApplication', params)
def update_application_version(self, application_name, version_label,
description=None):
"""Updates the application version to have the properties.
:type application_name: string
:param application_name: The name of the application associated with
this version. If no application is found with this name,
UpdateApplication returns an InvalidParameterValue error.
:type version_label: string
:param version_label: The name of the version to update. If no
application version is found with this label, UpdateApplication
returns an InvalidParameterValue error.
:type description: string
:param description: A new description for this release.
"""
params = {'ApplicationName': application_name,
'VersionLabel': version_label}
if description:
params['Description'] = description
return self._get_response('UpdateApplicationVersion', params)
def update_configuration_template(self, application_name, template_name,
description=None, option_settings=None,
options_to_remove=None):
"""
Updates the specified configuration template to have the
specified properties or configuration option values.
:type application_name: string
:param application_name: The name of the application associated with
the configuration template to update. If no application is found
with this name, UpdateConfigurationTemplate returns an
InvalidParameterValue error.
:type template_name: string
:param template_name: The name of the configuration template to update.
If no configuration template is found with this name,
UpdateConfigurationTemplate returns an InvalidParameterValue error.
:type description: string
:param description: A new description for the configuration.
:type option_settings: list
:param option_settings: A list of configuration option settings to
update with the new specified option value.
:type options_to_remove: list
:param options_to_remove: A list of configuration options to remove
from the configuration set. Constraint: You can remove only
UserDefined configuration options.
:raises: InsufficientPrivilegesException
"""
params = {'ApplicationName': application_name,
'TemplateName': template_name}
if description:
params['Description'] = description
if option_settings:
self._build_list_params(params, option_settings,
'OptionSettings.member',
('Namespace', 'OptionName', 'Value'))
if options_to_remove:
self.build_list_params(params, options_to_remove,
'OptionsToRemove.member')
return self._get_response('UpdateConfigurationTemplate', params)
def update_environment(self, environment_id=None, environment_name=None,
version_label=None, template_name=None,
description=None, option_settings=None,
options_to_remove=None, tier_name=None,
tier_type=None, tier_version='1.0'):
"""
Updates the environment description, deploys a new application
version, updates the configuration settings to an entirely new
configuration template, or updates select configuration option
values in the running environment. Attempting to update both
the release and configuration is not allowed and AWS Elastic
Beanstalk returns an InvalidParameterCombination error. When
updating the configuration settings to a new template or
individual settings, a draft configuration is created and
DescribeConfigurationSettings for this environment returns two
setting descriptions with different DeploymentStatus values.
:type environment_id: string
:param environment_id: The ID of the environment to update. If no
environment with this ID exists, AWS Elastic Beanstalk returns an
InvalidParameterValue error. Condition: You must specify either
this or an EnvironmentName, or both. If you do not specify either,
AWS Elastic Beanstalk returns MissingRequiredParameter error.
:type environment_name: string
:param environment_name: The name of the environment to update. If no
environment with this name exists, AWS Elastic Beanstalk returns an
InvalidParameterValue error. Condition: You must specify either
this or an EnvironmentId, or both. If you do not specify either,
AWS Elastic Beanstalk returns MissingRequiredParameter error.
:type version_label: string
:param version_label: If this parameter is specified, AWS Elastic
Beanstalk deploys the named application version to the environment.
If no such application version is found, returns an
InvalidParameterValue error.
:type template_name: string
:param template_name: If this parameter is specified, AWS Elastic
Beanstalk deploys this configuration template to the environment.
If no such configuration template is found, AWS Elastic Beanstalk
returns an InvalidParameterValue error.
:type description: string
:param description: If this parameter is specified, AWS Elastic
Beanstalk updates the description of this environment.
:type option_settings: list
:param option_settings: If specified, AWS Elastic Beanstalk updates the
configuration set associated with the running environment and sets
the specified configuration options to the requested value.
:type options_to_remove: list
:param options_to_remove: A list of custom user-defined configuration
options to remove from the configuration set for this environment.
:type tier_name: string
:param tier_name: The name of the tier. Valid values are
"WebServer" and "Worker". Defaults to "WebServer".
The ``tier_name`` and a ``tier_type`` parameters are
related and the values provided must be valid.
The possible combinations are:
* "WebServer" and "Standard" (the default)
* "Worker" and "SQS/HTTP"
:type tier_type: string
:param tier_type: The type of the tier. Valid values are
"Standard" if ``tier_name`` is "WebServer" and "SQS/HTTP"
if ``tier_name`` is "Worker". Defaults to "Standard".
:type tier_version: string
:type tier_version: The version of the tier. Valid values
currently are "1.0". Defaults to "1.0".
:raises: InsufficientPrivilegesException
"""
params = {}
if environment_id:
params['EnvironmentId'] = environment_id
if environment_name:
params['EnvironmentName'] = environment_name
if version_label:
params['VersionLabel'] = version_label
if template_name:
params['TemplateName'] = template_name
if description:
params['Description'] = description
if option_settings:
self._build_list_params(params, option_settings,
'OptionSettings.member',
('Namespace', 'OptionName', 'Value'))
if options_to_remove:
self.build_list_params(params, options_to_remove,
'OptionsToRemove.member')
if tier_name and tier_type and tier_version:
params['Tier.Name'] = tier_name
params['Tier.Type'] = tier_type
params['Tier.Version'] = tier_version
return self._get_response('UpdateEnvironment', params)
def validate_configuration_settings(self, application_name,
option_settings, template_name=None,
environment_name=None):
"""
Takes a set of configuration settings and either a
configuration template or environment, and determines whether
those values are valid. This action returns a list of messages
indicating any errors or warnings associated with the selection
of option values.
:type application_name: string
:param application_name: The name of the application that the
configuration template or environment belongs to.
:type template_name: string
:param template_name: The name of the configuration template to
validate the settings against. Condition: You cannot specify both
this and an environment name.
:type environment_name: string
:param environment_name: The name of the environment to validate the
settings against. Condition: You cannot specify both this and a
configuration template name.
:type option_settings: list
:param option_settings: A list of the options and desired values to
evaluate.
:raises: InsufficientPrivilegesException
"""
params = {'ApplicationName': application_name}
self._build_list_params(params, option_settings,
'OptionSettings.member',
('Namespace', 'OptionName', 'Value'))
if template_name:
params['TemplateName'] = template_name
if environment_name:
params['EnvironmentName'] = environment_name
return self._get_response('ValidateConfigurationSettings', params)
def _build_list_params(self, params, user_values, prefix, tuple_names):
# For params such as the ConfigurationOptionSettings,
# they can specify a list of tuples where each tuple maps to a specific
# arg. For example:
# user_values = [('foo', 'bar', 'baz']
# prefix=MyOption.member
# tuple_names=('One', 'Two', 'Three')
# would result in:
# MyOption.member.1.One = foo
# MyOption.member.1.Two = bar
# MyOption.member.1.Three = baz
for i, user_value in enumerate(user_values, 1):
current_prefix = '%s.%s' % (prefix, i)
for key, value in zip(tuple_names, user_value):
full_key = '%s.%s' % (current_prefix, key)
params[full_key] = value
| bsd-3-clause |
jason-p-pickering/dhis2-persian-calendar | dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateCategoryComboStore.java | 2437 | package org.hisp.dhis.dataelement.hibernate;
/*
* Copyright (c) 2004-2017, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.List;
import org.hibernate.criterion.Restrictions;
import org.hisp.dhis.common.DataDimensionType;
import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore;
import org.hisp.dhis.dataelement.CategoryComboStore;
import org.hisp.dhis.dataelement.DataElementCategoryCombo;
/**
* @author Lars Helge Overland
*/
public class HibernateCategoryComboStore
extends HibernateIdentifiableObjectStore<DataElementCategoryCombo>
implements CategoryComboStore
{
@Override
@SuppressWarnings("unchecked")
public List<DataElementCategoryCombo> getCategoryCombosByDimensionType( DataDimensionType dataDimensionType )
{
return getSharingDetachedCriteria( Restrictions.or( Restrictions.eq( "dataDimensionType", dataDimensionType ), Restrictions.eq( "name", "default" ) ) ).list();
}
}
| bsd-3-clause |
Natim/sentry | src/sentry/api/endpoints/project_tagkey_values.py | 2268 | from __future__ import absolute_import
from sentry.api.base import DocSection
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.exceptions import ResourceDoesNotExist
from sentry.api.serializers import serialize
from sentry.models import TagKey, TagKeyStatus, TagValue
from sentry.utils.db import is_postgres
class ProjectTagKeyValuesEndpoint(ProjectEndpoint):
doc_section = DocSection.PROJECTS
def get(self, request, project, key):
"""
List a Tag's Values
```````````````````
Return a list of values associated with this key. The `query`
parameter can be used to to perform a "starts with" match on
values.
:pparam string organization_slug: the slug of the organization.
:pparam string project_slug: the slug of the project.
:pparam string key: the tag key to look up.
:auth: required
"""
if key in ('release', 'user', 'filename', 'function'):
lookup_key = 'sentry:{0}'.format(key)
else:
lookup_key = key
try:
tagkey = TagKey.objects.get(
project=project,
key=lookup_key,
status=TagKeyStatus.VISIBLE,
)
except TagKey.DoesNotExist:
raise ResourceDoesNotExist
base_queryset = TagValue.objects.filter(
project=project,
key=tagkey.key,
)
query = request.GET.get('query')
if query:
if is_postgres():
# not quite optimal, but best we can do with ORM
queryset = TagValue.objects.filter(
id__in=base_queryset.order_by('-times_seen')[:10000]
)
else:
# MySQL can't handle an `IN` with a `LIMIT` clause
queryset = base_queryset
queryset = queryset.filter(value__istartswith=query)
else:
queryset = TagValue.objects.filter(
project=project,
key=tagkey.key,
)
return self.paginate(
request=request,
queryset=queryset,
order_by='-times_seen',
on_results=lambda x: serialize(x, request.user),
)
| bsd-3-clause |
litecoinscrypt/litecoinscrypt | src/qt/guiutil.cpp | 13575 | #include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"
#include "base58.h"
#include <QString>
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#include <QUrl>
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
if(uri.scheme() != QString("litecoinscrypt"))
return false;
// check if the address is valid
CBitcoinAddress addressFromUri(uri.path().toStdString());
if (!addressFromUri.IsValid())
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
QList<QPair<QString, QString> > items = uri.queryItems();
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert LiteCoinScrypt:// to LiteCoinScrypt:
//
// Cannot handle this later, because litecoinscrypt:// will cause Qt to see the part after // as host,
// which will lowercase it (and thus invalidate the address).
if(uri.startsWith("litecoinscrypt://"))
{
uri.replace(0, 11, "litecoinscrypt:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
QString escaped = Qt::escape(str);
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
QApplication::clipboard()->setText(selection.at(0).data(role).toString());
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "LiteCoinScrypt.lnk";
}
bool GetStartOnSystemStartup()
{
// check for LiteCoinScrypt.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "litecoinscrypt.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a litecoinscrypt.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=LiteCoinScrypt\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#else
// TODO: OSX startup stuff; see:
// https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr("litecoinscrypt-qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" litecoinscrypt-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage());
uiOptions = tr("UI options") + ":\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
setWindowTitle(tr("litecoinscrypt-qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in nonbreaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));
setDetailedText(coreOptions + "\n" + uiOptions);
}
void HelpMessageBox::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
fprintf(stderr, "%s", strUsage.toStdString().c_str());
}
void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
// On windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
} // namespace GUIUtil
| mit |
trustify/oroplatform | src/Oro/Bundle/TranslationBundle/Tests/Unit/Command/OroTranslationPackCommandTest.php | 7533 | <?php
namespace Oro\Bundle\TranslationBundle\Tests\Unit\Command;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Oro\Bundle\TranslationBundle\Tests\Unit\Command\Stubs\TestKernel;
use Oro\Bundle\TranslationBundle\Command\OroTranslationPackCommand;
class OroTranslationPackCommandTest extends \PHPUnit_Framework_TestCase
{
public function testConfigure()
{
$kernel = new TestKernel();
$kernel->boot();
$app = new Application($kernel);
$app->add($this->getCommandMock());
$command = $app->find('oro:translation:pack');
$this->assertNotEmpty($command->getDescription());
$this->assertNotEmpty($command->getDefinition());
$this->assertNotEmpty($command->getHelp());
}
/**
* Test command execute
*
* @dataProvider executeInputProvider
*
* @param array $input
* @param array $expectedCalls
* @param bool|string $exception
*/
public function testExecute($input, $expectedCalls = array(), $exception = false)
{
$kernel = new TestKernel();
$kernel->boot();
$app = new Application($kernel);
$commandMock = $this->getCommandMock(array_keys($expectedCalls));
$app->add($commandMock);
$command = $app->find('oro:translation:pack');
$command->setApplication($app);
if ($exception) {
$this->setExpectedException($exception);
}
$transServiceMock = $this->getMockBuilder(
'Oro\Bundle\TranslationBundle\Provider\TranslationServiceProvider'
)
->disableOriginalConstructor()
->getMock();
foreach ($expectedCalls as $method => $count) {
if ($method == 'getTranslationService') {
$commandMock->expects($this->exactly($count))
->method($method)
->will($this->returnValue($transServiceMock));
}
$commandMock->expects($this->exactly($count))->method($method);
}
$tester = new CommandTester($command);
$input += array('command' => $command->getName());
$tester->execute($input);
}
/**
* @return array
*/
public function executeInputProvider()
{
return array(
'error if action not specified' => array(
array('project' => 'SomeProject'),
array(
'dump' => 0,
'upload' => 0
)
),
'error if project not specified' => array(
array('--dump' => true),
array(
'dump' => 0,
'upload' => 0
),
'\RuntimeException'
),
'dump action should perform' => array(
array('--dump' => true, 'project' => 'SomeProject'),
array(
'dump' => 1,
'upload' => 0
),
),
'upload action should perform' => array(
array('--upload' => true, 'project' => 'SomeProject'),
array(
'dump' => 0,
'upload' => 1,
'getTranslationService' => 1,
'getLangPackDir' => 1,
),
),
'dump and upload action should perform' => array(
array('--upload' => true, '--dump' => true, 'project' => 'SomeProject'),
array(
'dump' => 1,
'upload' => 1,
'getTranslationService' => 1,
),
)
);
}
public function testUpload()
{
$this->runUploadDownloadTest('upload');
}
public function testUpdate()
{
$this->runUploadDownloadTest('upload', array('-m' => 'update'));
}
public function testDownload()
{
$this->runUploadDownloadTest('download');
}
public function runUploadDownloadTest($commandName, $args = [])
{
$kernel = new TestKernel();
$kernel->boot();
$projectId = 'someproject';
$adapterMock = $this->getNewMock('Oro\Bundle\TranslationBundle\Provider\CrowdinAdapter');
$adapterMock->expects($this->any())
->method('setProjectId')
->with($projectId);
$uploaderMock = $this->getNewMock('Oro\Bundle\TranslationBundle\Provider\TranslationServiceProvider');
$uploaderMock->expects($this->any())
->method('setAdapter')
->with($adapterMock)
->will($this->returnSelf());
$uploaderMock->expects($this->once())
->method('setLogger')
->with($this->isInstanceOf('Psr\Log\LoggerInterface'))
->will($this->returnSelf());
if (isset($args['-m']) && $args['-m'] == 'update') {
$uploaderMock->expects($this->once())
->method('update');
} else {
$uploaderMock->expects($this->once())
->method($commandName);
}
$kernel->getContainer()->set('oro_translation.uploader.crowdin_adapter', $adapterMock);
$kernel->getContainer()->set('oro_translation.service_provider', $uploaderMock);
$app = new Application($kernel);
$commandMock = $this->getCommandMock();
$app->add($commandMock);
$command = $app->find('oro:translation:pack');
$command->setApplication($app);
$tester = new CommandTester($command);
$input = array('command' => $command->getName(), '--' . $commandName => true, 'project' => $projectId);
if (!empty($args)) {
$input = array_merge($input, $args);
}
$tester->execute($input);
}
public function testExecuteWithoutMode()
{
$kernel = new TestKernel();
$kernel->boot();
$app = new Application($kernel);
$commandMock = $this->getCommandMock();
$app->add($commandMock);
$command = $app->find('oro:translation:pack');
$command->setApplication($app);
$tester = new CommandTester($command);
$input = array('command' => $command->getName(), 'project' => 'test123');
$return = $tester->execute($input);
$this->assertEquals(1, $return);
}
/**
* @return array
*/
public function formatProvider()
{
return array(
'format do not specified, yml default' => array('yml', false),
'format specified xml expected ' => array('xml', 'xml')
);
}
/**
* Prepares command mock
* asText mocked by default in case when we don't need to mock anything
*
* @param array $methods
*
* @return \PHPUnit_Framework_MockObject_MockObject|OroTranslationPackCommand
*/
protected function getCommandMock($methods = array('asText'))
{
$commandMock = $this->getMockBuilder('Oro\Bundle\TranslationBundle\Command\OroTranslationPackCommand')
->setMethods($methods);
return $commandMock->getMock();
}
/**
* @param $class
*
* @return \PHPUnit_Framework_MockObject_MockObject
*/
protected function getNewMock($class)
{
return $this->getMock($class, [], [], '', false);
}
}
| mit |
tronlec/three.js | utils/exporters/blender/addons/io_three/constants.py | 7879 | '''
All constant data used in the package should be defined here.
'''
from collections import OrderedDict as BASE_DICT
BLENDING_TYPES = type('Blending', (), {
'NONE': 'NoBlending',
'NORMAL': 'NormalBlending',
'ADDITIVE': 'AdditiveBlending',
'SUBTRACTIVE': 'SubtractiveBlending',
'MULTIPLY': 'MultiplyBlending',
'CUSTOM': 'CustomBlending'
})
NEAREST_FILTERS = type('NearestFilters', (), {
'NEAREST': 'NearestFilter',
'MIP_MAP_NEAREST': 'NearestMipMapNearestFilter',
'MIP_MAP_LINEAR': 'NearestMipMapLinearFilter'
})
LINEAR_FILTERS = type('LinearFilters', (), {
'LINEAR': 'LinearFilter',
'MIP_MAP_NEAREST': 'LinearMipMapNearestFilter',
'MIP_MAP_LINEAR': 'LinearMipMapLinearFilter'
})
MAPPING_TYPES = type('Mapping', (), {
'UV': 'UVMapping',
'CUBE_REFLECTION': 'CubeReflectionMapping',
'CUBE_REFRACTION': 'CubeRefractionMapping',
'SPHERICAL_REFLECTION': 'SphericalReflectionMapping'
})
NUMERIC = {
'UVMapping': 300,
'CubeReflectionMapping': 301,
'CubeRefractionMapping': 302,
'EquirectangularReflectionMapping': 303,
'EquirectangularRefractionMapping': 304,
'SphericalReflectionMapping': 305,
'RepeatWrapping': 1000,
'ClampToEdgeWrapping': 1001,
'MirroredRepeatWrapping': 1002,
'NearestFilter': 1003,
'NearestMipMapNearestFilter': 1004,
'NearestMipMapLinearFilter': 1005,
'LinearFilter': 1006,
'LinearMipMapNearestFilter': 1007,
'LinearMipMapLinearFilter': 1008
}
JSON = 'json'
EXTENSION = '.%s' % JSON
INDENT = 'indent'
MATERIALS = 'materials'
SCENE = 'scene'
VERTICES = 'vertices'
FACES = 'faces'
NORMALS = 'normals'
BONES = 'bones'
UVS = 'uvs'
APPLY_MODIFIERS = 'applyModifiers'
COLORS = 'colors'
MIX_COLORS = 'mixColors'
EXTRA_VGROUPS = 'extraVertexGroups'
INDEX = 'index'
DRAW_CALLS = 'drawcalls'
DC_START = 'start'
DC_COUNT = 'count'
DC_INDEX = 'index'
SCALE = 'scale'
COMPRESSION = 'compression'
MAPS = 'maps'
FRAME_STEP = 'frameStep'
FRAME_INDEX_AS_TIME = 'frameIndexAsTime'
ANIMATION = 'animations'
CLIPS="clips"
KEYFRAMES = 'tracks'
MORPH_TARGETS = 'morphTargets'
MORPH_TARGETS_ANIM = 'morphTargetsAnimation'
BLEND_SHAPES = 'blendShapes'
POSE = 'pose'
REST = 'rest'
SKIN_INDICES = 'skinIndices'
SKIN_WEIGHTS = 'skinWeights'
LOGGING = 'logging'
CAMERAS = 'cameras'
LIGHTS = 'lights'
HIERARCHY = 'hierarchy'
FACE_MATERIALS = 'faceMaterials'
SKINNING = 'skinning'
COPY_TEXTURES = 'copyTextures'
TEXTURE_FOLDER = 'textureFolder'
ENABLE_PRECISION = 'enablePrecision'
PRECISION = 'precision'
DEFAULT_PRECISION = 6
EMBED_GEOMETRY = 'embedGeometry'
EMBED_ANIMATION = 'embedAnimation'
OFF = 'off'
GLOBAL = 'global'
BUFFER_GEOMETRY = 'BufferGeometry'
GEOMETRY = 'geometry'
GEOMETRY_TYPE = 'geometryType'
INDEX_TYPE = 'indexType'
CRITICAL = 'critical'
ERROR = 'error'
WARNING = 'warning'
INFO = 'info'
DEBUG = 'debug'
DISABLED = 'disabled'
NONE = 'None'
MSGPACK = 'msgpack'
PACK = 'pack'
FLOAT_32 = 'Float32Array'
UINT_16 = 'Uint16Array'
UINT_32 = 'Uint32Array'
INFLUENCES_PER_VERTEX = 'influencesPerVertex'
EXPORT_OPTIONS = {
FACES: True,
VERTICES: True,
NORMALS: True,
UVS: True,
APPLY_MODIFIERS: True,
COLORS: False,
EXTRA_VGROUPS: '',
INDEX_TYPE: UINT_16,
MATERIALS: False,
FACE_MATERIALS: False,
SCALE: 1,
FRAME_STEP: 1,
FRAME_INDEX_AS_TIME: False,
SCENE: False,
MIX_COLORS: False,
COMPRESSION: None,
MAPS: False,
ANIMATION: OFF,
KEYFRAMES: False,
BONES: False,
SKINNING: False,
MORPH_TARGETS: False,
BLEND_SHAPES: False,
CAMERAS: False,
LIGHTS: False,
HIERARCHY: False,
COPY_TEXTURES: True,
TEXTURE_FOLDER: '',
LOGGING: DEBUG,
ENABLE_PRECISION: True,
PRECISION: DEFAULT_PRECISION,
EMBED_GEOMETRY: True,
EMBED_ANIMATION: True,
GEOMETRY_TYPE: GEOMETRY,
INFLUENCES_PER_VERTEX: 2,
INDENT: True
}
FORMAT_VERSION = 4.4
VERSION = 'version'
THREE = 'io_three'
GENERATOR = 'generator'
SOURCE_FILE = 'sourceFile'
VALID_DATA_TYPES = (str, int, float, bool, list, tuple, dict)
JSON = 'json'
GZIP = 'gzip'
EXTENSIONS = {
JSON: '.json',
MSGPACK: '.pack',
GZIP: '.gz'
}
METADATA = 'metadata'
GEOMETRIES = 'geometries'
IMAGES = 'images'
TEXTURE = 'texture'
TEXTURES = 'textures'
USER_DATA = 'userData'
DATA = 'data'
TYPE = 'type'
MATERIAL = 'material'
OBJECT = 'object'
PERSPECTIVE_CAMERA = 'PerspectiveCamera'
ORTHOGRAPHIC_CAMERA = 'OrthographicCamera'
AMBIENT_LIGHT = 'AmbientLight'
DIRECTIONAL_LIGHT = 'DirectionalLight'
POINT_LIGHT = 'PointLight'
SPOT_LIGHT = 'SpotLight'
HEMISPHERE_LIGHT = 'HemisphereLight'
MESH = 'Mesh'
EMPTY = 'Empty'
SPRITE = 'Sprite'
DEFAULT_METADATA = {
VERSION: FORMAT_VERSION,
TYPE: OBJECT.title(),
GENERATOR: THREE
}
UUID = 'uuid'
MATRIX = 'matrix'
POSITION = 'position'
QUATERNION = 'quaternion'
ROTATION = 'rotation'
SCALE = 'scale'
UV = 'uv'
ATTRIBUTES = 'attributes'
NORMAL = 'normal'
ITEM_SIZE = 'itemSize'
ARRAY = 'array'
FLOAT_32 = 'Float32Array'
VISIBLE = 'visible'
CAST_SHADOW = 'castShadow'
RECEIVE_SHADOW = 'receiveShadow'
QUAD = 'quad'
USER_DATA = 'userData'
MASK = {
QUAD: 0,
MATERIALS: 1,
UVS: 3,
NORMALS: 5,
COLORS: 7
}
CHILDREN = 'children'
URL = 'url'
WRAP = 'wrap'
REPEAT = 'repeat'
WRAPPING = type('Wrapping', (), {
'REPEAT': 'RepeatWrapping',
'CLAMP': 'ClampToEdgeWrapping',
'MIRROR': 'MirroredRepeatWrapping'
})
ANISOTROPY = 'anisotropy'
MAG_FILTER = 'magFilter'
MIN_FILTER = 'minFilter'
MAPPING = 'mapping'
IMAGE = 'image'
NAME = 'name'
PARENT = 'parent'
LENGTH = 'length'
FPS = 'fps'
HIERARCHY = 'hierarchy'
POS = 'pos'
ROTQ = 'rotq'
ROT = 'rot'
SCL = 'scl'
TIME = 'time'
KEYS = 'keys'
COLOR = 'color'
EMISSIVE = 'emissive'
SPECULAR = 'specular'
SPECULAR_COEF = 'specularCoef'
SHININESS = 'shininess'
SIDE = 'side'
OPACITY = 'opacity'
TRANSPARENT = 'transparent'
WIREFRAME = 'wireframe'
BLENDING = 'blending'
VERTEX_COLORS = 'vertexColors'
DEPTH_WRITE = 'depthWrite'
DEPTH_TEST = 'depthTest'
MAP = 'map'
SPECULAR_MAP = 'specularMap'
LIGHT_MAP = 'lightMap'
BUMP_MAP = 'bumpMap'
BUMP_SCALE = 'bumpScale'
NORMAL_MAP = 'normalMap'
NORMAL_SCALE = 'normalScale'
#@TODO ENV_MAP, REFLECTIVITY, REFRACTION_RATIO, COMBINE
MAP_DIFFUSE = 'mapDiffuse'
MAP_DIFFUSE_REPEAT = 'mapDiffuseRepeat'
MAP_DIFFUSE_WRAP = 'mapDiffuseWrap'
MAP_DIFFUSE_ANISOTROPY = 'mapDiffuseAnisotropy'
MAP_SPECULAR = 'mapSpecular'
MAP_SPECULAR_REPEAT = 'mapSpecularRepeat'
MAP_SPECULAR_WRAP = 'mapSpecularWrap'
MAP_SPECULAR_ANISOTROPY = 'mapSpecularAnisotropy'
MAP_LIGHT = 'mapLight'
MAP_LIGHT_REPEAT = 'mapLightRepeat'
MAP_LIGHT_WRAP = 'mapLightWrap'
MAP_LIGHT_ANISOTROPY = 'mapLightAnisotropy'
MAP_NORMAL = 'mapNormal'
MAP_NORMAL_FACTOR = 'mapNormalFactor'
MAP_NORMAL_REPEAT = 'mapNormalRepeat'
MAP_NORMAL_WRAP = 'mapNormalWrap'
MAP_NORMAL_ANISOTROPY = 'mapNormalAnisotropy'
MAP_BUMP = 'mapBump'
MAP_BUMP_REPEAT = 'mapBumpRepeat'
MAP_BUMP_WRAP = 'mapBumpWrap'
MAP_BUMP_ANISOTROPY = 'mapBumpAnisotropy'
MAP_BUMP_SCALE = 'mapBumpScale'
NORMAL_BLENDING = 0
VERTEX_COLORS_ON = 2
VERTEX_COLORS_OFF = 0
SIDE_DOUBLE = 2
THREE_BASIC = 'MeshBasicMaterial'
THREE_LAMBERT = 'MeshLambertMaterial'
THREE_PHONG = 'MeshPhongMaterial'
INTENSITY = 'intensity'
DISTANCE = 'distance'
ASPECT = 'aspect'
ANGLE = 'angle'
DECAY = 'decayExponent'
FOV = 'fov'
ASPECT = 'aspect'
NEAR = 'near'
FAR = 'far'
LEFT = 'left'
RIGHT = 'right'
TOP = 'top'
BOTTOM = 'bottom'
SHADING = 'shading'
COLOR_DIFFUSE = 'colorDiffuse'
COLOR_EMISSIVE = 'colorEmissive'
COLOR_SPECULAR = 'colorSpecular'
DBG_NAME = 'DbgName'
DBG_COLOR = 'DbgColor'
DBG_INDEX = 'DbgIndex'
EMIT = 'emit'
PHONG = 'phong'
LAMBERT = 'lambert'
BASIC = 'basic'
NORMAL_BLENDING = 'NormalBlending'
DBG_COLORS = (0xeeeeee, 0xee0000, 0x00ee00, 0x0000ee,
0xeeee00, 0x00eeee, 0xee00ee)
DOUBLE_SIDED = 'doubleSided'
EXPORT_SETTINGS_KEY = 'threeExportSettings'
| mit |