code
stringlengths
4
1.01M
language
stringclasses
2 values
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.config.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.config.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * DescribeConfigRulesRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DescribeConfigRulesRequestMarshaller { private static final MarshallingInfo<List> CONFIGRULENAMES_BINDING = MarshallingInfo.builder(MarshallingType.LIST) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ConfigRuleNames").build(); private static final MarshallingInfo<String> NEXTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("NextToken").build(); private static final DescribeConfigRulesRequestMarshaller instance = new DescribeConfigRulesRequestMarshaller(); public static DescribeConfigRulesRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(DescribeConfigRulesRequest describeConfigRulesRequest, ProtocolMarshaller protocolMarshaller) { if (describeConfigRulesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeConfigRulesRequest.getConfigRuleNames(), CONFIGRULENAMES_BINDING); protocolMarshaller.marshall(describeConfigRulesRequest.getNextToken(), NEXTTOKEN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
Java
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.iotevents.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/GetDetectorModelAnalysisResults" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetDetectorModelAnalysisResultsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The ID of the analysis result that you want to retrieve. * </p> */ private String analysisId; /** * <p> * The token that you can use to return the next set of results. * </p> */ private String nextToken; /** * <p> * The maximum number of results to be returned per request. * </p> */ private Integer maxResults; /** * <p> * The ID of the analysis result that you want to retrieve. * </p> * * @param analysisId * The ID of the analysis result that you want to retrieve. */ public void setAnalysisId(String analysisId) { this.analysisId = analysisId; } /** * <p> * The ID of the analysis result that you want to retrieve. * </p> * * @return The ID of the analysis result that you want to retrieve. */ public String getAnalysisId() { return this.analysisId; } /** * <p> * The ID of the analysis result that you want to retrieve. * </p> * * @param analysisId * The ID of the analysis result that you want to retrieve. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDetectorModelAnalysisResultsRequest withAnalysisId(String analysisId) { setAnalysisId(analysisId); return this; } /** * <p> * The token that you can use to return the next set of results. * </p> * * @param nextToken * The token that you can use to return the next set of results. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * The token that you can use to return the next set of results. * </p> * * @return The token that you can use to return the next set of results. */ public String getNextToken() { return this.nextToken; } /** * <p> * The token that you can use to return the next set of results. * </p> * * @param nextToken * The token that you can use to return the next set of results. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDetectorModelAnalysisResultsRequest withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * <p> * The maximum number of results to be returned per request. * </p> * * @param maxResults * The maximum number of results to be returned per request. */ public void setMaxResults(Integer maxResults) { this.maxResults = maxResults; } /** * <p> * The maximum number of results to be returned per request. * </p> * * @return The maximum number of results to be returned per request. */ public Integer getMaxResults() { return this.maxResults; } /** * <p> * The maximum number of results to be returned per request. * </p> * * @param maxResults * The maximum number of results to be returned per request. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDetectorModelAnalysisResultsRequest withMaxResults(Integer maxResults) { setMaxResults(maxResults); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAnalysisId() != null) sb.append("AnalysisId: ").append(getAnalysisId()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()).append(","); if (getMaxResults() != null) sb.append("MaxResults: ").append(getMaxResults()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetDetectorModelAnalysisResultsRequest == false) return false; GetDetectorModelAnalysisResultsRequest other = (GetDetectorModelAnalysisResultsRequest) obj; if (other.getAnalysisId() == null ^ this.getAnalysisId() == null) return false; if (other.getAnalysisId() != null && other.getAnalysisId().equals(this.getAnalysisId()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; if (other.getMaxResults() == null ^ this.getMaxResults() == null) return false; if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAnalysisId() == null) ? 0 : getAnalysisId().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode()); return hashCode; } @Override public GetDetectorModelAnalysisResultsRequest clone() { return (GetDetectorModelAnalysisResultsRequest) super.clone(); } }
Java
/* * Copyright 2014-2015 Nippon Telegraph and Telephone Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __LAGOPUS_RUNNABLE_FUNCS_H__ #define __LAGOPUS_RUNNABLE_FUNCS_H__ /** * @file lagopus_runnable_funcs.h */ #ifndef RUNNABLE_T_DECLARED typedef struct lagopus_runnable_record *lagopus_runnable_t; #define RUNNABLE_T_DECLARED #endif /* ! RUNNABLE_T_DECLARED */ /** * A procedure for a runnable. * * @param[in] rptr A runnable. * @param[in] arg An argument. * * @details If any resoures acquired in the function must be released * before returning. Doing this must be the functions's responsibility. * * @details This function must not loop infinitely, but must return in * appropriate amount of execution time. */ typedef void (*lagopus_runnable_proc_t)(const lagopus_runnable_t *rptr, void *arg); /** * Free a runnable up. * * @param[in] rptr A pointer to a runnable. * * @details Don't free the \b *rptr itself up. */ typedef void (*lagopus_runnable_freeup_proc_t)(lagopus_runnable_t *rptr); #endif /* ! __LAGOPUS_RUNNABLE_FUNCS_H__ */
Java
/* Copyright 2014 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" "fmt" "io" jsonpatch "github.com/evanphx/json-patch" "github.com/golang/glog" "github.com/spf13/cobra" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/json" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/cli-runtime/pkg/genericclioptions/printers" "k8s.io/cli-runtime/pkg/genericclioptions/resource" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/kubectl/cmd/templates" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "k8s.io/kubernetes/pkg/kubectl/scheme" "k8s.io/kubernetes/pkg/kubectl/util/i18n" ) // AnnotateOptions have the data required to perform the annotate operation type AnnotateOptions struct { PrintFlags *genericclioptions.PrintFlags PrintObj printers.ResourcePrinterFunc // Filename options resource.FilenameOptions RecordFlags *genericclioptions.RecordFlags // Common user flags overwrite bool local bool dryrun bool all bool resourceVersion string selector string fieldSelector string outputFormat string // results of arg parsing resources []string newAnnotations map[string]string removeAnnotations []string Recorder genericclioptions.Recorder namespace string enforceNamespace bool builder *resource.Builder unstructuredClientForMapping func(mapping *meta.RESTMapping) (resource.RESTClient, error) includeUninitialized bool genericclioptions.IOStreams } var ( annotateLong = templates.LongDesc(` Update the annotations on one or more resources All Kubernetes objects support the ability to store additional data with the object as annotations. Annotations are key/value pairs that can be larger than labels and include arbitrary string values such as structured JSON. Tools and system extensions may use annotations to store their own data. Attempting to set an annotation that already exists will fail unless --overwrite is set. If --resource-version is specified and does not match the current resource version on the server the command will fail.`) annotateExample = templates.Examples(i18n.T(` # Update pod 'foo' with the annotation 'description' and the value 'my frontend'. # If the same annotation is set multiple times, only the last value will be applied kubectl annotate pods foo description='my frontend' # Update a pod identified by type and name in "pod.json" kubectl annotate -f pod.json description='my frontend' # Update pod 'foo' with the annotation 'description' and the value 'my frontend running nginx', overwriting any existing value. kubectl annotate --overwrite pods foo description='my frontend running nginx' # Update all pods in the namespace kubectl annotate pods --all description='my frontend running nginx' # Update pod 'foo' only if the resource is unchanged from version 1. kubectl annotate pods foo description='my frontend running nginx' --resource-version=1 # Update pod 'foo' by removing an annotation named 'description' if it exists. # Does not require the --overwrite flag. kubectl annotate pods foo description-`)) ) func NewAnnotateOptions(ioStreams genericclioptions.IOStreams) *AnnotateOptions { return &AnnotateOptions{ PrintFlags: genericclioptions.NewPrintFlags("annotated").WithTypeSetter(scheme.Scheme), RecordFlags: genericclioptions.NewRecordFlags(), Recorder: genericclioptions.NoopRecorder{}, IOStreams: ioStreams, } } func NewCmdAnnotate(parent string, f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command { o := NewAnnotateOptions(ioStreams) cmd := &cobra.Command{ Use: "annotate [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]", DisableFlagsInUseLine: true, Short: i18n.T("Update the annotations on a resource"), Long: annotateLong + "\n\n" + cmdutil.SuggestApiResources(parent), Example: annotateExample, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(o.Complete(f, cmd, args)) cmdutil.CheckErr(o.Validate()) cmdutil.CheckErr(o.RunAnnotate()) }, } // bind flag structs o.RecordFlags.AddFlags(cmd) o.PrintFlags.AddFlags(cmd) cmdutil.AddIncludeUninitializedFlag(cmd) cmd.Flags().BoolVar(&o.overwrite, "overwrite", o.overwrite, "If true, allow annotations to be overwritten, otherwise reject annotation updates that overwrite existing annotations.") cmd.Flags().BoolVar(&o.local, "local", o.local, "If true, annotation will NOT contact api-server but run locally.") cmd.Flags().StringVarP(&o.selector, "selector", "l", o.selector, "Selector (label query) to filter on, not including uninitialized ones, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2).") cmd.Flags().StringVar(&o.fieldSelector, "field-selector", o.fieldSelector, "Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.") cmd.Flags().BoolVar(&o.all, "all", o.all, "Select all resources, including uninitialized ones, in the namespace of the specified resource types.") cmd.Flags().StringVar(&o.resourceVersion, "resource-version", o.resourceVersion, i18n.T("If non-empty, the annotation update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource.")) usage := "identifying the resource to update the annotation" cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, usage) cmdutil.AddDryRunFlag(cmd) return cmd } // Complete adapts from the command line args and factory to the data required. func (o *AnnotateOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error { var err error o.RecordFlags.Complete(cmd) o.Recorder, err = o.RecordFlags.ToRecorder() if err != nil { return err } o.outputFormat = cmdutil.GetFlagString(cmd, "output") o.dryrun = cmdutil.GetDryRunFlag(cmd) if o.dryrun { o.PrintFlags.Complete("%s (dry run)") } printer, err := o.PrintFlags.ToPrinter() if err != nil { return err } o.PrintObj = func(obj runtime.Object, out io.Writer) error { return printer.PrintObj(obj, out) } o.namespace, o.enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace() if err != nil { return err } o.includeUninitialized = cmdutil.ShouldIncludeUninitialized(cmd, false) o.builder = f.NewBuilder() o.unstructuredClientForMapping = f.UnstructuredClientForMapping // retrieves resource and annotation args from args // also checks args to verify that all resources are specified before annotations resources, annotationArgs, err := cmdutil.GetResourcesAndPairs(args, "annotation") if err != nil { return err } o.resources = resources o.newAnnotations, o.removeAnnotations, err = parseAnnotations(annotationArgs) if err != nil { return err } return nil } // Validate checks to the AnnotateOptions to see if there is sufficient information run the command. func (o AnnotateOptions) Validate() error { if o.all && len(o.selector) > 0 { return fmt.Errorf("cannot set --all and --selector at the same time") } if o.all && len(o.fieldSelector) > 0 { return fmt.Errorf("cannot set --all and --field-selector at the same time") } if len(o.resources) < 1 && cmdutil.IsFilenameSliceEmpty(o.Filenames) { return fmt.Errorf("one or more resources must be specified as <resource> <name> or <resource>/<name>") } if len(o.newAnnotations) < 1 && len(o.removeAnnotations) < 1 { return fmt.Errorf("at least one annotation update is required") } return validateAnnotations(o.removeAnnotations, o.newAnnotations) } // RunAnnotate does the work func (o AnnotateOptions) RunAnnotate() error { b := o.builder. Unstructured(). LocalParam(o.local). ContinueOnError(). NamespaceParam(o.namespace).DefaultNamespace(). FilenameParam(o.enforceNamespace, &o.FilenameOptions). IncludeUninitialized(o.includeUninitialized). Flatten() if !o.local { b = b.LabelSelectorParam(o.selector). FieldSelectorParam(o.fieldSelector). ResourceTypeOrNameArgs(o.all, o.resources...). Latest() } r := b.Do() if err := r.Err(); err != nil { return err } var singleItemImpliedResource bool r.IntoSingleItemImplied(&singleItemImpliedResource) // only apply resource version locking on a single resource. // we must perform this check after o.builder.Do() as // []o.resources can not not accurately return the proper number // of resources when they are not passed in "resource/name" format. if !singleItemImpliedResource && len(o.resourceVersion) > 0 { return fmt.Errorf("--resource-version may only be used with a single resource") } return r.Visit(func(info *resource.Info, err error) error { if err != nil { return err } var outputObj runtime.Object obj := info.Object if o.dryrun || o.local { if err := o.updateAnnotations(obj); err != nil { return err } outputObj = obj } else { name, namespace := info.Name, info.Namespace oldData, err := json.Marshal(obj) if err != nil { return err } if err := o.Recorder.Record(info.Object); err != nil { glog.V(4).Infof("error recording current command: %v", err) } if err := o.updateAnnotations(obj); err != nil { return err } newData, err := json.Marshal(obj) if err != nil { return err } patchBytes, err := jsonpatch.CreateMergePatch(oldData, newData) createdPatch := err == nil if err != nil { glog.V(2).Infof("couldn't compute patch: %v", err) } mapping := info.ResourceMapping() client, err := o.unstructuredClientForMapping(mapping) if err != nil { return err } helper := resource.NewHelper(client, mapping) if createdPatch { outputObj, err = helper.Patch(namespace, name, types.MergePatchType, patchBytes) } else { outputObj, err = helper.Replace(namespace, name, false, obj) } if err != nil { return err } } return o.PrintObj(outputObj, o.Out) }) } // parseAnnotations retrieves new and remove annotations from annotation args func parseAnnotations(annotationArgs []string) (map[string]string, []string, error) { return cmdutil.ParsePairs(annotationArgs, "annotation", true) } // validateAnnotations checks the format of annotation args and checks removed annotations aren't in the new annotations map func validateAnnotations(removeAnnotations []string, newAnnotations map[string]string) error { var modifyRemoveBuf bytes.Buffer for _, removeAnnotation := range removeAnnotations { if _, found := newAnnotations[removeAnnotation]; found { if modifyRemoveBuf.Len() > 0 { modifyRemoveBuf.WriteString(", ") } modifyRemoveBuf.WriteString(fmt.Sprintf(removeAnnotation)) } } if modifyRemoveBuf.Len() > 0 { return fmt.Errorf("can not both modify and remove the following annotation(s) in the same command: %s", modifyRemoveBuf.String()) } return nil } // validateNoAnnotationOverwrites validates that when overwrite is false, to-be-updated annotations don't exist in the object annotation map (yet) func validateNoAnnotationOverwrites(accessor metav1.Object, annotations map[string]string) error { var buf bytes.Buffer for key := range annotations { // change-cause annotation can always be overwritten if key == kubectl.ChangeCauseAnnotation { continue } if value, found := accessor.GetAnnotations()[key]; found { if buf.Len() > 0 { buf.WriteString("; ") } buf.WriteString(fmt.Sprintf("'%s' already has a value (%s)", key, value)) } } if buf.Len() > 0 { return fmt.Errorf("--overwrite is false but found the following declared annotation(s): %s", buf.String()) } return nil } // updateAnnotations updates annotations of obj func (o AnnotateOptions) updateAnnotations(obj runtime.Object) error { accessor, err := meta.Accessor(obj) if err != nil { return err } if !o.overwrite { if err := validateNoAnnotationOverwrites(accessor, o.newAnnotations); err != nil { return err } } annotations := accessor.GetAnnotations() if annotations == nil { annotations = make(map[string]string) } for key, value := range o.newAnnotations { annotations[key] = value } for _, annotation := range o.removeAnnotations { delete(annotations, annotation) } accessor.SetAnnotations(annotations) if len(o.resourceVersion) != 0 { accessor.SetResourceVersion(o.resourceVersion) } return nil }
Java
--- title: Span page_title: Span | UI for WinForms Documentation description: Span slug: winforms/richtextbox-(obsolete)/features/document-elements/span tags: span published: True position: 4 previous_url: richtextbox-features-document-elements-span --- # Span The __Span__ class represents an inline object that allows you to display formatted text. The __Spans__ can only be used in the context of a __Paragraph__ class. As the spans are inline elements they get placed one after another and the text inside them gets wrapped to the next line if the space is insufficient. This topic demonstrates how to: * [Use Spans](#use-spans) * [Add Text to a Span](#add-text-to-a-span) * [Customize a Span](#customize-a-span) ## Use Spans The __Spans__can be used only in the context of the [Paragraph]({%slug winforms/richtextbox-(obsolete)/features/document-elements/paragraph%}) element. The __Paragraph__ exposes a collection of Inlines, to which the spans can be added. {{source=..\SamplesCS\RichTextBox\Features\Document Elements\RichTextBoxSpan.cs region=UseSpans}} {{source=..\SamplesVB\RichTextBox\Features\Document Elements\RichTextBoxSpan.vb region=UseSpans}} ````C# Section section = new Section(); Paragraph paragraph = new Paragraph(); Span span = new Span("Span declared in code-behind"); paragraph.Inlines.Add(span); section.Blocks.Add(paragraph); this.radRichTextBox1.Document.Sections.Add(section); ```` ````VB.NET Dim section As New Section() Dim paragraph As New Paragraph() Dim span As New Span("Span declared in code-behind") paragraph.Inlines.Add(span) section.Blocks.Add(paragraph) Me.RadRichTextBox1.Document.Sections.Add(section) ```` {{endregion}} ## Add Text to a Span To specify the text in the __Span__ you can use its __Text__ property. {{source=..\SamplesCS\RichTextBox\Features\Document Elements\RichTextBoxSpan.cs region=AddTextToSpan}} {{source=..\SamplesVB\RichTextBox\Features\Document Elements\RichTextBoxSpan.vb region=AddTextToSpan}} ````C# Span mySpan = new Span(); mySpan.Text = "Thank you for choosing Telerik RadRichTextBox!"; ```` ````VB.NET Dim mySpan As New Span() mySpan.Text = "Thank you for choosing Telerik RadRichTextBox!" ```` {{endregion}} >caution The Text property of Span cannot be set to an empty string, as Spans that do not contain any text are considered invalid. If you add an empty Span in the document programmatically, an exception will be thrown. > ## Customize a Span The __Span__ exposes several properties that allow you to customize the layout of the elements placed underneath it. Here is a list of them: * __BaselineAlignment__ - indicates whether the text is __Baseline__, __Subscript__ or __Superscript__. * __FontFamily__ - represents the name of the text's font. * __FontSize__ - represent the size of the text. * __FontStyle__ - indicates whether the text should have its style set to bold, italic or to normal. * __ForeColor__ - represents the foreground color for the text. * __HighlightColor__ - represents the background color for the text. * __Strikethrough__ - indicates whether the text should be stroke through. * __UnderlineType__ - indicates whether the text should be underlined.
Java
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.adwords.jaxws.v201809.cm; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * * Returns a list of CampaignSharedSets based on the given selector. * @param selector the selector specifying the query * @return a list of CampaignSharedSet entities that meet the criterion specified * by the selector * @throws ApiException * * * <p>Java class for get element declaration. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;element name="get"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="selector" type="{https://adwords.google.com/api/adwords/cm/v201809}Selector" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "selector" }) @XmlRootElement(name = "get") public class CampaignSharedSetServiceInterfaceget { protected Selector selector; /** * Gets the value of the selector property. * * @return * possible object is * {@link Selector } * */ public Selector getSelector() { return selector; } /** * Sets the value of the selector property. * * @param value * allowed object is * {@link Selector } * */ public void setSelector(Selector value) { this.selector = value; } }
Java
/* Copyright 2018 The Knative 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 testing import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" fakeapiextensionsclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/fake" apiextensionsv1listers "k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" fakekubeclientset "k8s.io/client-go/kubernetes/fake" appsv1listers "k8s.io/client-go/listers/apps/v1" corev1listers "k8s.io/client-go/listers/core/v1" rbacv1listers "k8s.io/client-go/listers/rbac/v1" "k8s.io/client-go/tools/cache" sourcesv1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" fakeeventingclientset "knative.dev/eventing/pkg/client/clientset/versioned/fake" sourcev1beta2listers "knative.dev/eventing/pkg/client/listers/sources/v1beta2" duckv1 "knative.dev/pkg/apis/duck/v1" "knative.dev/pkg/reconciler/testing" ) var subscriberAddToScheme = func(scheme *runtime.Scheme) error { scheme.AddKnownTypeWithName(schema.GroupVersionKind{Group: "testing.eventing.knative.dev", Version: "v1", Kind: "Subscriber"}, &unstructured.Unstructured{}) return nil } var sourceAddToScheme = func(scheme *runtime.Scheme) error { scheme.AddKnownTypeWithName(schema.GroupVersionKind{Group: "testing.sources.knative.dev", Version: "v1", Kind: "TestSource"}, &duckv1.Source{}) return nil } var clientSetSchemes = []func(*runtime.Scheme) error{ fakekubeclientset.AddToScheme, fakeeventingclientset.AddToScheme, fakeapiextensionsclientset.AddToScheme, subscriberAddToScheme, sourceAddToScheme, } type Listers struct { sorter testing.ObjectSorter } func NewScheme() *runtime.Scheme { scheme := runtime.NewScheme() for _, addTo := range clientSetSchemes { addTo(scheme) } return scheme } func NewListers(objs []runtime.Object) Listers { scheme := runtime.NewScheme() for _, addTo := range clientSetSchemes { addTo(scheme) } ls := Listers{ sorter: testing.NewObjectSorter(scheme), } ls.sorter.AddObjects(objs...) return ls } func (l *Listers) indexerFor(obj runtime.Object) cache.Indexer { return l.sorter.IndexerForObjectType(obj) } func (l *Listers) GetKubeObjects() []runtime.Object { return l.sorter.ObjectsForSchemeFunc(fakekubeclientset.AddToScheme) } func (l *Listers) GetEventingObjects() []runtime.Object { return l.sorter.ObjectsForSchemeFunc(fakeeventingclientset.AddToScheme) } func (l *Listers) GetAPIExtentionsObjects() []runtime.Object { return l.sorter.ObjectsForSchemeFunc(fakeapiextensionsclientset.AddToScheme) } func (l *Listers) GetSubscriberObjects() []runtime.Object { return l.sorter.ObjectsForSchemeFunc(subscriberAddToScheme) } func (l *Listers) GetAllObjects() []runtime.Object { all := l.GetSubscriberObjects() all = append(all, l.GetEventingObjects()...) all = append(all, l.GetKubeObjects()...) return all } func (l *Listers) GetPingSourceV1beta2Lister() sourcev1beta2listers.PingSourceLister { return sourcev1beta2listers.NewPingSourceLister(l.indexerFor(&sourcesv1beta2.PingSource{})) } func (l *Listers) GetDeploymentLister() appsv1listers.DeploymentLister { return appsv1listers.NewDeploymentLister(l.indexerFor(&appsv1.Deployment{})) } func (l *Listers) GetK8sServiceLister() corev1listers.ServiceLister { return corev1listers.NewServiceLister(l.indexerFor(&corev1.Service{})) } func (l *Listers) GetSecretLister() corev1listers.SecretLister { return corev1listers.NewSecretLister(l.indexerFor(&corev1.Secret{})) } func (l *Listers) GetNamespaceLister() corev1listers.NamespaceLister { return corev1listers.NewNamespaceLister(l.indexerFor(&corev1.Namespace{})) } func (l *Listers) GetServiceAccountLister() corev1listers.ServiceAccountLister { return corev1listers.NewServiceAccountLister(l.indexerFor(&corev1.ServiceAccount{})) } func (l *Listers) GetServiceLister() corev1listers.ServiceLister { return corev1listers.NewServiceLister(l.indexerFor(&corev1.Service{})) } func (l *Listers) GetRoleBindingLister() rbacv1listers.RoleBindingLister { return rbacv1listers.NewRoleBindingLister(l.indexerFor(&rbacv1.RoleBinding{})) } func (l *Listers) GetEndpointsLister() corev1listers.EndpointsLister { return corev1listers.NewEndpointsLister(l.indexerFor(&corev1.Endpoints{})) } func (l *Listers) GetConfigMapLister() corev1listers.ConfigMapLister { return corev1listers.NewConfigMapLister(l.indexerFor(&corev1.ConfigMap{})) } func (l *Listers) GetCustomResourceDefinitionLister() apiextensionsv1listers.CustomResourceDefinitionLister { return apiextensionsv1listers.NewCustomResourceDefinitionLister(l.indexerFor(&apiextensionsv1.CustomResourceDefinition{})) }
Java
# AUTOGENERATED FILE FROM balenalib/jetson-tx1-fedora:34-run ENV GO_VERSION 1.16.3 # gcc for cgo RUN dnf install -y \ gcc-c++ \ gcc \ git \ && dnf clean all RUN mkdir -p /usr/local/go \ && curl -SLO "https://storage.googleapis.com/golang/go$GO_VERSION.linux-arm64.tar.gz" \ && echo "f4e96bbcd5d2d1942f5b55d9e4ab19564da4fad192012f6d7b0b9b055ba4208f go$GO_VERSION.linux-arm64.tar.gz" | sha256sum -c - \ && tar -xzf "go$GO_VERSION.linux-arm64.tar.gz" -C /usr/local/go --strip-components=1 \ && rm -f go$GO_VERSION.linux-arm64.tar.gz ENV GOROOT /usr/local/go ENV GOPATH /go ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH" WORKDIR $GOPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@golang.sh" \ && echo "Running test-stack@golang" \ && chmod +x test-stack@golang.sh \ && bash test-stack@golang.sh \ && rm -rf test-stack@golang.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Fedora 34 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.16.3 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
Java
# Using git with proxy Git-sync supports using a proxy through git-configuration. ## Background See [issue 180](https://github.com/kubernetes/git-sync/issues/180) for a background. See [Github documentation](https://docs.github.com/en/github/authenticating-to-github/using-ssh-over-the-https-port) specifically for GitHub. Lastly, [see similar issue for FluxCD](https://github.com/fluxcd/flux/pull/3152) for configuration. ## Step 1: Create configuration Create a ConfigMap to store your configuration: ```bash cat << EOF >> /tmp/ssh-config Host github.com ProxyCommand socat STDIO PROXY:<proxyIP>:%h:%p,proxyport=<proxyport>,proxyauth=<proxyAuth> User git Hostname ssh.github.com Port 443 IdentityFile /etc/git-secret/ssh EOF kubectl create configmap ssh-config --from-file=ssh-config=/tmp/ssh-config ``` then mount this under `~/.ssh/config`, typically `/tmp/.ssh/config`: ```yaml ... apiVersion: v1 kind: Pod ... spec: containers: - name: git-sync ... volumeMounts: - name: ssh-config mountPath: /tmp/.ssh/config readOnly: true subPath: ssh-config volumes: - name: ssh-config configMap: name: ssh-config ```
Java
/** * AET * * Copyright (C) 2013 Cognifide Limited * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * Copyright [2016] [http://bmp.lightbody.net/] * * 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.browsermob.core.json; import java.io.IOException; import java.lang.reflect.Type; import java.text.DateFormat; import java.util.Date; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.SerializerProvider; import org.codehaus.jackson.map.ser.ScalarSerializerBase; public class ISO8601DateFormatter extends ScalarSerializerBase<Date> { public final static ISO8601DateFormatter instance = new ISO8601DateFormatter(); public ISO8601DateFormatter() { super(Date.class); } @Override public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { DateFormat df = (DateFormat) provider.getConfig().getDateFormat().clone(); jgen.writeString(df.format(value)); } @Override public JsonNode getSchema(SerializerProvider provider, Type typeHint) throws JsonMappingException { return createSchemaNode("string", true); } }
Java
package org.apache.lucene.index; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import org.apache.lucene.analysis.tokenattributes.OffsetAttribute; import org.apache.lucene.analysis.tokenattributes.PayloadAttribute; import org.apache.lucene.codecs.TermVectorsWriter; import org.apache.lucene.util.ByteBlockPool; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.RamUsageEstimator; final class TermVectorsConsumerPerField extends TermsHashConsumerPerField { final TermsHashPerField termsHashPerField; final TermVectorsConsumer termsWriter; final FieldInfo fieldInfo; final DocumentsWriterPerThread.DocState docState; final FieldInvertState fieldState; boolean doVectors; boolean doVectorPositions; boolean doVectorOffsets; boolean doVectorPayloads; int maxNumPostings; OffsetAttribute offsetAttribute; PayloadAttribute payloadAttribute; boolean hasPayloads; // if enabled, and we actually saw any for this field public TermVectorsConsumerPerField(TermsHashPerField termsHashPerField, TermVectorsConsumer termsWriter, FieldInfo fieldInfo) { this.termsHashPerField = termsHashPerField; this.termsWriter = termsWriter; this.fieldInfo = fieldInfo; docState = termsHashPerField.docState; fieldState = termsHashPerField.fieldState; } @Override int getStreamCount() { return 2; } @Override boolean start(IndexableField[] fields, int count) { doVectors = false; doVectorPositions = false; doVectorOffsets = false; doVectorPayloads = false; hasPayloads = false; for(int i=0;i<count;i++) { IndexableField field = fields[i]; if (field.fieldType().indexed()) { if (field.fieldType().storeTermVectors()) { doVectors = true; doVectorPositions |= field.fieldType().storeTermVectorPositions(); doVectorOffsets |= field.fieldType().storeTermVectorOffsets(); if (doVectorPositions) { doVectorPayloads |= field.fieldType().storeTermVectorPayloads(); } else if (field.fieldType().storeTermVectorPayloads()) { // TODO: move this check somewhere else, and impl the other missing ones throw new IllegalArgumentException("cannot index term vector payloads without term vector positions (field=\"" + field.name() + "\")"); } } else { if (field.fieldType().storeTermVectorOffsets()) { throw new IllegalArgumentException("cannot index term vector offsets when term vectors are not indexed (field=\"" + field.name() + "\")"); } if (field.fieldType().storeTermVectorPositions()) { throw new IllegalArgumentException("cannot index term vector positions when term vectors are not indexed (field=\"" + field.name() + "\")"); } if (field.fieldType().storeTermVectorPayloads()) { throw new IllegalArgumentException("cannot index term vector payloads when term vectors are not indexed (field=\"" + field.name() + "\")"); } } } else { if (field.fieldType().storeTermVectors()) { throw new IllegalArgumentException("cannot index term vectors when field is not indexed (field=\"" + field.name() + "\")"); } if (field.fieldType().storeTermVectorOffsets()) { throw new IllegalArgumentException("cannot index term vector offsets when field is not indexed (field=\"" + field.name() + "\")"); } if (field.fieldType().storeTermVectorPositions()) { throw new IllegalArgumentException("cannot index term vector positions when field is not indexed (field=\"" + field.name() + "\")"); } if (field.fieldType().storeTermVectorPayloads()) { throw new IllegalArgumentException("cannot index term vector payloads when field is not indexed (field=\"" + field.name() + "\")"); } } } if (doVectors) { termsWriter.hasVectors = true; if (termsHashPerField.bytesHash.size() != 0) { // Only necessary if previous doc hit a // non-aborting exception while writing vectors in // this field: termsHashPerField.reset(); } } // TODO: only if needed for performance //perThread.postingsCount = 0; return doVectors; } public void abort() {} /** Called once per field per document if term vectors * are enabled, to write the vectors to * RAMOutputStream, which is then quickly flushed to * the real term vectors files in the Directory. */ @Override void finish() { if (!doVectors || termsHashPerField.bytesHash.size() == 0) { return; } termsWriter.addFieldToFlush(this); } void finishDocument() throws IOException { assert docState.testPoint("TermVectorsTermsWriterPerField.finish start"); final int numPostings = termsHashPerField.bytesHash.size(); final BytesRef flushTerm = termsWriter.flushTerm; assert numPostings >= 0; if (numPostings > maxNumPostings) maxNumPostings = numPostings; // This is called once, after inverting all occurrences // of a given field in the doc. At this point we flush // our hash into the DocWriter. assert termsWriter.vectorFieldsInOrder(fieldInfo); TermVectorsPostingsArray postings = (TermVectorsPostingsArray) termsHashPerField.postingsArray; final TermVectorsWriter tv = termsWriter.writer; final int[] termIDs = termsHashPerField.sortPostings(); tv.startField(fieldInfo, numPostings, doVectorPositions, doVectorOffsets, hasPayloads); final ByteSliceReader posReader = doVectorPositions ? termsWriter.vectorSliceReaderPos : null; final ByteSliceReader offReader = doVectorOffsets ? termsWriter.vectorSliceReaderOff : null; final ByteBlockPool termBytePool = termsHashPerField.termBytePool; for(int j=0;j<numPostings;j++) { final int termID = termIDs[j]; final int freq = postings.freqs[termID]; // Get BytesRef termBytePool.setBytesRef(flushTerm, postings.textStarts[termID]); tv.startTerm(flushTerm, freq); if (doVectorPositions || doVectorOffsets) { if (posReader != null) { termsHashPerField.initReader(posReader, termID, 0); } if (offReader != null) { termsHashPerField.initReader(offReader, termID, 1); } tv.addProx(freq, posReader, offReader); } tv.finishTerm(); } tv.finishField(); termsHashPerField.reset(); fieldInfo.setStoreTermVectors(); } @Override void start(IndexableField f) { if (doVectorOffsets) { offsetAttribute = fieldState.attributeSource.addAttribute(OffsetAttribute.class); } else { offsetAttribute = null; } if (doVectorPayloads && fieldState.attributeSource.hasAttribute(PayloadAttribute.class)) { payloadAttribute = fieldState.attributeSource.getAttribute(PayloadAttribute.class); } else { payloadAttribute = null; } } void writeProx(TermVectorsPostingsArray postings, int termID) { if (doVectorOffsets) { int startOffset = fieldState.offset + offsetAttribute.startOffset(); int endOffset = fieldState.offset + offsetAttribute.endOffset(); termsHashPerField.writeVInt(1, startOffset - postings.lastOffsets[termID]); termsHashPerField.writeVInt(1, endOffset - startOffset); postings.lastOffsets[termID] = endOffset; } if (doVectorPositions) { final BytesRef payload; if (payloadAttribute == null) { payload = null; } else { payload = payloadAttribute.getPayload(); } final int pos = fieldState.position - postings.lastPositions[termID]; if (payload != null && payload.length > 0) { termsHashPerField.writeVInt(0, (pos<<1)|1); termsHashPerField.writeVInt(0, payload.length); termsHashPerField.writeBytes(0, payload.bytes, payload.offset, payload.length); hasPayloads = true; } else { termsHashPerField.writeVInt(0, pos<<1); } postings.lastPositions[termID] = fieldState.position; } } @Override void newTerm(final int termID) { assert docState.testPoint("TermVectorsTermsWriterPerField.newTerm start"); TermVectorsPostingsArray postings = (TermVectorsPostingsArray) termsHashPerField.postingsArray; postings.freqs[termID] = 1; postings.lastOffsets[termID] = 0; postings.lastPositions[termID] = 0; writeProx(postings, termID); } @Override void addTerm(final int termID) { assert docState.testPoint("TermVectorsTermsWriterPerField.addTerm start"); TermVectorsPostingsArray postings = (TermVectorsPostingsArray) termsHashPerField.postingsArray; postings.freqs[termID]++; writeProx(postings, termID); } @Override void skippingLongTerm() {} @Override ParallelPostingsArray createPostingsArray(int size) { return new TermVectorsPostingsArray(size); } static final class TermVectorsPostingsArray extends ParallelPostingsArray { public TermVectorsPostingsArray(int size) { super(size); freqs = new int[size]; lastOffsets = new int[size]; lastPositions = new int[size]; } int[] freqs; // How many times this term occurred in the current doc int[] lastOffsets; // Last offset we saw int[] lastPositions; // Last position where this term occurred @Override ParallelPostingsArray newInstance(int size) { return new TermVectorsPostingsArray(size); } @Override void copyTo(ParallelPostingsArray toArray, int numToCopy) { assert toArray instanceof TermVectorsPostingsArray; TermVectorsPostingsArray to = (TermVectorsPostingsArray) toArray; super.copyTo(toArray, numToCopy); System.arraycopy(freqs, 0, to.freqs, 0, size); System.arraycopy(lastOffsets, 0, to.lastOffsets, 0, size); System.arraycopy(lastPositions, 0, to.lastPositions, 0, size); } @Override int bytesPerPosting() { return super.bytesPerPosting() + 3 * RamUsageEstimator.NUM_BYTES_INT; } } }
Java
# # Author:: Scott Bonds (scott@ggr.com) # Copyright:: Copyright 2014-2016, Scott Bonds # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "spec_helper" require "ostruct" describe Chef::Provider::Package::Openbsd do let(:node) do node = Chef::Node.new node.default["kernel"] = { "name" => "OpenBSD", "release" => "5.5", "machine" => "amd64" } node end let (:provider) do events = Chef::EventDispatch::Dispatcher.new run_context = Chef::RunContext.new(node, {}, events) Chef::Provider::Package::Openbsd.new(new_resource, run_context) end let(:new_resource) { Chef::Resource::Package.new(name) } before(:each) do ENV["PKG_PATH"] = nil end describe "install a package" do let(:name) { "ihavetoes" } let(:version) { "0.0" } context "when not already installed" do before do allow(provider).to receive(:shell_out_compacted!).with("pkg_info", "-e", "#{name}->0", anything).and_return(instance_double("shellout", stdout: "")) end context "when there is a single candidate" do context "when source is not provided" do it "should run the installation command" do expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", name, anything).and_return( instance_double("shellout", stdout: "#{name}-#{version}\n") ) expect(provider).to receive(:shell_out_compacted!).with( "pkg_add", "-r", "#{name}-#{version}", { env: { "PKG_PATH" => "http://ftp.OpenBSD.org/pub/OpenBSD/5.5/packages/amd64/" }, timeout: 900 } ) { OpenStruct.new status: true } provider.run_action(:install) end end end context "when there are multiple candidates" do let(:flavor_a) { "flavora" } let(:flavor_b) { "flavorb" } context "if no version is specified" do it "should raise an exception" do expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", name, anything).and_return( instance_double("shellout", stdout: "#{name}-#{version}-#{flavor_a}\n#{name}-#{version}-#{flavor_b}\n") ) expect { provider.run_action(:install) }.to raise_error(Chef::Exceptions::Package, /multiple matching candidates/) end end context "if a flavor is specified" do let(:flavor) { "flavora" } let(:package_name) { "ihavetoes" } let(:name) { "#{package_name}--#{flavor}" } context "if no version is specified" do it "should run the installation command" do expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-e", "#{package_name}->0", anything).and_return(instance_double("shellout", stdout: "")) expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", name, anything).and_return( instance_double("shellout", stdout: "#{name}-#{version}-#{flavor}\n") ) expect(provider).to receive(:shell_out_compacted!).with( "pkg_add", "-r", "#{name}-#{version}-#{flavor}", { env: { "PKG_PATH" => "http://ftp.OpenBSD.org/pub/OpenBSD/5.5/packages/amd64/" }, timeout: 900 } ) { OpenStruct.new status: true } provider.run_action(:install) end end end context "if a version is specified" do it "should use the flavor from the version" do expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", "#{name}-#{version}-#{flavor_b}", anything).and_return( instance_double("shellout", stdout: "#{name}-#{version}-#{flavor_a}\n") ) new_resource.version("#{version}-#{flavor_b}") expect(provider).to receive(:shell_out_compacted!).with( "pkg_add", "-r", "#{name}-#{version}-#{flavor_b}", { env: { "PKG_PATH" => "http://ftp.OpenBSD.org/pub/OpenBSD/5.5/packages/amd64/" }, timeout: 900 } ) { OpenStruct.new status: true } provider.run_action(:install) end end end end end describe "delete a package" do before do @name = "ihavetoes" @new_resource = Chef::Resource::Package.new(@name) @current_resource = Chef::Resource::Package.new(@name) @provider = Chef::Provider::Package::Openbsd.new(@new_resource, @run_context) @provider.current_resource = @current_resource end it "should run the command to delete the installed package" do expect(@provider).to receive(:shell_out_compacted!).with( "pkg_delete", @name, env: nil, timeout: 900 ) { OpenStruct.new status: true } @provider.remove_package(@name, nil) end end end
Java
/* * Copyright 2011 Ning, Inc. * * Ning 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 com.mogwee.executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * Factory that sets the name of each thread it creates to {@code [name]-[id]}. * This makes debugging stack traces much easier. */ public class NamedThreadFactory implements ThreadFactory { private final AtomicInteger count = new AtomicInteger(0); private final String name; public NamedThreadFactory(String name) { this.name = name; } @Override public Thread newThread(final Runnable runnable) { Thread thread = new Thread(runnable); thread.setName(name + "-" + count.incrementAndGet()); return thread; } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_11) on Mon Oct 19 11:00:57 CEST 2009 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.apache.mina.statemachine.annotation.IoHandlerTransitions (Apache MINA 2.0.0-RC1 API Documentation) </TITLE> <META NAME="date" CONTENT="2009-10-19"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.mina.statemachine.annotation.IoHandlerTransitions (Apache MINA 2.0.0-RC1 API Documentation)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/mina/statemachine/annotation/IoHandlerTransitions.html" title="annotation in org.apache.mina.statemachine.annotation"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/mina/statemachine/annotation//class-useIoHandlerTransitions.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="IoHandlerTransitions.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.mina.statemachine.annotation.IoHandlerTransitions</B></H2> </CENTER> No usage of org.apache.mina.statemachine.annotation.IoHandlerTransitions <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/mina/statemachine/annotation/IoHandlerTransitions.html" title="annotation in org.apache.mina.statemachine.annotation"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/mina/statemachine/annotation//class-useIoHandlerTransitions.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="IoHandlerTransitions.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2004-2009 <a href="http://mina.apache.org/">Apache MINA Project</a>. All Rights Reserved. </BODY> </HTML>
Java
# # farmwork/forms.py # from django import forms from django.utils.text import slugify from .models import Farmwork # ======================================================== # FARMWORK FORM # ======================================================== class FarmworkForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(FarmworkForm, self).__init__(*args, **kwargs) class Meta: model = Farmwork fields = [ 'job_role', 'job_fruit', 'job_pay', 'job_pay_type', 'job_start_date', 'job_duration', 'job_duration_type', 'job_description', 'con_first_name', 'con_surname', 'con_number', 'con_email', 'con_description', 'acc_variety', 'acc_price', 'acc_price_type', 'acc_description', 'loc_street_address', 'loc_city', 'loc_state', 'loc_post_code', ] # -- # AUTO GENERATE SLUG ON SAVE # Credit: https://keyerror.com/blog/automatically-generating-unique-slugs-in-django # -- def save(self): if self.instance.pk: return super(FarmworkForm, self).save() instance = super(FarmworkForm, self).save(commit=False) instance.slug = slugify(instance.get_job_fruit_display() + '-' + instance.get_job_role_display() + '-in-' + instance.loc_city) instance.save() return instance
Java
namespace Konves.ChordPro.Directives { public sealed class CommentBoxDirective : Directive { public CommentBoxDirective(string text) { Text = text; } public string Text { get; set; } } }
Java
from django.contrib.auth.models import AnonymousUser from core.models import Identity from api.v2.serializers.post import AccountSerializer from api.v2.views.base import AdminAuthViewSet class AccountViewSet(AdminAuthViewSet): """ API endpoint that allows providers to be viewed or edited. """ lookup_fields = ("id", "uuid") queryset = Identity.objects.all() serializer_class = AccountSerializer http_method_names = ['post', 'head', 'options', 'trace'] def get_queryset(self): """ Filter providers by current user """ user = self.request.user if (type(user) == AnonymousUser): return Identity.objects.none() identities = user.current_identities() return identities
Java
--- title: raft(2) categories: 分布式算法 tags: Raft --- ## 概念 ### 1. Term ![term](../images/raft/raft_term.png) raft中,将时间划分成了一段一段的,每一段成为一个term。每当发起一次领导竞选(leader election)时,term会加1。 由图可以看到蓝色为election时期,绿色为leader带领follower正常操作时期。但也可以看到term3只有leader election,且之后马上又是leader election,但term已经变为4了。但term3到term4这是怎么回事呢?不急慢慢来,暂且先明白term的含义 ### 2. HeartBeat raft算法是一个分区容错共识算法,因此它需要具有判断分区是否发生故障。leader节点会每隔一段时间就向follower节点发送一个心跳信息,然后follower节点会返回一个消息,以此来判断节点是否发生故障或者分区故障。这个行为称为heartBeat。 ### 3. election timeout 上面说了,leader节点每隔一段时间会向follower节点发送一个心跳信息。如果leader节点没有发送呢? 如果follower节点在election timeout这个时间内没有收到心跳信息,则会发起新一轮竞选。election timeout和heart beat的时间不一样,且心跳的时间远远小于election timeout ### 4. Role ![raft_role](../images/raft/raft_role.png) 各角色职责: follower: 1. 接收心跳信息 2. 当在election timeout未接收 ## 工具 ### AppendEntries RPC |Arguments:|| |:--:|:--:| |term|leader的term| |leaderId|leader所在服务器id| |prevLogIndex|| |prevLogTerm|| |entries[]|日志数组| |leaderCommit|leader当前已经commit的log index| |**Results:**|| |term|| |success|| ### RequestVote RPC | Arguments: | | | :----------: | :-----------------------------: | | term | candidate的term number | | candidateId | candidate的id | | lastLogIndex | candidate最近一条日志的索引 | | lastLogTerm | candidate最近一条日志的term编号 | | **Results:** | | | term | | | voteGranted | |
Java
<?php $test = array('2004', '2005', '2006'); $test2 = array('1000', '1170', '660'); $end = array_pop($test); $end2 = array_pop($test2); ?> <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi?autoload={ 'modules':[{ 'name':'visualization', 'version':'1', 'packages':['corechart'] }] }"></script> <script type="text/javascript"> google.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Year', 'Sales'], <?php foreach (array_combine($test, $test2) as $nb => $nb2) { echo '["'.$nb.'", '.$nb2."],"; echo "\n"; } echo '["'.$end.'", '.$end2."]"; ?> ]); var options = { title: 'Company Performance', curveType: 'function', legend: { position: 'bottom' } }; var chart = new google.visualization.LineChart(document.getElementById('curve_chart')); chart.draw(data, options); } </script> </head> <body> <div id="curve_chart" style="width: 900px; height: 500px"></div> </body> </html>
Java
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import ApiCreationController from './api-creation.controller'; import { shouldDisplayHint } from './form.helper'; import ApiPrimaryOwnerModeService from '../../../../services/apiPrimaryOwnerMode.service'; const ApiCreationStep1Component: ng.IComponentOptions = { require: { parent: '^apiCreation', }, template: require('./api-creation-step1.html'), controller: class { private parent: ApiCreationController; private advancedMode: boolean; private useGroupAsPrimaryOwner: boolean; public shouldDisplayHint = shouldDisplayHint; constructor(private ApiPrimaryOwnerModeService: ApiPrimaryOwnerModeService) { 'ngInject'; this.advancedMode = false; this.useGroupAsPrimaryOwner = this.ApiPrimaryOwnerModeService.isGroupOnly(); } toggleAdvancedMode = () => { this.advancedMode = !this.advancedMode; if (!this.advancedMode) { this.parent.api.groups = []; } }; canUseAdvancedMode = () => { return ( (this.ApiPrimaryOwnerModeService.isHybrid() && ((this.parent.attachableGroups && this.parent.attachableGroups.length > 0) || (this.parent.poGroups && this.parent.poGroups.length > 0))) || (this.ApiPrimaryOwnerModeService.isGroupOnly() && this.parent.attachableGroups && this.parent.attachableGroups.length > 0) ); }; }, }; export default ApiCreationStep1Component;
Java
/* * Copyright 2013 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 de.micromata.jira.rest.core.misc; /** * @author Christian Schulze * @author Vitali Filippow */ public interface RestPathConstants { // Common Stuff for Jersey Client String AUTHORIZATION = "Authorization"; String BASIC = "Basic"; // REST Paths String BASE_REST_PATH = "/rest/api/2"; String PROJECT = "/project"; String USER = "/user"; String SEARCH = "/search"; String ISSUE = "/issue"; String COMMENT = "/comment"; String VERSIONS = "/versions"; String COMPONENTS = "/components"; String ISSUETPYES = "/issuetype"; String STATUS = "/status"; String PRIORITY = "/priority"; String TRANSITIONS = "/transitions"; String WORKLOG = "/worklog"; String ATTACHMENTS = "/attachments"; String ATTACHMENT = "/attachment"; String ASSIGNABLE = "/assignable"; String FILTER = "/filter"; String FAVORITE = "/favourite"; String FIELD = "/field"; String META = "/meta"; String CREATEMETA = "/createmeta"; String MYPERMISSIONS = "/mypermissions"; String CONFIGURATION = "/configuration"; }
Java
/***************************************************************************** * Copyright (C) jparsec.org * * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package org.jparsec.examples.sql.parser; import static org.jparsec.examples.sql.parser.TerminalParser.phrase; import static org.jparsec.examples.sql.parser.TerminalParser.term; import java.util.List; import java.util.function.BinaryOperator; import java.util.function.UnaryOperator; import org.jparsec.OperatorTable; import org.jparsec.Parser; import org.jparsec.Parsers; import org.jparsec.examples.sql.ast.BetweenExpression; import org.jparsec.examples.sql.ast.BinaryExpression; import org.jparsec.examples.sql.ast.BinaryRelationalExpression; import org.jparsec.examples.sql.ast.Expression; import org.jparsec.examples.sql.ast.FullCaseExpression; import org.jparsec.examples.sql.ast.FunctionExpression; import org.jparsec.examples.sql.ast.LikeExpression; import org.jparsec.examples.sql.ast.NullExpression; import org.jparsec.examples.sql.ast.NumberExpression; import org.jparsec.examples.sql.ast.Op; import org.jparsec.examples.sql.ast.QualifiedName; import org.jparsec.examples.sql.ast.QualifiedNameExpression; import org.jparsec.examples.sql.ast.Relation; import org.jparsec.examples.sql.ast.SimpleCaseExpression; import org.jparsec.examples.sql.ast.StringExpression; import org.jparsec.examples.sql.ast.TupleExpression; import org.jparsec.examples.sql.ast.UnaryExpression; import org.jparsec.examples.sql.ast.UnaryRelationalExpression; import org.jparsec.examples.sql.ast.WildcardExpression; import org.jparsec.functors.Pair; /** * Parser for expressions. * * @author Ben Yu */ public final class ExpressionParser { static final Parser<Expression> NULL = term("null").<Expression>retn(NullExpression.instance); static final Parser<Expression> NUMBER = TerminalParser.NUMBER.map(NumberExpression::new); static final Parser<Expression> QUALIFIED_NAME = TerminalParser.QUALIFIED_NAME .map(QualifiedNameExpression::new); static final Parser<Expression> QUALIFIED_WILDCARD = TerminalParser.QUALIFIED_NAME .followedBy(phrase(". *")) .map(WildcardExpression::new); static final Parser<Expression> WILDCARD = term("*").<Expression>retn(new WildcardExpression(QualifiedName.of())) .or(QUALIFIED_WILDCARD); static final Parser<Expression> STRING = TerminalParser.STRING.map(StringExpression::new); static Parser<Expression> functionCall(Parser<Expression> param) { return Parsers.sequence( TerminalParser.QUALIFIED_NAME, paren(param.sepBy(TerminalParser.term(","))), FunctionExpression::new); } static Parser<Expression> tuple(Parser<Expression> expr) { return paren(expr.sepBy(term(","))).map(TupleExpression::new); } static Parser<Expression> simpleCase(Parser<Expression> expr) { return Parsers.sequence( term("case").next(expr), whenThens(expr, expr), term("else").next(expr).optional().followedBy(term("end")), SimpleCaseExpression::new); } static Parser<Expression> fullCase(Parser<Expression> cond, Parser<Expression> expr) { return Parsers.sequence( term("case").next(whenThens(cond, expr)), term("else").next(expr).optional().followedBy(term("end")), FullCaseExpression::new); } private static Parser<List<Pair<Expression, Expression>>> whenThens( Parser<Expression> cond, Parser<Expression> expr) { return Parsers.pair(term("when").next(cond), term("then").next(expr)).many1(); } static <T> Parser<T> paren(Parser<T> parser) { return parser.between(term("("), term(")")); } static Parser<Expression> arithmetic(Parser<Expression> atom) { Parser.Reference<Expression> reference = Parser.newReference(); Parser<Expression> operand = Parsers.or(paren(reference.lazy()), functionCall(reference.lazy()), atom); Parser<Expression> parser = new OperatorTable<Expression>() .infixl(binary("+", Op.PLUS), 10) .infixl(binary("-", Op.MINUS), 10) .infixl(binary("*", Op.MUL), 20) .infixl(binary("/", Op.DIV), 20) .infixl(binary("%", Op.MOD), 20) .prefix(unary("-", Op.NEG), 50) .build(operand); reference.set(parser); return parser; } static Parser<Expression> expression(Parser<Expression> cond) { Parser.Reference<Expression> reference = Parser.newReference(); Parser<Expression> lazyExpr = reference.lazy(); Parser<Expression> atom = Parsers.or( NUMBER, WILDCARD, QUALIFIED_NAME, simpleCase(lazyExpr), fullCase(cond, lazyExpr)); Parser<Expression> expression = arithmetic(atom).label("expression"); reference.set(expression); return expression; } /************************** boolean expressions ****************************/ static Parser<Expression> compare(Parser<Expression> expr) { return Parsers.or( compare(expr, ">", Op.GT), compare(expr, ">=", Op.GE), compare(expr, "<", Op.LT), compare(expr, "<=", Op.LE), compare(expr, "=", Op.EQ), compare(expr, "<>", Op.NE), nullCheck(expr), like(expr), between(expr)); } static Parser<Expression> like(Parser<Expression> expr) { return Parsers.sequence( expr, Parsers.or(term("like").retn(true), phrase("not like").retn(false)), expr, term("escape").next(expr).optional(), LikeExpression::new); } static Parser<Expression> nullCheck(Parser<Expression> expr) { return Parsers.sequence( expr, phrase("is not").retn(Op.NOT).or(phrase("is").retn(Op.IS)), NULL, BinaryExpression::new); } static Parser<Expression> logical(Parser<Expression> expr) { Parser.Reference<Expression> ref = Parser.newReference(); Parser<Expression> parser = new OperatorTable<Expression>() .prefix(unary("not", Op.NOT), 30) .infixl(binary("and", Op.AND), 20) .infixl(binary("or", Op.OR), 10) .build(paren(ref.lazy()).or(expr)).label("logical expression"); ref.set(parser); return parser; } static Parser<Expression> between(Parser<Expression> expr) { return Parsers.sequence( expr, Parsers.or(term("between").retn(true), phrase("not between").retn(false)), expr, term("and").next(expr), BetweenExpression::new); } static Parser<Expression> exists(Parser<Relation> relation) { return term("exists").next(relation).map(e -> new UnaryRelationalExpression(e, Op.EXISTS)); } static Parser<Expression> notExists(Parser<Relation> relation) { return phrase("not exists").next(relation) .map(e -> new UnaryRelationalExpression(e, Op.NOT_EXISTS)); } static Parser<Expression> inRelation(Parser<Expression> expr, Parser<Relation> relation) { return Parsers.sequence( expr, Parsers.between(phrase("in ("), relation, term(")")), (e, r) -> new BinaryRelationalExpression(e, Op.IN, r)); } static Parser<Expression> notInRelation(Parser<Expression> expr, Parser<Relation> relation) { return Parsers.sequence( expr, Parsers.between(phrase("not in ("), relation, term(")")), (e, r) -> new BinaryRelationalExpression(e, Op.NOT_IN, r)); } static Parser<Expression> in(Parser<Expression> expr) { return Parsers.sequence( expr, term("in").next(tuple(expr)), (e, t) -> new BinaryExpression(e, Op.IN, t)); } static Parser<Expression> notIn(Parser<Expression> expr) { return Parsers.sequence( expr, phrase("not in").next(tuple(expr)), (e, t) -> new BinaryExpression(e, Op.NOT_IN, t)); } static Parser<Expression> condition(Parser<Expression> expr, Parser<Relation> rel) { Parser<Expression> atom = Parsers.or( compare(expr), in(expr), notIn(expr), exists(rel), notExists(rel), inRelation(expr, rel), notInRelation(expr, rel)); return logical(atom); } /************************** utility methods ****************************/ private static Parser<Expression> compare( Parser<Expression> operand, String name, Op op) { return Parsers.sequence( operand, term(name).retn(op), operand, BinaryExpression::new); } private static Parser<BinaryOperator<Expression>> binary(String name, Op op) { return term(name).retn((l, r) -> new BinaryExpression(l, op, r)); } private static Parser<UnaryOperator<Expression>> unary(String name, Op op) { return term(name).retn(e -> new UnaryExpression(op, e)); } }
Java
--- title: Over the Moon for June! date: 2016-06-01 00:00:00 -06:00 categories: - whats-blooming layout: post blog-banner: whats-blooming-now-summer.jpg post-date: June 01, 2016 post-time: 4:33 PM blog-image: wbn-default.jpg --- <div class="text-center"> Here at the Garden, we are over the moon excited for the warm weather that brings an abundance of flowers. Now that it is June and many of you are out of school and the official start of summer is right around the corner, there is no excuse to not be at Red Butte enjoying nature's splendor.</div> <div class="text-center"> <img src="/images/blogs/Opuntia%20polyacantha%20Flower%20HMS16.jpg" width="560" height="420" alt="" title="" /> <p>Plains Pricklypear &nbsp;&nbsp;<i> Opuntia polyacantha</i></p> <p>This plant may be prickly but it sure is pretty! Can be seen near Hobb's Bench.</p> </div> <div class="text-center"> <img src="/images/blogs/Natural%20Area%20HMS16.jpg" width="560" height="420" alt="" title="" /> <p>Natural Area</p> <p>Be sure to hike through the Natural Area while you are here, the scene is breathtaking.</p> </div> <div class="text-center"> <img src="/images/blogs/Baptisia%20australis%20%27Bluemound%27%20Flower%20HMS16.jpg" width="560" height="1103" alt="" title="" /> <p>Bluemound False Indigo &nbsp;&nbsp;<i> Baptisia australis </i> 'Bluemound'</p> <p>Along the Floral Walk, these exciting flowers are sure to lift your spirits.</p> </div> <div class="text-center"> <img src="/images/blogs/Yucca%20angustissima%20Habit%20and%20Flower%20HMS16.jpg" width="560" height="1088" alt="" title="" /> <p>Narrow-leaf Yucca &nbsp;&nbsp;<i> Yucca angustissima</i></p> <p>These unique flowers are thick and waxy and can only be pollinated by the Pronuba moth. You will find this native beauty at Hobb's Bench.</p> </div> <div class="text-center"> <img src="/images/blogs/Picea%20orientalis%20%27Aureospicata%27%20Habit%20and%20New%20Growth%20HMS16.jpg" width="560" height="810" alt="" title="" /> <p>Golden Candle Oriental Spruce &nbsp;&nbsp;<i> Picea orientalis</i> 'Aureospicata'</p> <p>On the way to Hobb's Bench, check out the wonderful contrast of yellow new growth against the dark green old growth. Amazing right?!</p> </div> <div class="text-center"> The sun is shining, so put on your sunblock and come see the Garden blooming with magnificent color.</div> <h5 class="text-center green">Photos by Heidi Simper</h5>
Java
/* * Copyright 2004-2008 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.codehaus.groovy.grails.web.json; import static org.codehaus.groovy.grails.web.json.JSONWriter.Mode.ARRAY; import static org.codehaus.groovy.grails.web.json.JSONWriter.Mode.KEY; import static org.codehaus.groovy.grails.web.json.JSONWriter.Mode.OBJECT; import java.io.IOException; import java.io.Writer; /** * A JSONWriter dedicated to create indented/pretty printed output. * * @author Siegfried Puchbauer * @since 1.1 */ public class PrettyPrintJSONWriter extends JSONWriter { public static final String DEFAULT_INDENT_STR = " "; public static final String NEWLINE; static { String nl = System.getProperty("line.separator"); NEWLINE = nl != null ? nl : "\n"; } private int indentLevel = 0; private final String indentStr; public PrettyPrintJSONWriter(Writer w) { this(w, DEFAULT_INDENT_STR); } public PrettyPrintJSONWriter(Writer w, String indentStr) { super(w); this.indentStr = indentStr; } private void newline() { try { writer.write(NEWLINE); } catch (IOException e) { throw new JSONException(e); } } private void indent() { try { for (int i = 0; i < indentLevel; i++) { writer.write(indentStr); } } catch (IOException e) { throw new JSONException(e); } } @Override protected JSONWriter append(String s) { if (s == null) { throw new JSONException("Null pointer"); } if (mode == OBJECT || mode == ARRAY) { try { if (comma && mode == ARRAY) { comma(); } if (mode == ARRAY) { newline(); indent(); } writer.write(s); } catch (IOException e) { throw new JSONException(e); } if (mode == OBJECT) { mode = KEY; } comma = true; return this; } throw new JSONException("Value out of sequence."); } @Override protected JSONWriter end(Mode m, char c) { newline(); indent(); return super.end(m, c); } @Override public JSONWriter array() { super.array(); indentLevel++; return this; } @Override public JSONWriter endArray() { indentLevel--; super.endArray(); return this; } @Override public JSONWriter object() { super.object(); indentLevel++; return this; } @Override public JSONWriter endObject() { indentLevel--; super.endObject(); return this; } @Override public JSONWriter key(String s) { if (s == null) { throw new JSONException("Null key."); } if (mode == KEY) { try { if (comma) { comma(); } newline(); indent(); writer.write(JSONObject.quote(s)); writer.write(": "); comma = false; mode = OBJECT; return this; } catch (IOException e) { throw new JSONException(e); } } throw new JSONException("Misplaced key."); } }
Java
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using Infoplus.Client; using Infoplus.Model; namespace Infoplus.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IReplenishmentApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Search replenishments by filter /// </summary> /// <remarks> /// Returns the list of replenishments that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;Replenishment&gt;</returns> List<Replenishment> GetReplenishmentByFilter (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search replenishments by filter /// </summary> /// <remarks> /// Returns the list of replenishments that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;Replenishment&gt;</returns> ApiResponse<List<Replenishment>> GetReplenishmentByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a replenishment by id /// </summary> /// <remarks> /// Returns the replenishment identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="replenishmentId">Id of the replenishment to be returned.</param> /// <returns>Replenishment</returns> Replenishment GetReplenishmentById (int? replenishmentId); /// <summary> /// Get a replenishment by id /// </summary> /// <remarks> /// Returns the replenishment identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="replenishmentId">Id of the replenishment to be returned.</param> /// <returns>ApiResponse of Replenishment</returns> ApiResponse<Replenishment> GetReplenishmentByIdWithHttpInfo (int? replenishmentId); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Search replenishments by filter /// </summary> /// <remarks> /// Returns the list of replenishments that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;Replenishment&gt;</returns> System.Threading.Tasks.Task<List<Replenishment>> GetReplenishmentByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search replenishments by filter /// </summary> /// <remarks> /// Returns the list of replenishments that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;Replenishment&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<Replenishment>>> GetReplenishmentByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a replenishment by id /// </summary> /// <remarks> /// Returns the replenishment identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="replenishmentId">Id of the replenishment to be returned.</param> /// <returns>Task of Replenishment</returns> System.Threading.Tasks.Task<Replenishment> GetReplenishmentByIdAsync (int? replenishmentId); /// <summary> /// Get a replenishment by id /// </summary> /// <remarks> /// Returns the replenishment identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="replenishmentId">Id of the replenishment to be returned.</param> /// <returns>Task of ApiResponse (Replenishment)</returns> System.Threading.Tasks.Task<ApiResponse<Replenishment>> GetReplenishmentByIdAsyncWithHttpInfo (int? replenishmentId); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class ReplenishmentApi : IReplenishmentApi { private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="ReplenishmentApi"/> class. /// </summary> /// <returns></returns> public ReplenishmentApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="ReplenishmentApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public ReplenishmentApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Infoplus.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Search replenishments by filter Returns the list of replenishments that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;Replenishment&gt;</returns> public List<Replenishment> GetReplenishmentByFilter (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<Replenishment>> localVarResponse = GetReplenishmentByFilterWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search replenishments by filter Returns the list of replenishments that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;Replenishment&gt;</returns> public ApiResponse< List<Replenishment> > GetReplenishmentByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/replenishment/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetReplenishmentByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<Replenishment>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<Replenishment>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<Replenishment>))); } /// <summary> /// Search replenishments by filter Returns the list of replenishments that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;Replenishment&gt;</returns> public async System.Threading.Tasks.Task<List<Replenishment>> GetReplenishmentByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<Replenishment>> localVarResponse = await GetReplenishmentByFilterAsyncWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search replenishments by filter Returns the list of replenishments that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;Replenishment&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<Replenishment>>> GetReplenishmentByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/replenishment/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetReplenishmentByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<Replenishment>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<Replenishment>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<Replenishment>))); } /// <summary> /// Get a replenishment by id Returns the replenishment identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="replenishmentId">Id of the replenishment to be returned.</param> /// <returns>Replenishment</returns> public Replenishment GetReplenishmentById (int? replenishmentId) { ApiResponse<Replenishment> localVarResponse = GetReplenishmentByIdWithHttpInfo(replenishmentId); return localVarResponse.Data; } /// <summary> /// Get a replenishment by id Returns the replenishment identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="replenishmentId">Id of the replenishment to be returned.</param> /// <returns>ApiResponse of Replenishment</returns> public ApiResponse< Replenishment > GetReplenishmentByIdWithHttpInfo (int? replenishmentId) { // verify the required parameter 'replenishmentId' is set if (replenishmentId == null) throw new ApiException(400, "Missing required parameter 'replenishmentId' when calling ReplenishmentApi->GetReplenishmentById"); var localVarPath = "/v1.0/replenishment/{replenishmentId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (replenishmentId != null) localVarPathParams.Add("replenishmentId", Configuration.ApiClient.ParameterToString(replenishmentId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetReplenishmentById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Replenishment>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (Replenishment) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Replenishment))); } /// <summary> /// Get a replenishment by id Returns the replenishment identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="replenishmentId">Id of the replenishment to be returned.</param> /// <returns>Task of Replenishment</returns> public async System.Threading.Tasks.Task<Replenishment> GetReplenishmentByIdAsync (int? replenishmentId) { ApiResponse<Replenishment> localVarResponse = await GetReplenishmentByIdAsyncWithHttpInfo(replenishmentId); return localVarResponse.Data; } /// <summary> /// Get a replenishment by id Returns the replenishment identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="replenishmentId">Id of the replenishment to be returned.</param> /// <returns>Task of ApiResponse (Replenishment)</returns> public async System.Threading.Tasks.Task<ApiResponse<Replenishment>> GetReplenishmentByIdAsyncWithHttpInfo (int? replenishmentId) { // verify the required parameter 'replenishmentId' is set if (replenishmentId == null) throw new ApiException(400, "Missing required parameter 'replenishmentId' when calling ReplenishmentApi->GetReplenishmentById"); var localVarPath = "/v1.0/replenishment/{replenishmentId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (replenishmentId != null) localVarPathParams.Add("replenishmentId", Configuration.ApiClient.ParameterToString(replenishmentId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetReplenishmentById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Replenishment>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (Replenishment) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Replenishment))); } } }
Java
<%# Copyright 2013-2018 the original author or authors from the JHipster project. This file is part of the JHipster project, see http://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. -%> <div> <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1 data-translate="register.title">Registration</h1> <div class="alert alert-success" ng-show="vm.success" data-translate="register.messages.success"> <strong>Registration saved!</strong> Please check your email for confirmation. </div> <div class="alert alert-danger" ng-show="vm.error" data-translate="register.messages.error.fail"> <strong>Registration failed!</strong> Please try again later. </div> <div class="alert alert-danger" ng-show="vm.errorUserExists" data-translate="register.messages.error.userexists"> <strong>Login name already registered!</strong> Please choose another one. </div> <div class="alert alert-danger" ng-show="vm.errorEmailExists" data-translate="register.messages.error.emailexists"> <strong>Email is already in use!</strong> Please choose another one. </div> <div class="alert alert-danger" ng-show="vm.doNotMatch" data-translate="global.messages.error.dontmatch"> The password and its confirmation do not match! </div> </div> <%_ if (enableSocialSignIn) { _%> <div class="col-md-4 col-md-offset-2"> <%_ } else { _%> <div class="col-md-8 col-md-offset-2"> <%_ } _%> <form ng-show="!vm.success" name="form" role="form" novalidate ng-submit="vm.register()" show-validation> <div class="form-group"> <label class="control-label" for="login" data-translate="global.form.username">Username</label> <input type="text" class="form-control" id="login" name="login" placeholder="{{'global.form.username.placeholder' | translate}}" ng-model="vm.registerAccount.login" ng-minlength=1 ng-maxlength=50 ng-pattern="/^[_'.@A-Za-z0-9-]*$/" required> <div ng-show="form.login.$dirty && form.login.$invalid"> <p class="help-block" ng-show="form.login.$error.required" data-translate="register.messages.validate.login.required"> Your username is required. </p> <p class="help-block" ng-show="form.login.$error.minlength" data-translate="register.messages.validate.login.minlength"> Your username is required to be at least 1 character. </p> <p class="help-block" ng-show="form.login.$error.maxlength" data-translate="register.messages.validate.login.maxlength"> Your username cannot be longer than 50 characters. </p> <p class="help-block" ng-show="form.login.$error.pattern" data-translate="register.messages.validate.login.pattern"> Your username can only contain letters and digits. </p> </div> </div> <div class="form-group"> <label class="control-label" for="email" data-translate="global.form.email">Email</label> <input type="email" class="form-control" id="email" name="email" placeholder="{{'global.form.email.placeholder' | translate}}" ng-model="vm.registerAccount.email" ng-minlength=5 ng-maxlength=100 required> <div ng-show="form.email.$dirty && form.email.$invalid"> <p class="help-block" ng-show="form.email.$error.required" data-translate="global.messages.validate.email.required"> Your email is required. </p> <p class="help-block" ng-show="form.email.$error.email" data-translate="global.messages.validate.email.invalid"> Your email is invalid. </p> <p class="help-block" ng-show="form.email.$error.minlength" data-translate="global.messages.validate.email.minlength"> Your email is required to be at least 5 characters. </p> <p class="help-block" ng-show="form.email.$error.maxlength" data-translate="global.messages.validate.email.maxlength"> Your email cannot be longer than 100 characters. </p> </div> </div> <div class="form-group"> <label class="control-label" for="password" data-translate="global.form.newpassword">New password</label> <input type="password" class="form-control" id="password" name="password" placeholder="{{'global.form.newpassword.placeholder' | translate}}" ng-model="vm.registerAccount.password" ng-minlength=4 ng-maxlength=50 required> <div ng-show="form.password.$dirty && form.password.$invalid"> <p class="help-block" ng-show="form.password.$error.required" data-translate="global.messages.validate.newpassword.required"> Your password is required. </p> <p class="help-block" ng-show="form.password.$error.minlength" data-translate="global.messages.validate.newpassword.minlength"> Your password is required to be at least 4 characters. </p> <p class="help-block" ng-show="form.password.$error.maxlength" data-translate="global.messages.validate.newpassword.maxlength"> Your password cannot be longer than 50 characters. </p> </div> <password-strength-bar password-to-check="vm.registerAccount.password"></password-strength-bar> </div> <div class="form-group"> <label class="control-label" for="confirmPassword" data-translate="global.form.confirmpassword">New password confirmation</label> <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" placeholder="{{'global.form.confirmpassword.placeholder' | translate}}" ng-model="vm.confirmPassword" ng-minlength=4 ng-maxlength=50 required> <div ng-show="form.confirmPassword.$dirty && form.confirmPassword.$invalid"> <p class="help-block" ng-show="form.confirmPassword.$error.required" data-translate="global.messages.validate.confirmpassword.required"> Your confirmation password is required. </p> <p class="help-block" ng-show="form.confirmPassword.$error.minlength" data-translate="global.messages.validate.confirmpassword.minlength"> Your confirmation password is required to be at least 4 characters. </p> <p class="help-block" ng-show="form.confirmPassword.$error.maxlength" data-translate="global.messages.validate.confirmpassword.maxlength"> Your confirmation password cannot be longer than 50 characters. </p> </div> </div> <button type="submit" ng-disabled="form.$invalid" class="btn btn-primary" data-translate="register.form.button">Register</button> </form> <p></p> <div class="alert alert-warning" data-translate="global.messages.info.authenticated" translate-compile> If you want to <a class="alert-link" href="" ng-click="vm.login()">sign in</a>, you can try the default accounts:<br/>- Administrator (login="admin" and password="admin") <br/>- User (login="user" and password="user"). </div> </div> <%_ if (enableSocialSignIn) { _%> <div class="col-md-4"> <br/> <jh-social ng-provider="google"></jh-social> <jh-social ng-provider="facebook"></jh-social> <jh-social ng-provider="twitter"></jh-social> <!-- jhipster-needle-add-social-button --> </div> <%_ } _%> </div> </div>
Java
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestBase; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UserDiagnosticProviderEngine { [UseExportProvider] public class DiagnosticAnalyzerDriverTests { [Fact] public async Task DiagnosticAnalyzerDriverAllInOne() { var source = TestResource.AllInOneCSharpCode; // AllInOneCSharpCode has no properties with initializers or named types with primary constructors. var symbolKindsWithNoCodeBlocks = new HashSet<SymbolKind>(); symbolKindsWithNoCodeBlocks.Add(SymbolKind.Property); symbolKindsWithNoCodeBlocks.Add(SymbolKind.NamedType); var missingSyntaxNodes = new HashSet<SyntaxKind>(); // https://github.com/dotnet/roslyn/issues/44682 - Add to all in one missingSyntaxNodes.Add(SyntaxKind.WithExpression); missingSyntaxNodes.Add(SyntaxKind.RecordDeclaration); missingSyntaxNodes.Add(SyntaxKind.FunctionPointerType); var analyzer = new CSharpTrackingDiagnosticAnalyzer(); using var workspace = TestWorkspace.CreateCSharp(source, TestOptions.Regular); var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); AccessSupportedDiagnostics(analyzer); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(document, new TextSpan(0, document.GetTextAsync().Result.Length)); analyzer.VerifyAllAnalyzerMembersWereCalled(); analyzer.VerifyAnalyzeSymbolCalledForAllSymbolKinds(); analyzer.VerifyAnalyzeNodeCalledForAllSyntaxKinds(missingSyntaxNodes); analyzer.VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(symbolKindsWithNoCodeBlocks, true); } [Fact, WorkItem(908658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908658")] public async Task DiagnosticAnalyzerDriverVsAnalyzerDriverOnCodeBlock() { var methodNames = new string[] { "Initialize", "AnalyzeCodeBlock" }; var source = @" [System.Obsolete] class C { int P { get; set; } delegate void A(); delegate string F(); } "; var ideEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var ideEngineWorkspace = TestWorkspace.CreateCSharp(source)) { var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create<DiagnosticAnalyzer>(ideEngineAnalyzer)); ideEngineWorkspace.TryApplyChanges(ideEngineWorkspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(ideEngineDocument, new TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); foreach (var method in methodNames) { Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid)); Assert.True(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property)); } } var compilerEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer(); using var compilerEngineWorkspace = TestWorkspace.CreateCSharp(source); var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetRequiredCompilationAsync(CancellationToken.None).Result; compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { compilerEngineAnalyzer }); foreach (var method in methodNames) { Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid)); Assert.True(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property)); } } [Fact] [WorkItem(759, "https://github.com/dotnet/roslyn/issues/759")] public async Task DiagnosticAnalyzerDriverIsSafeAgainstAnalyzerExceptions() { var source = TestResource.AllInOneCSharpCode; using var workspace = TestWorkspace.CreateCSharp(source, TestOptions.Regular); await ThrowingDiagnosticAnalyzer<SyntaxKind>.VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(async analyzer => { var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create(analyzer)); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); return await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(document, new TextSpan(0, document.GetTextAsync().Result.Length)); }); } [WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")] [Fact] public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_1() { var analyzer = new ThrowingDiagnosticAnalyzer<SyntaxKind>(); analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name); AccessSupportedDiagnostics(analyzer); } [WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")] [Fact] public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_2() { var analyzer = new ThrowingDoNotCatchDiagnosticAnalyzer<SyntaxKind>(); analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name); var exceptions = new List<Exception>(); try { AccessSupportedDiagnostics(analyzer); } catch (Exception e) { exceptions.Add(e); } Assert.True(exceptions.Count == 0); } [Fact] public async Task AnalyzerOptionsArePassedToAllAnalyzers() { using var workspace = TestWorkspace.CreateCSharp(TestResource.AllInOneCSharpCode, TestOptions.Regular); var additionalDocId = DocumentId.CreateNewId(workspace.CurrentSolution.Projects.Single().Id); var additionalText = new TestAdditionalText("add.config", SourceText.From("random text")); var options = new AnalyzerOptions(ImmutableArray.Create<AdditionalText>(additionalText)); var analyzer = new OptionsDiagnosticAnalyzer<SyntaxKind>(expectedOptions: options); var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); workspace.TryApplyChanges(workspace.CurrentSolution .WithAnalyzerReferences(new[] { analyzerReference }) .AddAdditionalDocument(additionalDocId, "add.config", additionalText.GetText())); var sourceDocument = workspace.CurrentSolution.Projects.Single().Documents.Single(); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(sourceDocument, new TextSpan(0, sourceDocument.GetTextAsync().Result.Length)); analyzer.VerifyAnalyzerOptions(); } private void AccessSupportedDiagnostics(DiagnosticAnalyzer analyzer) { var diagnosticService = new HostDiagnosticAnalyzers(new[] { new AnalyzerImageReference(ImmutableArray.Create(analyzer)) }); diagnosticService.GetDiagnosticDescriptorsPerReference(new DiagnosticAnalyzerInfoCache()); } private class ThrowingDoNotCatchDiagnosticAnalyzer<TLanguageKindEnum> : ThrowingDiagnosticAnalyzer<TLanguageKindEnum>, IBuiltInAnalyzer where TLanguageKindEnum : struct { public bool OpenFileOnly(OptionSet options) => false; public DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis | DiagnosticAnalyzerCategory.SemanticDocumentAnalysis | DiagnosticAnalyzerCategory.ProjectAnalysis; } [Fact] public async Task AnalyzerCreatedAtCompilationLevelNeedNotBeCompilationAnalyzer() { var source = @"x"; using var workspace = TestWorkspace.CreateCSharp(source); var analyzer = new CompilationAnalyzerWithSyntaxTreeAnalyzer(); var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var ideEngineDocument = workspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(ideEngineDocument, new TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == "SyntaxDiagnostic"); Assert.Equal(1, diagnosticsFromAnalyzer.Count()); } private class CompilationAnalyzerWithSyntaxTreeAnalyzer : DiagnosticAnalyzer { private const string ID = "SyntaxDiagnostic"; private static readonly DiagnosticDescriptor s_syntaxDiagnosticDescriptor = new DiagnosticDescriptor(ID, title: "Syntax", messageFormat: "Syntax", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(s_syntaxDiagnosticDescriptor); } } public override void Initialize(AnalysisContext context) => context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation); public void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) => context.RegisterSyntaxTreeAction(new SyntaxTreeAnalyzer().AnalyzeSyntaxTree); private class SyntaxTreeAnalyzer { public void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) => context.ReportDiagnostic(Diagnostic.Create(s_syntaxDiagnosticDescriptor, context.Tree.GetRoot().GetFirstToken().GetLocation())); } } [Fact] public async Task CodeBlockAnalyzersOnlyAnalyzeExecutableCode() { var source = @" using System; class C { void F(int x = 0) { Console.WriteLine(0); } } "; var analyzer = new CodeBlockAnalyzerFactory(); using (var ideEngineWorkspace = TestWorkspace.CreateCSharp(source)) { var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); ideEngineWorkspace.TryApplyChanges(ideEngineWorkspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(ideEngineDocument, new TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id); Assert.Equal(2, diagnosticsFromAnalyzer.Count()); } source = @" using System; class C { void F(int x = 0, int y = 1, int z = 2) { Console.WriteLine(0); } } "; using (var compilerEngineWorkspace = TestWorkspace.CreateCSharp(source)) { var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetRequiredCompilationAsync(CancellationToken.None).Result; var diagnostics = compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { analyzer }); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id); Assert.Equal(4, diagnosticsFromAnalyzer.Count()); } } private class CodeBlockAnalyzerFactory : DiagnosticAnalyzer { public static DiagnosticDescriptor Descriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor); } } public override void Initialize(AnalysisContext context) => context.RegisterCodeBlockStartAction<SyntaxKind>(CreateAnalyzerWithinCodeBlock); public void CreateAnalyzerWithinCodeBlock(CodeBlockStartAnalysisContext<SyntaxKind> context) { var blockAnalyzer = new CodeBlockAnalyzer(); context.RegisterCodeBlockEndAction(blockAnalyzer.AnalyzeCodeBlock); context.RegisterSyntaxNodeAction(blockAnalyzer.AnalyzeNode, blockAnalyzer.SyntaxKindsOfInterest.ToArray()); } private class CodeBlockAnalyzer { public ImmutableArray<SyntaxKind> SyntaxKindsOfInterest { get { return ImmutableArray.Create(SyntaxKind.MethodDeclaration, SyntaxKind.ExpressionStatement, SyntaxKind.EqualsValueClause); } } public void AnalyzeCodeBlock(CodeBlockAnalysisContext context) { } public void AnalyzeNode(SyntaxNodeAnalysisContext context) { // Ensure only executable nodes are analyzed. Assert.NotEqual(SyntaxKind.MethodDeclaration, context.Node.Kind()); context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Node.GetLocation())); } } } [Fact] public async Task TestDiagnosticSpan() { var source = @"// empty code"; var analyzer = new InvalidSpanAnalyzer(); using var compilerEngineWorkspace = TestWorkspace.CreateCSharp(source); var compilerEngineCompilation = (CSharpCompilation)(await compilerEngineWorkspace.CurrentSolution.Projects.Single().GetRequiredCompilationAsync(CancellationToken.None)); var diagnostics = compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { analyzer }); AssertEx.Any(diagnostics, d => d.Id == AnalyzerHelper.AnalyzerExceptionDiagnosticId); } private class InvalidSpanAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor Descriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) => context.RegisterSyntaxTreeAction(Analyze); private void Analyze(SyntaxTreeAnalysisContext context) => context.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.Create(context.Tree, TextSpan.FromBounds(1000, 2000)))); } [Fact, WorkItem(18818, "https://github.com/dotnet/roslyn/issues/18818")] public async Task TestNuGetAndVsixAnalyzer_ReportsSameId() { // NuGet and VSIX analyzer reporting same diagnostic IDs. var reportedDiagnosticIds = new[] { "A", "B", "C" }; var nugetAnalyzer = new NuGetAnalyzer(reportedDiagnosticIds); var vsixAnalyzer = new VsixAnalyzer(reportedDiagnosticIds); Assert.Equal(reportedDiagnosticIds, nugetAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); Assert.Equal(reportedDiagnosticIds, vsixAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); // No NuGet or VSIX analyzer - no diagnostics. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer: null, expectedNugetAnalyzerExecuted: false, vsixAnalyzer: null, expectedVsixAnalyzerExecuted: false); // Only NuGet analyzer - verify diagnostics. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer, expectedNugetAnalyzerExecuted: true, vsixAnalyzer: null, expectedVsixAnalyzerExecuted: false, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), }); // Only VSIX analyzer - verify diagnostics. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer: null, expectedNugetAnalyzerExecuted: false, vsixAnalyzer, expectedVsixAnalyzerExecuted: true, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), }); // Both NuGet and VSIX analyzer, verify the following: // 1) No duplicate diagnostics // 2) Only NuGet analyzer executes await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer, expectedNugetAnalyzerExecuted: true, vsixAnalyzer, expectedVsixAnalyzerExecuted: false, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), }); } [Fact, WorkItem(18818, "https://github.com/dotnet/roslyn/issues/18818")] public async Task TestNuGetAndVsixAnalyzer_NuGetAnalyzerReportsSubsetOfVsixAnalyzerIds() { // NuGet analyzer reports subset of diagnostic IDs reported by VSIX analyzer. var nugetAnalyzerDiagnosticIds = new[] { "B" }; var vsixAnalyzerDiagnosticIds = new[] { "A", "B", "C" }; var nugetAnalyzer = new NuGetAnalyzer(nugetAnalyzerDiagnosticIds); var vsixAnalyzer = new VsixAnalyzer(vsixAnalyzerDiagnosticIds); Assert.Equal(nugetAnalyzerDiagnosticIds, nugetAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); Assert.Equal(vsixAnalyzerDiagnosticIds, vsixAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); // Only NuGet analyzer - verify diagnostics. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer, expectedNugetAnalyzerExecuted: true, vsixAnalyzer: null, expectedVsixAnalyzerExecuted: false, new[] { (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)) }); // Only VSIX analyzer - verify diagnostics. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer: null, expectedNugetAnalyzerExecuted: false, vsixAnalyzer, expectedVsixAnalyzerExecuted: true, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), }); // Both NuGet and VSIX analyzer, verify the following: // 1) No duplicate diagnostics // 2) Both NuGet and Vsix analyzers execute // 3) Appropriate diagnostic filtering is done - NuGet analyzer reported diagnostic IDs are filtered from Vsix analyzer execution. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer, expectedNugetAnalyzerExecuted: true, vsixAnalyzer, expectedVsixAnalyzerExecuted: true, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), }); } [Fact, WorkItem(18818, "https://github.com/dotnet/roslyn/issues/18818")] public async Task TestNuGetAndVsixAnalyzer_VsixAnalyzerReportsSubsetOfNuGetAnalyzerIds() { // VSIX analyzer reports subset of diagnostic IDs reported by NuGet analyzer. var nugetAnalyzerDiagnosticIds = new[] { "A", "B", "C" }; var vsixAnalyzerDiagnosticIds = new[] { "B" }; var nugetAnalyzer = new NuGetAnalyzer(nugetAnalyzerDiagnosticIds); var vsixAnalyzer = new VsixAnalyzer(vsixAnalyzerDiagnosticIds); Assert.Equal(nugetAnalyzerDiagnosticIds, nugetAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); Assert.Equal(vsixAnalyzerDiagnosticIds, vsixAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); // Only NuGet analyzer - verify diagnostics. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer, expectedNugetAnalyzerExecuted: true, vsixAnalyzer: null, expectedVsixAnalyzerExecuted: false, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)) }); // Only VSIX analyzer - verify diagnostics. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer: null, expectedNugetAnalyzerExecuted: false, vsixAnalyzer, expectedVsixAnalyzerExecuted: true, new[] { (Diagnostic("B", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)) }); // Both NuGet and VSIX analyzer, verify the following: // 1) No duplicate diagnostics // 2) Only NuGet analyzer executes await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer, expectedNugetAnalyzerExecuted: true, vsixAnalyzer, expectedVsixAnalyzerExecuted: false, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), }); } [Fact, WorkItem(18818, "https://github.com/dotnet/roslyn/issues/18818")] public async Task TestNuGetAndVsixAnalyzer_MultipleNuGetAnalyzersCollectivelyReportSameIds() { // Multiple NuGet analyzers collectively report same diagnostic IDs reported by Vsix analyzer. var firstNugetAnalyzerDiagnosticIds = new[] { "B" }; var secondNugetAnalyzerDiagnosticIds = new[] { "A", "C" }; var vsixAnalyzerDiagnosticIds = new[] { "A", "B", "C" }; var firstNugetAnalyzer = new NuGetAnalyzer(firstNugetAnalyzerDiagnosticIds); var secondNugetAnalyzer = new NuGetAnalyzer(secondNugetAnalyzerDiagnosticIds); var vsixAnalyzer = new VsixAnalyzer(vsixAnalyzerDiagnosticIds); Assert.Equal(firstNugetAnalyzerDiagnosticIds, firstNugetAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); Assert.Equal(secondNugetAnalyzerDiagnosticIds, secondNugetAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); Assert.Equal(vsixAnalyzerDiagnosticIds, vsixAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); // All NuGet analyzers and no Vsix analyzer, verify the following: // 1) No duplicate diagnostics // 2) Only NuGet analyzers execute await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzers: ImmutableArray.Create(firstNugetAnalyzer, secondNugetAnalyzer), expectedNugetAnalyzersExecuted: true, vsixAnalyzers: ImmutableArray<VsixAnalyzer>.Empty, expectedVsixAnalyzersExecuted: false, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)) }); // All NuGet analyzers and Vsix analyzer, verify the following: // 1) No duplicate diagnostics // 2) Only NuGet analyzers execute await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzers: ImmutableArray.Create(firstNugetAnalyzer, secondNugetAnalyzer), expectedNugetAnalyzersExecuted: true, vsixAnalyzers: ImmutableArray.Create(vsixAnalyzer), expectedVsixAnalyzersExecuted: false, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)) }); // Subset of NuGet analyzers and Vsix analyzer, verify the following: // 1) No duplicate diagnostics // 2) Both NuGet and Vsix analyzers execute // 3) Appropriate diagnostic filtering is done - NuGet analyzer reported diagnostic IDs are filtered from Vsix analyzer execution. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzers: ImmutableArray.Create(firstNugetAnalyzer), expectedNugetAnalyzersExecuted: true, vsixAnalyzers: ImmutableArray.Create(vsixAnalyzer), expectedVsixAnalyzersExecuted: true, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)) }); } private static Task TestNuGetAndVsixAnalyzerCoreAsync( NuGetAnalyzer? nugetAnalyzer, bool expectedNugetAnalyzerExecuted, VsixAnalyzer? vsixAnalyzer, bool expectedVsixAnalyzerExecuted, params (DiagnosticDescription diagnostic, string message)[] expectedDiagnostics) => TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer != null ? ImmutableArray.Create(nugetAnalyzer) : ImmutableArray<NuGetAnalyzer>.Empty, expectedNugetAnalyzerExecuted, vsixAnalyzer != null ? ImmutableArray.Create(vsixAnalyzer) : ImmutableArray<VsixAnalyzer>.Empty, expectedVsixAnalyzerExecuted, expectedDiagnostics); private static async Task TestNuGetAndVsixAnalyzerCoreAsync( ImmutableArray<NuGetAnalyzer> nugetAnalyzers, bool expectedNugetAnalyzersExecuted, ImmutableArray<VsixAnalyzer> vsixAnalyzers, bool expectedVsixAnalyzersExecuted, params (DiagnosticDescription diagnostic, string message)[] expectedDiagnostics) { // First clear out the analyzer state for all analyzers. foreach (var nugetAnalyzer in nugetAnalyzers) { nugetAnalyzer.SymbolActionInvoked = false; } foreach (var vsixAnalyzer in vsixAnalyzers) { vsixAnalyzer.SymbolActionInvoked = false; } using var workspace = TestWorkspace.CreateCSharp("class Class { }", TestOptions.Regular); Assert.True(workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { new AnalyzerImageReference(vsixAnalyzers.CastArray<DiagnosticAnalyzer>()) }))); var project = workspace.CurrentSolution.Projects.Single(); if (!nugetAnalyzers.IsEmpty) { project = project.WithAnalyzerReferences(new[] { new AnalyzerImageReference(nugetAnalyzers.As<DiagnosticAnalyzer>()) }); } var document = project.Documents.Single(); var root = await document.GetRequiredSyntaxRootAsync(CancellationToken.None); var diagnostics = (await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(document, root.FullSpan)) .OrderBy(d => d.Id).ToImmutableArray(); diagnostics.Verify(expectedDiagnostics.Select(d => d.diagnostic).ToArray()); int index = 0; foreach (var (_, expectedMessage) in expectedDiagnostics) { Assert.Equal(expectedMessage, diagnostics[index].GetMessage()); index++; } foreach (var nugetAnalyzer in nugetAnalyzers) { Assert.Equal(expectedNugetAnalyzersExecuted, nugetAnalyzer.SymbolActionInvoked); } foreach (var vsixAnalyzer in vsixAnalyzers) { Assert.Equal(expectedVsixAnalyzersExecuted, vsixAnalyzer.SymbolActionInvoked); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] private sealed class NuGetAnalyzer : AbstractNuGetOrVsixAnalyzer { public NuGetAnalyzer(string[] reportedIds) : base(nameof(NuGetAnalyzer), reportedIds) { } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] private sealed class VsixAnalyzer : AbstractNuGetOrVsixAnalyzer { public VsixAnalyzer(string[] reportedIds) : base(nameof(VsixAnalyzer), reportedIds) { } } private abstract class AbstractNuGetOrVsixAnalyzer : DiagnosticAnalyzer { protected AbstractNuGetOrVsixAnalyzer(string analyzerName, params string[] reportedIds) => SupportedDiagnostics = CreateSupportedDiagnostics(analyzerName, reportedIds); private static ImmutableArray<DiagnosticDescriptor> CreateSupportedDiagnostics(string analyzerName, string[] reportedIds) { var builder = ArrayBuilder<DiagnosticDescriptor>.GetInstance(reportedIds.Length); foreach (var id in reportedIds) { var descriptor = new DiagnosticDescriptor(id, "Title", messageFormat: analyzerName, "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); builder.Add(descriptor); } return builder.ToImmutableAndFree(); } public bool SymbolActionInvoked { get; set; } public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public sealed override void Initialize(AnalysisContext context) => context.RegisterSymbolAction(OnSymbol, SymbolKind.NamedType); private void OnSymbol(SymbolAnalysisContext context) { SymbolActionInvoked = true; foreach (var descriptor in SupportedDiagnostics) { var diagnostic = Diagnostic.Create(descriptor, context.Symbol.Locations[0]); context.ReportDiagnostic(diagnostic); } } } } }
Java
// bslmf_invokeresult.06.t.cpp -*-C++-*- // ============================================================================ // INCLUDE STANDARD TEST MACHINERY FROM CASE 0 // ---------------------------------------------------------------------------- #define BSLMF_INVOKERESULT_00T_AS_INCLUDE #include <bslmf_invokeresult.00.t.cpp> //============================================================================= // TEST PLAN //----------------------------------------------------------------------------- // See the test plan in 'bslmf_invokeresult.00.t.cpp'. // // This file contains the following test: // [6] 'InvokeResultDeductionFailed' //----------------------------------------------------------------------------- // ============================================================================ // STANDARD BSL ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- // These are defined as part of the standard machinery included from file // bslmf_invokeresult.00.t.cpp // // We need to suppress the bde_verify error due to them not being in this file: // BDE_VERIFY pragma: -TP19 // ============================================================================ // STANDARD BSL TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- // These are defined as part of the standard machinery included from file // bslmf_invokeresult.00.t.cpp // // We need to suppress the bde_verify error due to them not being in this file: // BDE_VERIFY pragma: -TP19 using namespace BloombergLP; //============================================================================= // GLOBAL TYPEDEFS/CONSTANTS FOR TESTING //----------------------------------------------------------------------------- template <class TP> TP returnObj() // Return a value-initialized object of type 'TP'. { return TP(); } template <class TP> TP& returnNoCVRef() // Return a reference to a value-initialized object of type 'TP'. 'TP' is // assumed not to be cv-qualified. { static TP obj; return obj; } template <class TP> TP& returnLvalueRef() // Return an lvalue reference to a value-initialized object of type // 'TP'. 'TP' may be cv-qualified. { return returnNoCVRef<typename bsl::remove_cv<TP>::type>(); } #ifdef BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES template <class TP> TP&& returnRvalueRef() // Return an rvalue reference to a value-initialized object of type 'TP'. { return std::move(returnLvalueRef<TP>()); } #endif template <class TP> bslmf::InvokeResultDeductionFailed discardObj() // Return an 'bslmf::InvokeResultDeductionFailed' object initialized from // an rvalue of type 'TP'. { return returnObj<TP>(); } template <class TP> bslmf::InvokeResultDeductionFailed discardLvalueRef() // Return an 'bslmf::InvokeResultDeductionFailed' object initialized from // an lvalue reference of type 'TP&'. 'TP' may be cv-qualified. { return returnLvalueRef<TP>(); } #ifdef BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES template <class TP> bslmf::InvokeResultDeductionFailed discardRvalueRef() // Return an 'bslmf::InvokeResultDeductionFailed' object initialized from // an rvalue reference of type 'TP&&'. 'TP' may be cv-qualified. { return returnRvalueRef<TP>(); } #endif // ============================================================================ // MAIN PROGRAM // ---------------------------------------------------------------------------- int main(int argc, char *argv[]) { const int test = argc > 1 ? atoi(argv[1]) : 0; BSLA_MAYBE_UNUSED const bool verbose = argc > 2; BSLA_MAYBE_UNUSED const bool veryVerbose = argc > 3; BSLA_MAYBE_UNUSED const bool veryVeryVerbose = argc > 4; BSLA_MAYBE_UNUSED const bool veryVeryVeryVerbose = argc > 5; using BloombergLP::bslmf::InvokeResultDeductionFailed; printf("TEST " __FILE__ " CASE %d\n", test); // As test cases are defined elsewhere, we need to suppress bde_verify // warnings about missing test case comments/banners. // BDE_VERIFY pragma: push // BDE_VERIFY pragma: -TP05 // BDE_VERIFY pragma: -TP17 switch (test) { case 0: // Zero is always the leading case. case 8: BSLA_FALLTHROUGH; case 7: { referUserToElsewhere(test, verbose); } break; case 6: { // -------------------------------------------------------------------- // TESTING 'InvokeResultDeductionFailed' // // Concerns: //: 1 'bslmf::InvokeResultDeductionFailed' can be constructed from any //: object type. //: 2 'bslmf::InvokeResultDeductionFailed' can be constructed from any //: lvalue reference. //: 3 The previous concerns apply if the initializer is cv qualified. //: 4 In C++11 and later compilations, //: 'bslmf::InvokeResultDeductionFailed' can be constructed from any //: rvalue reference. //: 5 The above concerns apply to values that are the result of a //: function return. //: 6 The 'return' statement of a function returning a //: 'bslmf::InvokeResultDeductionFailed' can specify an lvalue or //: rvalue of any type, resulting in the value being ignored. // // Plan: //: 1 For concern 1, construct 'bslmf::InvokeResultDeductionFailed' //: objects from value-initialized objects of numeric type, //: pointer type, class type, and enumeration type. There is nothing //: to verify -- simply compiling successfully is enough. //: 2 For concern 2, create variables of the same types as in the //: previous step. Construct a 'bslmf::InvokeResultDeductionFailed' //: object from each (lvalue) variable. //: 3 For concern 3, repeat step 2, using a 'const_cast' to add cv //: qualifiers to the lvalues. //: 4 For concern 4, repeat step 2, applying 'std::move' to each //: variable used to construct an object (C++11 and later only). //: 5 For concern 5, implement a function 'returnObj<TP>' that returns //: an object of type 'TP', a function 'returnLvalueRef<TP>', that //: returns a reference of type 'TP&' and (for C++11 and later) //: 'returnRvalueRef<TP>' that returns a reference of type //: 'TP&&'. Construct a 'bslmf::InvokeResultDeductionFailed' object //: from a call to each function template instantiated with each of //: the types from step 1 and various cv-qualifier combinations. //: 6 For concern 6, implement function templates returning //: 'bslmf::InvokeResultDeductionFailed' objects 'discardObj<TP>', //: 'discardLvalueRef<TP>', and 'discardRvalueRef<TP>'. These //: functions respectively contain the statements 'return //: returnObj<TP>', 'return returnLvalueRef<TP>', and 'return //: returnRvalueRef<TP>'. Invoke each function with the same types //: as in step 5. // // Testing // 'InvokeResultDeductionFailed' // -------------------------------------------------------------------- if (verbose) printf("\nTESTING 'InvokeResultDeductionFailed'" "\n=====================================\n"); if (verbose) printf( "This test only exists in file bslm_invokeresult.%02d.t.cpp\n" "(versions in other files are no-ops)\n", test); int v1 = 0; bsl::nullptr_t v2; const char* v3 = "hello"; MyEnum v4 = MY_ENUMERATOR; MyClass v5; ASSERT(true); // Suppress "not used" warning // Step 1: Conversion from rvalue { bslmf::InvokeResultDeductionFailed x1(0); (void) x1; // Suppress "set but not used" warning bslmf::InvokeResultDeductionFailed x2 = bsl::nullptr_t(); bslmf::InvokeResultDeductionFailed x3("hello"); bslmf::InvokeResultDeductionFailed x4(MY_ENUMERATOR); // MyEnum bslmf::InvokeResultDeductionFailed x5 = MyClass(); (void) x2; // Suppress "set but not used" warning (void) x3; // Suppress "set but not used" warning (void) x4; // Suppress "set but not used" warning (void) x5; // Suppress "set but not used" warning } // Step 2: Conversion from lvalue { bslmf::InvokeResultDeductionFailed x1 = v1; (void) x1; // Suppress "set but not used" warning bslmf::InvokeResultDeductionFailed x2 = v2; bslmf::InvokeResultDeductionFailed x3 = v3; bslmf::InvokeResultDeductionFailed x4 = v4; bslmf::InvokeResultDeductionFailed x5 = v5; (void) x2; // Suppress "set but not used" warning (void) x3; // Suppress "set but not used" warning (void) x4; // Suppress "set but not used" warning (void) x5; // Suppress "set but not used" warning } // Step 3: Conversion from cv-qualified lvalue { bslmf::InvokeResultDeductionFailed x1 = const_cast<const int&>(v1); bslmf::InvokeResultDeductionFailed x3 = const_cast<const char *volatile& >(v3); bslmf::InvokeResultDeductionFailed x4 = const_cast<const volatile MyEnum&>(v4); bslmf::InvokeResultDeductionFailed x5 = const_cast<const MyClass&>(v5); (void) x1; // Suppress "set but not used" warning (void) x3; // Suppress "set but not used" warning (void) x4; // Suppress "set but not used" warning (void) x5; // Suppress "set but not used" warning } #ifdef BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES // Step 4: Conversion from rvalue reference { bslmf::InvokeResultDeductionFailed x1 = std::move(v1); bslmf::InvokeResultDeductionFailed x2 = std::move(v2); bslmf::InvokeResultDeductionFailed x3 = std::move(v3); bslmf::InvokeResultDeductionFailed x4 = std::move(v4); bslmf::InvokeResultDeductionFailed x5 = std::move(v5); (void) x1; // Suppress "set but not used" warning (void) x2; // Suppress "set but not used" warning (void) x3; // Suppress "set but not used" warning (void) x4; // Suppress "set but not used" warning (void) x5; // Suppress "set but not used" warning } #endif // Step 5: Initialization from function return { bslmf::InvokeResultDeductionFailed x1 = returnObj<int>(); (void) x1; // Suppress "set but not used" warning bslmf::InvokeResultDeductionFailed x2 = returnObj<bsl::nullptr_t>(); bslmf::InvokeResultDeductionFailed x3 = returnObj<const char *>(); bslmf::InvokeResultDeductionFailed x4 = returnObj<MyEnum>(); bslmf::InvokeResultDeductionFailed x5 = returnObj<MyClass>(); (void) x2; // Suppress "set but not used" warning (void) x3; // Suppress "set but not used" warning (void) x4; // Suppress "set but not used" warning (void) x5; // Suppress "set but not used" warning } { bslmf::InvokeResultDeductionFailed x1 = returnLvalueRef<int>(); bslmf::InvokeResultDeductionFailed x2 = returnLvalueRef<bsl::nullptr_t>(); bslmf::InvokeResultDeductionFailed x3 = returnLvalueRef<const char *const>(); bslmf::InvokeResultDeductionFailed x4 = returnLvalueRef<volatile MyEnum>(); bslmf::InvokeResultDeductionFailed x5 = returnLvalueRef<const volatile MyClass>(); (void) x1; // Suppress "set but not used" warning (void) x2; // Suppress "set but not used" warning (void) x3; // Suppress "set but not used" warning (void) x4; // Suppress "set but not used" warning (void) x5; // Suppress "set but not used" warning } #ifdef BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES { bslmf::InvokeResultDeductionFailed x1 = returnRvalueRef<int>(); bslmf::InvokeResultDeductionFailed x2 = returnRvalueRef<bsl::nullptr_t>(); bslmf::InvokeResultDeductionFailed x3 = returnRvalueRef<const char *>(); bslmf::InvokeResultDeductionFailed x4 = returnRvalueRef<MyEnum>(); bslmf::InvokeResultDeductionFailed x5 = returnRvalueRef<MyClass>(); (void) x1; // Suppress "set but not used" warning (void) x2; // Suppress "set but not used" warning (void) x3; // Suppress "set but not used" warning (void) x4; // Suppress "set but not used" warning (void) x5; // Suppress "set but not used" warning } #endif // Step 6: Return 'bslmf::InvokeResultDeductionFailed' { discardObj<int>(); discardObj<bsl::nullptr_t>(); discardObj<const char *>(); discardObj<MyEnum>(); discardObj<MyClass>(); discardLvalueRef<int>(); discardLvalueRef<bsl::nullptr_t>(); discardLvalueRef<const char *const>(); discardLvalueRef<volatile MyEnum>(); discardLvalueRef<const volatile MyClass>(); #ifdef BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES discardRvalueRef<int>(); discardRvalueRef<bsl::nullptr_t>(); discardRvalueRef<const char *>(); discardRvalueRef<MyEnum>(); discardRvalueRef<MyClass>(); #endif } } break; case 5: BSLA_FALLTHROUGH; case 4: BSLA_FALLTHROUGH; case 3: BSLA_FALLTHROUGH; case 2: BSLA_FALLTHROUGH; case 1: { referUserToElsewhere(test, verbose); } break; default: { fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test); testStatus = -1; } } // BDE_VERIFY pragma: pop if (testStatus > 0) { fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus); } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2018 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
Java
/** * Test for LOOMIA TILE Token * * @author Pactum IO <dev@pactum.io> */ import {getEvents, BigNumber} from './helpers/tools'; import expectThrow from './helpers/expectThrow'; const loomiaToken = artifacts.require('./TileToken'); const should = require('chai') // eslint-disable-line .use(require('chai-as-promised')) .use(require('chai-bignumber')(BigNumber)) .should(); /** * Tile Token Contract */ contract('TileToken', (accounts) => { const owner = accounts[0]; const tokenHolder1 = accounts[1]; const spendingAddress = accounts[2]; const recipient = accounts[3]; const anotherAccount = accounts[4]; const tokenHolder5 = accounts[5]; const zeroTokenHolder = accounts[6]; const zeroAddress = '0x0000000000000000000000000000000000000000'; const zero = new BigNumber(0); const tokenSupply = new BigNumber(1046000000000000000000000000); // Provide Tile Token instance for every test case let tileTokenInstance; beforeEach(async () => { tileTokenInstance = await loomiaToken.deployed(); }); it('should instantiate the token correctly', async () => { const name = await tileTokenInstance.NAME(); const symbol = await tileTokenInstance.SYMBOL(); const decimals = await tileTokenInstance.DECIMALS(); const totalSupply = await tileTokenInstance.totalSupply(); assert.equal(name, 'LOOMIA TILE', 'Name does not match'); assert.equal(symbol, 'TILE', 'Symbol does not match'); assert.equal(decimals, 18, 'Decimals does not match'); totalSupply.should.be.bignumber.equal(tokenSupply); }); describe('balanceOf', function () { describe('when the requested account has no tokens', function () { it('returns zero', async function () { const balance = await tileTokenInstance.balanceOf(zeroTokenHolder); balance.should.be.bignumber.equal(zero); }); }); describe('when the requested account has some tokens', function () { it('returns the total amount of tokens', async function () { const balance = await tileTokenInstance.balanceOf(owner); balance.should.be.bignumber.equal(tokenSupply); }); }); }); describe('transfer', function () { describe('when the recipient is not the zero address', function () { const to = tokenHolder1; describe('when the sender does not have enough balance', function () { const transferAmount = tokenSupply.add(1); it('reverts', async function () { await expectThrow(tileTokenInstance.transfer(to, transferAmount, { from: owner })); }); }); describe('when the sender has enough balance', function () { const transferAmount = new BigNumber(500 * 1e18); it('transfers the requested amount', async function () { await tileTokenInstance.transfer(to, transferAmount, { from: owner }); const senderBalance = await tileTokenInstance.balanceOf(owner); senderBalance.should.be.bignumber.equal(tokenSupply.sub(transferAmount)); const recipientBalance = await tileTokenInstance.balanceOf(to); recipientBalance.should.be.bignumber.equal(transferAmount); }); it('emits a transfer event', async function () { const tx = await tileTokenInstance.transfer(to, transferAmount, { from: owner }); // Test the event const events = getEvents(tx, 'Transfer'); assert.equal(events[0].from, owner, 'From address does not match'); assert.equal(events[0].to, to, 'To address does not match'); (events[0].value).should.be.bignumber.equal(transferAmount); }); }); }); describe('when the recipient is the zero address', function () { const to = zeroAddress; it('reverts', async function () { await expectThrow(tileTokenInstance.transfer(to, 100, { from: owner })); }); }); }); describe('approve', function () { describe('when the spender is not the zero address', function () { const spender = spendingAddress; describe('when the sender has enough balance', function () { const amount = new BigNumber(100 * 1e18); it('emits an approval event', async function () { const tx = await tileTokenInstance.approve(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(amount); }); describe('when there was no approved amount before', function () { it('approves the requested amount', async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { await tileTokenInstance.approve(spender, 1, { from: owner }); }); it('approves the requested amount and replaces the previous one', async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); }); }); describe('when the sender does not have enough balance', function () { const amount = new BigNumber(101 * 1e18); it('emits an approval event', async function () { const tx = await tileTokenInstance.approve(spender, amount, { from: owner }); const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(amount); }); describe('when there was no approved amount before', function () { it('approves the requested amount', async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { await tileTokenInstance.approve(spender, 1, { from: owner }); }); it('approves the requested amount and replaces the previous one', async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); }); }); }); describe('when the spender is the zero address', function () { const amount = new BigNumber(100 * 1e18); const spender = zeroAddress; it('approves the requested amount', async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); it('emits an approval event', async function () { const tx = await tileTokenInstance.approve(spender, amount, { from: owner }); const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(amount); }); }); }); describe('transfer from', function () { const spender = recipient; describe('when the recipient is not the zero address', function () { const to = anotherAccount; describe('when the spender has enough approved balance', function () { beforeEach(async function () { const approvalAmount = new BigNumber(30000 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: owner }); await tileTokenInstance.approve(spender, approvalAmount, { from: zeroTokenHolder }); }); describe('when the owner has enough balance', function () { const amount = new BigNumber(30000 * 1e18); it('transfers the requested amount', async function () { const balanceBefore = await tileTokenInstance.balanceOf(owner); await tileTokenInstance.transferFrom(owner, to, amount, { from: spender }); const senderBalance = await tileTokenInstance.balanceOf(owner); senderBalance.should.be.bignumber.equal(balanceBefore.sub(amount)); const recipientBalance = await tileTokenInstance.balanceOf(to); recipientBalance.should.be.bignumber.equal(amount); }); it('decreases the spender allowance', async function () { await tileTokenInstance.transferFrom(owner, to, amount, { from: spender }); const allowance = await tileTokenInstance.allowance(owner, spender); assert(allowance.eq(0)); }); it('emits a transfer event', async function () { const tx = await tileTokenInstance.transferFrom(owner, to, amount, { from: spender }); // Test the event const events = getEvents(tx, 'Transfer'); assert.equal(events[0].from, owner, 'address does not match'); assert.equal(events[0].to, to, 'To address does not match'); (events[0].value).should.be.bignumber.equal(amount); }); }); describe('when the owner does not have enough balance', function () { const amount = new BigNumber(1 * 1e18); it('reverts', async function () { await expectThrow(tileTokenInstance.transferFrom(zeroTokenHolder, to, amount, { from: spender })); }); }); }); describe('when the spender does not have enough approved balance', function () { beforeEach(async function () { const approvalAmount = new BigNumber(99 * 1e18); const bigApprovalAmount = new BigNumber(999 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: owner }); await tileTokenInstance.approve(spender, bigApprovalAmount, { from: tokenHolder1 }); }); describe('when the owner has enough balance', function () { const amount = new BigNumber(100 * 1e18); it('reverts', async function () { await expectThrow(tileTokenInstance.transferFrom(owner, to, amount, { from: spender })); }); }); describe('when the owner does not have enough balance', function () { const amount = new BigNumber(1001 * 1e18); it('reverts', async function () { await expectThrow(tileTokenInstance.transferFrom(tokenHolder1, to, amount, { from: spender })); }); }); }); }); describe('when the recipient is the zero address', function () { const amount = new BigNumber(100 * 1e18); const to = zeroAddress; beforeEach(async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); }); it('reverts', async function () { await expectThrow(tileTokenInstance.transferFrom(owner, to, amount, { from: spender })); }); }); }); describe('decrease approval', function () { describe('when the spender is not the zero address', function () { const spender = recipient; describe('when the sender has enough balance', function () { const amount = new BigNumber(100 * 1e18); it('emits an approval event', async function () { const tx = await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(0); }); describe('when there was no approved amount before', function () { it('keeps the allowance to zero', async function () { await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(0); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { const approvalAmount = new BigNumber(1000 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: owner }); }); it('decreases the spender allowance subtracting the requested amount', async function () { await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); const approvalAmount = new BigNumber(1000 * 1e18); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(approvalAmount.sub(amount)); }); }); }); describe('when the sender does not have enough balance', function () { const amount = new BigNumber(1000 * 1e18); it('emits an approval event', async function () { const tx = await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(0); }); describe('when there was no approved amount before', function () { it('keeps the allowance to zero', async function () { await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(0); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { const approvalAmount = new BigNumber(1001 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: owner }); }); it('decreases the spender allowance subtracting the requested amount', async function () { await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(1 * 1e18); }); }); }); }); describe('when the spender is the zero address', function () { const amount = new BigNumber(100 * 1e18); const spender = zeroAddress; it('decreases the requested amount', async function () { await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(0); }); it('emits an approval event', async function () { const tx = await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(0); }); }); }); describe('increase approval', function () { const amount = new BigNumber(100 * 1e18); describe('when the spender is not the zero address', function () { const spender = recipient; describe('when the sender has enough balance', function () { it('emits an approval event', async function () { const oldAllowance = await tileTokenInstance.allowance(owner, spender); const tx = await tileTokenInstance.increaseApproval(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(amount.add(oldAllowance)); }); describe('when there was no approved amount before', function () { it('approves the requested amount', async function () { const oldAllowance = await tileTokenInstance.allowance(owner, spender); await tileTokenInstance.increaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount.add(oldAllowance)); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { const approvalAmount = new BigNumber(1 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: owner }); }); it('increases the spender allowance adding the requested amount', async function () { const oldAllowance = await tileTokenInstance.allowance(owner, spender); await tileTokenInstance.increaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(oldAllowance.add(amount)); }); }); }); describe('when the sender does not have enough balance', function () { const amount = new BigNumber(2 * 1e18); it('emits an approval event', async function () { const oldAllowance = await tileTokenInstance.allowance(tokenHolder1, spender); const tx = await tileTokenInstance.increaseApproval(spender, amount, { from: tokenHolder1 }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, tokenHolder1, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(oldAllowance.add(amount)); }); describe('when there was no approved amount before', function () { it('approves the requested amount', async function () { await tileTokenInstance.increaseApproval(spender, amount, { from: tokenHolder5 }); const allowance = await tileTokenInstance.allowance(tokenHolder5, spender); allowance.should.be.bignumber.equal(amount); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { const approvalAmount = new BigNumber(1 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: tokenHolder5 }); }); it('increases the spender allowance adding the requested amount', async function () { const oldAllowance = await tileTokenInstance.allowance(tokenHolder5, spender); await tileTokenInstance.increaseApproval(spender, amount, { from: tokenHolder5 }); const allowance = await tileTokenInstance.allowance(tokenHolder5, spender); allowance.should.be.bignumber.equal(oldAllowance.add(amount)); }); }); }); }); describe('when the spender is the zero address', function () { const spender = zeroAddress; it('approves the requested amount', async function () { await tileTokenInstance.increaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); it('emits an approval event', async function () { const oldAllowance = await tileTokenInstance.allowance(owner, spender); const tx = await tileTokenInstance.increaseApproval(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(oldAllowance.add(amount)); }); }); }); });
Java
/** */ package org.tud.inf.st.mbt.ocm.impl; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; import org.tud.inf.st.mbt.ocm.*; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class OcmFactoryImpl extends EFactoryImpl implements OcmFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static OcmFactory init() { try { OcmFactory theOcmFactory = (OcmFactory)EPackage.Registry.INSTANCE.getEFactory(OcmPackage.eNS_URI); if (theOcmFactory != null) { return theOcmFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new OcmFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OcmFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case OcmPackage.OPERATIONAL_CONFIGURATION_MODEL: return createOperationalConfigurationModel(); case OcmPackage.STANDARD_CONFIGURATION_NODE: return createStandardConfigurationNode(); case OcmPackage.RECONFIGURATION_ACTION_NODE: return createReconfigurationActionNode(); case OcmPackage.TIMED_EDGE: return createTimedEdge(); case OcmPackage.EVENT_GUARDED_EDGE: return createEventGuardedEdge(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OperationalConfigurationModel createOperationalConfigurationModel() { OperationalConfigurationModelImpl operationalConfigurationModel = new OperationalConfigurationModelImpl(); return operationalConfigurationModel; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public StandardConfigurationNode createStandardConfigurationNode() { StandardConfigurationNodeImpl standardConfigurationNode = new StandardConfigurationNodeImpl(); return standardConfigurationNode; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ReconfigurationActionNode createReconfigurationActionNode() { ReconfigurationActionNodeImpl reconfigurationActionNode = new ReconfigurationActionNodeImpl(); return reconfigurationActionNode; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TimedEdge createTimedEdge() { TimedEdgeImpl timedEdge = new TimedEdgeImpl(); return timedEdge; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EventGuardedEdge createEventGuardedEdge() { EventGuardedEdgeImpl eventGuardedEdge = new EventGuardedEdgeImpl(); return eventGuardedEdge; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OcmPackage getOcmPackage() { return (OcmPackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static OcmPackage getPackage() { return OcmPackage.eINSTANCE; } } //OcmFactoryImpl
Java
/** * Copyright (c) 2013-2019 Contributors to the Eclipse Foundation * * <p> See the NOTICE file distributed with this work for additional information regarding copyright * ownership. All rights reserved. This program and the accompanying materials are made available * under the terms of the Apache License, Version 2.0 which accompanies this distribution and is * available at http://www.apache.org/licenses/LICENSE-2.0.txt */ package org.locationtech.geowave.core.store.util; import java.util.Iterator; import java.util.Map; import org.locationtech.geowave.core.store.adapter.PersistentAdapterStore; import org.locationtech.geowave.core.store.adapter.RowMergingDataAdapter; import org.locationtech.geowave.core.store.adapter.RowMergingDataAdapter.RowTransform; import org.locationtech.geowave.core.store.api.Index; import org.locationtech.geowave.core.store.entities.GeoWaveRow; import org.locationtech.geowave.core.store.operations.RowDeleter; import org.locationtech.geowave.core.store.operations.RowWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RewritingMergingEntryIterator<T> extends MergingEntryIterator<T> { private static final Logger LOGGER = LoggerFactory.getLogger(RewritingMergingEntryIterator.class); private final RowWriter writer; private final RowDeleter deleter; public RewritingMergingEntryIterator( final PersistentAdapterStore adapterStore, final Index index, final Iterator<GeoWaveRow> scannerIt, final Map<Short, RowMergingDataAdapter> mergingAdapters, final RowWriter writer, final RowDeleter deleter) { super(adapterStore, index, scannerIt, null, null, mergingAdapters, null, null); this.writer = writer; this.deleter = deleter; } @Override protected GeoWaveRow mergeSingleRowValues( final GeoWaveRow singleRow, final RowTransform rowTransform) { if (singleRow.getFieldValues().length < 2) { return singleRow; } deleter.delete(singleRow); deleter.flush(); final GeoWaveRow merged = super.mergeSingleRowValues(singleRow, rowTransform); writer.write(merged); return merged; } }
Java
package plugin /* usage: !day */ import ( "strings" "time" "github.com/microamp/gerri/cmd" "github.com/microamp/gerri/data" ) func ReplyDay(pm data.Privmsg, config *data.Config) (string, error) { return cmd.Privmsg(pm.Target, strings.ToLower(time.Now().Weekday().String())), nil }
Java
/* * Copyright (C) 2019 Contentful GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.contentful.java.cma; import com.contentful.java.cma.model.CMAArray; import com.contentful.java.cma.model.CMATag; import io.reactivex.Flowable; import retrofit2.Response; import retrofit2.http.GET; import retrofit2.http.PUT; import retrofit2.http.Path; import retrofit2.http.QueryMap; import retrofit2.http.Body; import retrofit2.http.DELETE; import java.util.Map; /** * Spaces Service. */ interface ServiceContentTags { @GET("/spaces/{space_id}/environments/{environment_id}/tags") Flowable<CMAArray<CMATag>> fetchAll( @Path("space_id") String spaceId, @Path("environment_id") String environmentID, @QueryMap Map<String, String> query ); @PUT("/spaces/{space_id}/environments/{environment_id}/tags/{tag_id}") Flowable<CMATag> create( @Path("space_id") String spaceId, @Path("environment_id") String environmentID, @Path("tag_id") String tagId, @Body CMATag tag); @GET("/spaces/{space_id}/environments/{environment_id}/tags/{tag_id}") Flowable<CMATag> fetchOne( @Path("space_id") String spaceId, @Path("environment_id") String environmentID, @Path("tag_id") String tagId ); @PUT("/spaces/{space_id}/environments/{environment_id}/tags/{tag_id}") Flowable<CMATag> update( @Path("space_id") String spaceId, @Path("environment_id") String environmentID, @Path("tag_id") String tagId, @Body CMATag tag); @DELETE("/spaces/{space_id}/environments/{environment_id}/tags/{tag_id}") Flowable<Response<Void>> delete( @Path("space_id") String spaceId, @Path("environment_id") String environmentID, @Path("tag_id") String tagId); }
Java
package main import ( "net/url" "time" "github.com/codegangsta/cli" "github.com/michaeltrobinson/cadvisor-integration/scraper" "github.com/signalfx/metricproxy/protocol/signalfx" log "github.com/Sirupsen/logrus" ) var ( sfxAPIToken string sfxIngestURL string clusterName string sendInterval time.Duration cadvisorPort int discoveryInterval time.Duration maxDatapoints int kubeUser string kubePass string ) func init() { app.Commands = append(app.Commands, cli.Command{ Name: "run", Usage: "start the service (the default)", Action: run, Before: setupRun, Flags: []cli.Flag{ cli.StringFlag{ Name: "sfx-ingest-url", EnvVar: "SFX_ENDPOINT", Value: "https://ingest.signalfx.com", Usage: "SignalFx ingest URL", }, cli.StringFlag{ Name: "sfx-api-token", EnvVar: "SFX_API_TOKEN", Usage: "SignalFx API token", }, cli.StringFlag{ Name: "cluster-name", EnvVar: "CLUSTER_NAME", Usage: "Cluster name will appear as dimension", }, cli.DurationFlag{ Name: "send-interval", EnvVar: "SEND_INTERVAL", Value: time.Second * 30, Usage: "Rate at which data is queried from cAdvisor and send to SignalFx", }, cli.IntFlag{ Name: "cadvisor-port", EnvVar: "CADVISOR_PORT", Value: 4194, Usage: "Port on which cAdvisor listens", }, cli.DurationFlag{ Name: "discovery-interval", EnvVar: "NODE_SERVICE_DISCOVERY_INTERVAL", Value: time.Minute * 5, Usage: "Rate at which nodes and services will be rediscovered", }, cli.StringFlag{ Name: "kube-user", EnvVar: "KUBE_USER", Usage: "Username to authenticate to kubernetes api", }, cli.StringFlag{ Name: "kube-pass", EnvVar: "KUBE_PASS", Usage: "Password to authenticate to kubernetes api", }, cli.IntFlag{ Name: "max-datapoints", EnvVar: "MAX_DATAPOINTS", Value: 50, Usage: "How many datapoints to batch before forwarding to SignalFX", }, }, }) } func setupRun(c *cli.Context) error { sfxAPIToken = c.String("sfx-api-token") if sfxAPIToken == "" { cli.ShowAppHelp(c) log.Fatal("API token is required") } clusterName = c.String("cluster-name") if clusterName == "" { cli.ShowAppHelp(c) log.Fatal("cluster name is required") } sfxIngestURL = c.String("sfx-ingest-url") sendInterval = c.Duration("send-interval") cadvisorPort = c.Int("cadvisor-port") discoveryInterval = c.Duration("discovery-interval") kubeUser = c.String("kube-user") kubePass = c.String("kube-pass") if kubeUser == "" || kubePass == "" { cli.ShowAppHelp(c) log.Fatal("kubernetes credentials are required") } maxDatapoints = c.Int("max-datapoints") return nil } func run(c *cli.Context) { s := scraper.New( newSfxClient(sfxIngestURL, sfxAPIToken), scraper.Config{ ClusterName: clusterName, CadvisorPort: cadvisorPort, KubeUser: kubeUser, KubePass: kubePass, MaxDatapoints: maxDatapoints, }) if err := s.Run(sendInterval, discoveryInterval); err != nil { log.WithError(err).Fatal("failure") } } func newSfxClient(ingestURL, authToken string) *signalfx.Forwarder { sfxEndpoint, err := url.Parse(ingestURL) if err != nil { panic("failed to parse SFX ingest URL") } return signalfx.NewSignalfxJSONForwarder(sfxEndpoint.String(), time.Second*10, authToken, 10, "", "", "") }
Java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/mwaa/MWAA_EXPORTS.h> #include <aws/mwaa/MWAARequest.h> #include <aws/core/utils/memory/stl/AWSMap.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/mwaa/model/LoggingConfigurationInput.h> #include <aws/mwaa/model/NetworkConfiguration.h> #include <aws/mwaa/model/WebserverAccessMode.h> #include <utility> namespace Aws { namespace MWAA { namespace Model { /** * <p>This section contains the Amazon Managed Workflows for Apache Airflow (MWAA) * API reference documentation to create an environment. For more information, see * <a href="https://docs.aws.amazon.com/mwaa/latest/userguide/get-started.html">Get * started with Amazon Managed Workflows for Apache Airflow</a>.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/mwaa-2020-07-01/CreateEnvironmentInput">AWS * API Reference</a></p> */ class AWS_MWAA_API CreateEnvironmentRequest : public MWAARequest { public: CreateEnvironmentRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "CreateEnvironment"; } Aws::String SerializePayload() const override; /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline const Aws::Map<Aws::String, Aws::String>& GetAirflowConfigurationOptions() const{ return m_airflowConfigurationOptions; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline bool AirflowConfigurationOptionsHasBeenSet() const { return m_airflowConfigurationOptionsHasBeenSet; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline void SetAirflowConfigurationOptions(const Aws::Map<Aws::String, Aws::String>& value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions = value; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline void SetAirflowConfigurationOptions(Aws::Map<Aws::String, Aws::String>&& value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions = std::move(value); } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& WithAirflowConfigurationOptions(const Aws::Map<Aws::String, Aws::String>& value) { SetAirflowConfigurationOptions(value); return *this;} /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& WithAirflowConfigurationOptions(Aws::Map<Aws::String, Aws::String>&& value) { SetAirflowConfigurationOptions(std::move(value)); return *this;} /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& AddAirflowConfigurationOptions(const Aws::String& key, const Aws::String& value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions.emplace(key, value); return *this; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& AddAirflowConfigurationOptions(Aws::String&& key, const Aws::String& value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions.emplace(std::move(key), value); return *this; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& AddAirflowConfigurationOptions(const Aws::String& key, Aws::String&& value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions.emplace(key, std::move(value)); return *this; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& AddAirflowConfigurationOptions(Aws::String&& key, Aws::String&& value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions.emplace(std::move(key), std::move(value)); return *this; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& AddAirflowConfigurationOptions(const char* key, Aws::String&& value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions.emplace(key, std::move(value)); return *this; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& AddAirflowConfigurationOptions(Aws::String&& key, const char* value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions.emplace(std::move(key), value); return *this; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& AddAirflowConfigurationOptions(const char* key, const char* value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions.emplace(key, value); return *this; } /** * <p>The Apache Airflow version you want to use for your environment.</p> */ inline const Aws::String& GetAirflowVersion() const{ return m_airflowVersion; } /** * <p>The Apache Airflow version you want to use for your environment.</p> */ inline bool AirflowVersionHasBeenSet() const { return m_airflowVersionHasBeenSet; } /** * <p>The Apache Airflow version you want to use for your environment.</p> */ inline void SetAirflowVersion(const Aws::String& value) { m_airflowVersionHasBeenSet = true; m_airflowVersion = value; } /** * <p>The Apache Airflow version you want to use for your environment.</p> */ inline void SetAirflowVersion(Aws::String&& value) { m_airflowVersionHasBeenSet = true; m_airflowVersion = std::move(value); } /** * <p>The Apache Airflow version you want to use for your environment.</p> */ inline void SetAirflowVersion(const char* value) { m_airflowVersionHasBeenSet = true; m_airflowVersion.assign(value); } /** * <p>The Apache Airflow version you want to use for your environment.</p> */ inline CreateEnvironmentRequest& WithAirflowVersion(const Aws::String& value) { SetAirflowVersion(value); return *this;} /** * <p>The Apache Airflow version you want to use for your environment.</p> */ inline CreateEnvironmentRequest& WithAirflowVersion(Aws::String&& value) { SetAirflowVersion(std::move(value)); return *this;} /** * <p>The Apache Airflow version you want to use for your environment.</p> */ inline CreateEnvironmentRequest& WithAirflowVersion(const char* value) { SetAirflowVersion(value); return *this;} /** * <p>The relative path to the DAG folder on your Amazon S3 storage bucket. For * example, <code>dags</code>. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline const Aws::String& GetDagS3Path() const{ return m_dagS3Path; } /** * <p>The relative path to the DAG folder on your Amazon S3 storage bucket. For * example, <code>dags</code>. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline bool DagS3PathHasBeenSet() const { return m_dagS3PathHasBeenSet; } /** * <p>The relative path to the DAG folder on your Amazon S3 storage bucket. For * example, <code>dags</code>. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetDagS3Path(const Aws::String& value) { m_dagS3PathHasBeenSet = true; m_dagS3Path = value; } /** * <p>The relative path to the DAG folder on your Amazon S3 storage bucket. For * example, <code>dags</code>. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetDagS3Path(Aws::String&& value) { m_dagS3PathHasBeenSet = true; m_dagS3Path = std::move(value); } /** * <p>The relative path to the DAG folder on your Amazon S3 storage bucket. For * example, <code>dags</code>. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetDagS3Path(const char* value) { m_dagS3PathHasBeenSet = true; m_dagS3Path.assign(value); } /** * <p>The relative path to the DAG folder on your Amazon S3 storage bucket. For * example, <code>dags</code>. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithDagS3Path(const Aws::String& value) { SetDagS3Path(value); return *this;} /** * <p>The relative path to the DAG folder on your Amazon S3 storage bucket. For * example, <code>dags</code>. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithDagS3Path(Aws::String&& value) { SetDagS3Path(std::move(value)); return *this;} /** * <p>The relative path to the DAG folder on your Amazon S3 storage bucket. For * example, <code>dags</code>. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithDagS3Path(const char* value) { SetDagS3Path(value); return *this;} /** * <p>The environment class you want to use for your environment. The environment * class determines the size of the containers and database used for your Apache * Airflow services.</p> */ inline const Aws::String& GetEnvironmentClass() const{ return m_environmentClass; } /** * <p>The environment class you want to use for your environment. The environment * class determines the size of the containers and database used for your Apache * Airflow services.</p> */ inline bool EnvironmentClassHasBeenSet() const { return m_environmentClassHasBeenSet; } /** * <p>The environment class you want to use for your environment. The environment * class determines the size of the containers and database used for your Apache * Airflow services.</p> */ inline void SetEnvironmentClass(const Aws::String& value) { m_environmentClassHasBeenSet = true; m_environmentClass = value; } /** * <p>The environment class you want to use for your environment. The environment * class determines the size of the containers and database used for your Apache * Airflow services.</p> */ inline void SetEnvironmentClass(Aws::String&& value) { m_environmentClassHasBeenSet = true; m_environmentClass = std::move(value); } /** * <p>The environment class you want to use for your environment. The environment * class determines the size of the containers and database used for your Apache * Airflow services.</p> */ inline void SetEnvironmentClass(const char* value) { m_environmentClassHasBeenSet = true; m_environmentClass.assign(value); } /** * <p>The environment class you want to use for your environment. The environment * class determines the size of the containers and database used for your Apache * Airflow services.</p> */ inline CreateEnvironmentRequest& WithEnvironmentClass(const Aws::String& value) { SetEnvironmentClass(value); return *this;} /** * <p>The environment class you want to use for your environment. The environment * class determines the size of the containers and database used for your Apache * Airflow services.</p> */ inline CreateEnvironmentRequest& WithEnvironmentClass(Aws::String&& value) { SetEnvironmentClass(std::move(value)); return *this;} /** * <p>The environment class you want to use for your environment. The environment * class determines the size of the containers and database used for your Apache * Airflow services.</p> */ inline CreateEnvironmentRequest& WithEnvironmentClass(const char* value) { SetEnvironmentClass(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the execution role for your environment. An * execution role is an AWS Identity and Access Management (IAM) role that grants * MWAA permission to access AWS services and resources used by your environment. * For example, <code>arn:aws:iam::123456789:role/my-execution-role</code>. For * more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/manage-access.html">Managing * access to Amazon Managed Workflows for Apache Airflow</a>.</p> */ inline const Aws::String& GetExecutionRoleArn() const{ return m_executionRoleArn; } /** * <p>The Amazon Resource Name (ARN) of the execution role for your environment. An * execution role is an AWS Identity and Access Management (IAM) role that grants * MWAA permission to access AWS services and resources used by your environment. * For example, <code>arn:aws:iam::123456789:role/my-execution-role</code>. For * more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/manage-access.html">Managing * access to Amazon Managed Workflows for Apache Airflow</a>.</p> */ inline bool ExecutionRoleArnHasBeenSet() const { return m_executionRoleArnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the execution role for your environment. An * execution role is an AWS Identity and Access Management (IAM) role that grants * MWAA permission to access AWS services and resources used by your environment. * For example, <code>arn:aws:iam::123456789:role/my-execution-role</code>. For * more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/manage-access.html">Managing * access to Amazon Managed Workflows for Apache Airflow</a>.</p> */ inline void SetExecutionRoleArn(const Aws::String& value) { m_executionRoleArnHasBeenSet = true; m_executionRoleArn = value; } /** * <p>The Amazon Resource Name (ARN) of the execution role for your environment. An * execution role is an AWS Identity and Access Management (IAM) role that grants * MWAA permission to access AWS services and resources used by your environment. * For example, <code>arn:aws:iam::123456789:role/my-execution-role</code>. For * more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/manage-access.html">Managing * access to Amazon Managed Workflows for Apache Airflow</a>.</p> */ inline void SetExecutionRoleArn(Aws::String&& value) { m_executionRoleArnHasBeenSet = true; m_executionRoleArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the execution role for your environment. An * execution role is an AWS Identity and Access Management (IAM) role that grants * MWAA permission to access AWS services and resources used by your environment. * For example, <code>arn:aws:iam::123456789:role/my-execution-role</code>. For * more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/manage-access.html">Managing * access to Amazon Managed Workflows for Apache Airflow</a>.</p> */ inline void SetExecutionRoleArn(const char* value) { m_executionRoleArnHasBeenSet = true; m_executionRoleArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the execution role for your environment. An * execution role is an AWS Identity and Access Management (IAM) role that grants * MWAA permission to access AWS services and resources used by your environment. * For example, <code>arn:aws:iam::123456789:role/my-execution-role</code>. For * more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/manage-access.html">Managing * access to Amazon Managed Workflows for Apache Airflow</a>.</p> */ inline CreateEnvironmentRequest& WithExecutionRoleArn(const Aws::String& value) { SetExecutionRoleArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the execution role for your environment. An * execution role is an AWS Identity and Access Management (IAM) role that grants * MWAA permission to access AWS services and resources used by your environment. * For example, <code>arn:aws:iam::123456789:role/my-execution-role</code>. For * more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/manage-access.html">Managing * access to Amazon Managed Workflows for Apache Airflow</a>.</p> */ inline CreateEnvironmentRequest& WithExecutionRoleArn(Aws::String&& value) { SetExecutionRoleArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the execution role for your environment. An * execution role is an AWS Identity and Access Management (IAM) role that grants * MWAA permission to access AWS services and resources used by your environment. * For example, <code>arn:aws:iam::123456789:role/my-execution-role</code>. For * more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/manage-access.html">Managing * access to Amazon Managed Workflows for Apache Airflow</a>.</p> */ inline CreateEnvironmentRequest& WithExecutionRoleArn(const char* value) { SetExecutionRoleArn(value); return *this;} /** * <p>The AWS Key Management Service (KMS) key to encrypt and decrypt the data in * your environment. You can use an AWS KMS key managed by MWAA, or a custom KMS * key (advanced). For more information, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html?icmpid=docs_console_unmapped#master_keys">Customer * master keys (CMKs)</a> in the AWS KMS developer guide.</p> */ inline const Aws::String& GetKmsKey() const{ return m_kmsKey; } /** * <p>The AWS Key Management Service (KMS) key to encrypt and decrypt the data in * your environment. You can use an AWS KMS key managed by MWAA, or a custom KMS * key (advanced). For more information, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html?icmpid=docs_console_unmapped#master_keys">Customer * master keys (CMKs)</a> in the AWS KMS developer guide.</p> */ inline bool KmsKeyHasBeenSet() const { return m_kmsKeyHasBeenSet; } /** * <p>The AWS Key Management Service (KMS) key to encrypt and decrypt the data in * your environment. You can use an AWS KMS key managed by MWAA, or a custom KMS * key (advanced). For more information, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html?icmpid=docs_console_unmapped#master_keys">Customer * master keys (CMKs)</a> in the AWS KMS developer guide.</p> */ inline void SetKmsKey(const Aws::String& value) { m_kmsKeyHasBeenSet = true; m_kmsKey = value; } /** * <p>The AWS Key Management Service (KMS) key to encrypt and decrypt the data in * your environment. You can use an AWS KMS key managed by MWAA, or a custom KMS * key (advanced). For more information, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html?icmpid=docs_console_unmapped#master_keys">Customer * master keys (CMKs)</a> in the AWS KMS developer guide.</p> */ inline void SetKmsKey(Aws::String&& value) { m_kmsKeyHasBeenSet = true; m_kmsKey = std::move(value); } /** * <p>The AWS Key Management Service (KMS) key to encrypt and decrypt the data in * your environment. You can use an AWS KMS key managed by MWAA, or a custom KMS * key (advanced). For more information, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html?icmpid=docs_console_unmapped#master_keys">Customer * master keys (CMKs)</a> in the AWS KMS developer guide.</p> */ inline void SetKmsKey(const char* value) { m_kmsKeyHasBeenSet = true; m_kmsKey.assign(value); } /** * <p>The AWS Key Management Service (KMS) key to encrypt and decrypt the data in * your environment. You can use an AWS KMS key managed by MWAA, or a custom KMS * key (advanced). For more information, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html?icmpid=docs_console_unmapped#master_keys">Customer * master keys (CMKs)</a> in the AWS KMS developer guide.</p> */ inline CreateEnvironmentRequest& WithKmsKey(const Aws::String& value) { SetKmsKey(value); return *this;} /** * <p>The AWS Key Management Service (KMS) key to encrypt and decrypt the data in * your environment. You can use an AWS KMS key managed by MWAA, or a custom KMS * key (advanced). For more information, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html?icmpid=docs_console_unmapped#master_keys">Customer * master keys (CMKs)</a> in the AWS KMS developer guide.</p> */ inline CreateEnvironmentRequest& WithKmsKey(Aws::String&& value) { SetKmsKey(std::move(value)); return *this;} /** * <p>The AWS Key Management Service (KMS) key to encrypt and decrypt the data in * your environment. You can use an AWS KMS key managed by MWAA, or a custom KMS * key (advanced). For more information, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html?icmpid=docs_console_unmapped#master_keys">Customer * master keys (CMKs)</a> in the AWS KMS developer guide.</p> */ inline CreateEnvironmentRequest& WithKmsKey(const char* value) { SetKmsKey(value); return *this;} /** * <p>The Apache Airflow logs you want to send to Amazon CloudWatch Logs.</p> */ inline const LoggingConfigurationInput& GetLoggingConfiguration() const{ return m_loggingConfiguration; } /** * <p>The Apache Airflow logs you want to send to Amazon CloudWatch Logs.</p> */ inline bool LoggingConfigurationHasBeenSet() const { return m_loggingConfigurationHasBeenSet; } /** * <p>The Apache Airflow logs you want to send to Amazon CloudWatch Logs.</p> */ inline void SetLoggingConfiguration(const LoggingConfigurationInput& value) { m_loggingConfigurationHasBeenSet = true; m_loggingConfiguration = value; } /** * <p>The Apache Airflow logs you want to send to Amazon CloudWatch Logs.</p> */ inline void SetLoggingConfiguration(LoggingConfigurationInput&& value) { m_loggingConfigurationHasBeenSet = true; m_loggingConfiguration = std::move(value); } /** * <p>The Apache Airflow logs you want to send to Amazon CloudWatch Logs.</p> */ inline CreateEnvironmentRequest& WithLoggingConfiguration(const LoggingConfigurationInput& value) { SetLoggingConfiguration(value); return *this;} /** * <p>The Apache Airflow logs you want to send to Amazon CloudWatch Logs.</p> */ inline CreateEnvironmentRequest& WithLoggingConfiguration(LoggingConfigurationInput&& value) { SetLoggingConfiguration(std::move(value)); return *this;} /** * <p>The maximum number of workers that you want to run in your environment. MWAA * scales the number of Apache Airflow workers and the Fargate containers that run * your tasks up to the number you specify in this field. When there are no more * tasks running, and no more in the queue, MWAA disposes of the extra containers * leaving the one worker that is included with your environment.</p> */ inline int GetMaxWorkers() const{ return m_maxWorkers; } /** * <p>The maximum number of workers that you want to run in your environment. MWAA * scales the number of Apache Airflow workers and the Fargate containers that run * your tasks up to the number you specify in this field. When there are no more * tasks running, and no more in the queue, MWAA disposes of the extra containers * leaving the one worker that is included with your environment.</p> */ inline bool MaxWorkersHasBeenSet() const { return m_maxWorkersHasBeenSet; } /** * <p>The maximum number of workers that you want to run in your environment. MWAA * scales the number of Apache Airflow workers and the Fargate containers that run * your tasks up to the number you specify in this field. When there are no more * tasks running, and no more in the queue, MWAA disposes of the extra containers * leaving the one worker that is included with your environment.</p> */ inline void SetMaxWorkers(int value) { m_maxWorkersHasBeenSet = true; m_maxWorkers = value; } /** * <p>The maximum number of workers that you want to run in your environment. MWAA * scales the number of Apache Airflow workers and the Fargate containers that run * your tasks up to the number you specify in this field. When there are no more * tasks running, and no more in the queue, MWAA disposes of the extra containers * leaving the one worker that is included with your environment.</p> */ inline CreateEnvironmentRequest& WithMaxWorkers(int value) { SetMaxWorkers(value); return *this;} /** * <p>The name of your MWAA environment.</p> */ inline const Aws::String& GetName() const{ return m_name; } /** * <p>The name of your MWAA environment.</p> */ inline bool NameHasBeenSet() const { return m_nameHasBeenSet; } /** * <p>The name of your MWAA environment.</p> */ inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p>The name of your MWAA environment.</p> */ inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); } /** * <p>The name of your MWAA environment.</p> */ inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); } /** * <p>The name of your MWAA environment.</p> */ inline CreateEnvironmentRequest& WithName(const Aws::String& value) { SetName(value); return *this;} /** * <p>The name of your MWAA environment.</p> */ inline CreateEnvironmentRequest& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;} /** * <p>The name of your MWAA environment.</p> */ inline CreateEnvironmentRequest& WithName(const char* value) { SetName(value); return *this;} /** * <p>The VPC networking components you want to use for your environment. At least * two private subnet identifiers and one VPC security group identifier are * required to create an environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline const NetworkConfiguration& GetNetworkConfiguration() const{ return m_networkConfiguration; } /** * <p>The VPC networking components you want to use for your environment. At least * two private subnet identifiers and one VPC security group identifier are * required to create an environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline bool NetworkConfigurationHasBeenSet() const { return m_networkConfigurationHasBeenSet; } /** * <p>The VPC networking components you want to use for your environment. At least * two private subnet identifiers and one VPC security group identifier are * required to create an environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline void SetNetworkConfiguration(const NetworkConfiguration& value) { m_networkConfigurationHasBeenSet = true; m_networkConfiguration = value; } /** * <p>The VPC networking components you want to use for your environment. At least * two private subnet identifiers and one VPC security group identifier are * required to create an environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline void SetNetworkConfiguration(NetworkConfiguration&& value) { m_networkConfigurationHasBeenSet = true; m_networkConfiguration = std::move(value); } /** * <p>The VPC networking components you want to use for your environment. At least * two private subnet identifiers and one VPC security group identifier are * required to create an environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline CreateEnvironmentRequest& WithNetworkConfiguration(const NetworkConfiguration& value) { SetNetworkConfiguration(value); return *this;} /** * <p>The VPC networking components you want to use for your environment. At least * two private subnet identifiers and one VPC security group identifier are * required to create an environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline CreateEnvironmentRequest& WithNetworkConfiguration(NetworkConfiguration&& value) { SetNetworkConfiguration(std::move(value)); return *this;} /** * <p>The <code>plugins.zip</code> file version you want to use.</p> */ inline const Aws::String& GetPluginsS3ObjectVersion() const{ return m_pluginsS3ObjectVersion; } /** * <p>The <code>plugins.zip</code> file version you want to use.</p> */ inline bool PluginsS3ObjectVersionHasBeenSet() const { return m_pluginsS3ObjectVersionHasBeenSet; } /** * <p>The <code>plugins.zip</code> file version you want to use.</p> */ inline void SetPluginsS3ObjectVersion(const Aws::String& value) { m_pluginsS3ObjectVersionHasBeenSet = true; m_pluginsS3ObjectVersion = value; } /** * <p>The <code>plugins.zip</code> file version you want to use.</p> */ inline void SetPluginsS3ObjectVersion(Aws::String&& value) { m_pluginsS3ObjectVersionHasBeenSet = true; m_pluginsS3ObjectVersion = std::move(value); } /** * <p>The <code>plugins.zip</code> file version you want to use.</p> */ inline void SetPluginsS3ObjectVersion(const char* value) { m_pluginsS3ObjectVersionHasBeenSet = true; m_pluginsS3ObjectVersion.assign(value); } /** * <p>The <code>plugins.zip</code> file version you want to use.</p> */ inline CreateEnvironmentRequest& WithPluginsS3ObjectVersion(const Aws::String& value) { SetPluginsS3ObjectVersion(value); return *this;} /** * <p>The <code>plugins.zip</code> file version you want to use.</p> */ inline CreateEnvironmentRequest& WithPluginsS3ObjectVersion(Aws::String&& value) { SetPluginsS3ObjectVersion(std::move(value)); return *this;} /** * <p>The <code>plugins.zip</code> file version you want to use.</p> */ inline CreateEnvironmentRequest& WithPluginsS3ObjectVersion(const char* value) { SetPluginsS3ObjectVersion(value); return *this;} /** * <p>The relative path to the <code>plugins.zip</code> file on your Amazon S3 * storage bucket. For example, <code>plugins.zip</code>. If a relative path is * provided in the request, then <code>PluginsS3ObjectVersion</code> is required. * For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline const Aws::String& GetPluginsS3Path() const{ return m_pluginsS3Path; } /** * <p>The relative path to the <code>plugins.zip</code> file on your Amazon S3 * storage bucket. For example, <code>plugins.zip</code>. If a relative path is * provided in the request, then <code>PluginsS3ObjectVersion</code> is required. * For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline bool PluginsS3PathHasBeenSet() const { return m_pluginsS3PathHasBeenSet; } /** * <p>The relative path to the <code>plugins.zip</code> file on your Amazon S3 * storage bucket. For example, <code>plugins.zip</code>. If a relative path is * provided in the request, then <code>PluginsS3ObjectVersion</code> is required. * For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetPluginsS3Path(const Aws::String& value) { m_pluginsS3PathHasBeenSet = true; m_pluginsS3Path = value; } /** * <p>The relative path to the <code>plugins.zip</code> file on your Amazon S3 * storage bucket. For example, <code>plugins.zip</code>. If a relative path is * provided in the request, then <code>PluginsS3ObjectVersion</code> is required. * For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetPluginsS3Path(Aws::String&& value) { m_pluginsS3PathHasBeenSet = true; m_pluginsS3Path = std::move(value); } /** * <p>The relative path to the <code>plugins.zip</code> file on your Amazon S3 * storage bucket. For example, <code>plugins.zip</code>. If a relative path is * provided in the request, then <code>PluginsS3ObjectVersion</code> is required. * For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetPluginsS3Path(const char* value) { m_pluginsS3PathHasBeenSet = true; m_pluginsS3Path.assign(value); } /** * <p>The relative path to the <code>plugins.zip</code> file on your Amazon S3 * storage bucket. For example, <code>plugins.zip</code>. If a relative path is * provided in the request, then <code>PluginsS3ObjectVersion</code> is required. * For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithPluginsS3Path(const Aws::String& value) { SetPluginsS3Path(value); return *this;} /** * <p>The relative path to the <code>plugins.zip</code> file on your Amazon S3 * storage bucket. For example, <code>plugins.zip</code>. If a relative path is * provided in the request, then <code>PluginsS3ObjectVersion</code> is required. * For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithPluginsS3Path(Aws::String&& value) { SetPluginsS3Path(std::move(value)); return *this;} /** * <p>The relative path to the <code>plugins.zip</code> file on your Amazon S3 * storage bucket. For example, <code>plugins.zip</code>. If a relative path is * provided in the request, then <code>PluginsS3ObjectVersion</code> is required. * For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithPluginsS3Path(const char* value) { SetPluginsS3Path(value); return *this;} /** * <p>The <code>requirements.txt</code> file version you want to use.</p> */ inline const Aws::String& GetRequirementsS3ObjectVersion() const{ return m_requirementsS3ObjectVersion; } /** * <p>The <code>requirements.txt</code> file version you want to use.</p> */ inline bool RequirementsS3ObjectVersionHasBeenSet() const { return m_requirementsS3ObjectVersionHasBeenSet; } /** * <p>The <code>requirements.txt</code> file version you want to use.</p> */ inline void SetRequirementsS3ObjectVersion(const Aws::String& value) { m_requirementsS3ObjectVersionHasBeenSet = true; m_requirementsS3ObjectVersion = value; } /** * <p>The <code>requirements.txt</code> file version you want to use.</p> */ inline void SetRequirementsS3ObjectVersion(Aws::String&& value) { m_requirementsS3ObjectVersionHasBeenSet = true; m_requirementsS3ObjectVersion = std::move(value); } /** * <p>The <code>requirements.txt</code> file version you want to use.</p> */ inline void SetRequirementsS3ObjectVersion(const char* value) { m_requirementsS3ObjectVersionHasBeenSet = true; m_requirementsS3ObjectVersion.assign(value); } /** * <p>The <code>requirements.txt</code> file version you want to use.</p> */ inline CreateEnvironmentRequest& WithRequirementsS3ObjectVersion(const Aws::String& value) { SetRequirementsS3ObjectVersion(value); return *this;} /** * <p>The <code>requirements.txt</code> file version you want to use.</p> */ inline CreateEnvironmentRequest& WithRequirementsS3ObjectVersion(Aws::String&& value) { SetRequirementsS3ObjectVersion(std::move(value)); return *this;} /** * <p>The <code>requirements.txt</code> file version you want to use.</p> */ inline CreateEnvironmentRequest& WithRequirementsS3ObjectVersion(const char* value) { SetRequirementsS3ObjectVersion(value); return *this;} /** * <p>The relative path to the <code>requirements.txt</code> file on your Amazon S3 * storage bucket. For example, <code>requirements.txt</code>. If a relative path * is provided in the request, then <code>RequirementsS3ObjectVersion</code> is * required. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline const Aws::String& GetRequirementsS3Path() const{ return m_requirementsS3Path; } /** * <p>The relative path to the <code>requirements.txt</code> file on your Amazon S3 * storage bucket. For example, <code>requirements.txt</code>. If a relative path * is provided in the request, then <code>RequirementsS3ObjectVersion</code> is * required. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline bool RequirementsS3PathHasBeenSet() const { return m_requirementsS3PathHasBeenSet; } /** * <p>The relative path to the <code>requirements.txt</code> file on your Amazon S3 * storage bucket. For example, <code>requirements.txt</code>. If a relative path * is provided in the request, then <code>RequirementsS3ObjectVersion</code> is * required. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetRequirementsS3Path(const Aws::String& value) { m_requirementsS3PathHasBeenSet = true; m_requirementsS3Path = value; } /** * <p>The relative path to the <code>requirements.txt</code> file on your Amazon S3 * storage bucket. For example, <code>requirements.txt</code>. If a relative path * is provided in the request, then <code>RequirementsS3ObjectVersion</code> is * required. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetRequirementsS3Path(Aws::String&& value) { m_requirementsS3PathHasBeenSet = true; m_requirementsS3Path = std::move(value); } /** * <p>The relative path to the <code>requirements.txt</code> file on your Amazon S3 * storage bucket. For example, <code>requirements.txt</code>. If a relative path * is provided in the request, then <code>RequirementsS3ObjectVersion</code> is * required. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetRequirementsS3Path(const char* value) { m_requirementsS3PathHasBeenSet = true; m_requirementsS3Path.assign(value); } /** * <p>The relative path to the <code>requirements.txt</code> file on your Amazon S3 * storage bucket. For example, <code>requirements.txt</code>. If a relative path * is provided in the request, then <code>RequirementsS3ObjectVersion</code> is * required. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithRequirementsS3Path(const Aws::String& value) { SetRequirementsS3Path(value); return *this;} /** * <p>The relative path to the <code>requirements.txt</code> file on your Amazon S3 * storage bucket. For example, <code>requirements.txt</code>. If a relative path * is provided in the request, then <code>RequirementsS3ObjectVersion</code> is * required. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithRequirementsS3Path(Aws::String&& value) { SetRequirementsS3Path(std::move(value)); return *this;} /** * <p>The relative path to the <code>requirements.txt</code> file on your Amazon S3 * storage bucket. For example, <code>requirements.txt</code>. If a relative path * is provided in the request, then <code>RequirementsS3ObjectVersion</code> is * required. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithRequirementsS3Path(const char* value) { SetRequirementsS3Path(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, * <code>arn:aws:s3:::airflow-mybucketname</code>.</p> */ inline const Aws::String& GetSourceBucketArn() const{ return m_sourceBucketArn; } /** * <p>The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, * <code>arn:aws:s3:::airflow-mybucketname</code>.</p> */ inline bool SourceBucketArnHasBeenSet() const { return m_sourceBucketArnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, * <code>arn:aws:s3:::airflow-mybucketname</code>.</p> */ inline void SetSourceBucketArn(const Aws::String& value) { m_sourceBucketArnHasBeenSet = true; m_sourceBucketArn = value; } /** * <p>The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, * <code>arn:aws:s3:::airflow-mybucketname</code>.</p> */ inline void SetSourceBucketArn(Aws::String&& value) { m_sourceBucketArnHasBeenSet = true; m_sourceBucketArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, * <code>arn:aws:s3:::airflow-mybucketname</code>.</p> */ inline void SetSourceBucketArn(const char* value) { m_sourceBucketArnHasBeenSet = true; m_sourceBucketArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, * <code>arn:aws:s3:::airflow-mybucketname</code>.</p> */ inline CreateEnvironmentRequest& WithSourceBucketArn(const Aws::String& value) { SetSourceBucketArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, * <code>arn:aws:s3:::airflow-mybucketname</code>.</p> */ inline CreateEnvironmentRequest& WithSourceBucketArn(Aws::String&& value) { SetSourceBucketArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, * <code>arn:aws:s3:::airflow-mybucketname</code>.</p> */ inline CreateEnvironmentRequest& WithSourceBucketArn(const char* value) { SetSourceBucketArn(value); return *this;} /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline const Aws::Map<Aws::String, Aws::String>& GetTags() const{ return m_tags; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline void SetTags(const Aws::Map<Aws::String, Aws::String>& value) { m_tagsHasBeenSet = true; m_tags = value; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline void SetTags(Aws::Map<Aws::String, Aws::String>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& WithTags(const Aws::Map<Aws::String, Aws::String>& value) { SetTags(value); return *this;} /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& WithTags(Aws::Map<Aws::String, Aws::String>&& value) { SetTags(std::move(value)); return *this;} /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& AddTags(const Aws::String& key, const Aws::String& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, value); return *this; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& AddTags(Aws::String&& key, const Aws::String& value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), value); return *this; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& AddTags(const Aws::String& key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, std::move(value)); return *this; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& AddTags(Aws::String&& key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), std::move(value)); return *this; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& AddTags(const char* key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, std::move(value)); return *this; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& AddTags(Aws::String&& key, const char* value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), value); return *this; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& AddTags(const char* key, const char* value) { m_tagsHasBeenSet = true; m_tags.emplace(key, value); return *this; } /** * <p>The networking access of your Apache Airflow web server. A public network * allows your Airflow UI to be accessed over the Internet by users granted access * in your IAM policy. A private network limits access of your Airflow UI to users * within your VPC. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline const WebserverAccessMode& GetWebserverAccessMode() const{ return m_webserverAccessMode; } /** * <p>The networking access of your Apache Airflow web server. A public network * allows your Airflow UI to be accessed over the Internet by users granted access * in your IAM policy. A private network limits access of your Airflow UI to users * within your VPC. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline bool WebserverAccessModeHasBeenSet() const { return m_webserverAccessModeHasBeenSet; } /** * <p>The networking access of your Apache Airflow web server. A public network * allows your Airflow UI to be accessed over the Internet by users granted access * in your IAM policy. A private network limits access of your Airflow UI to users * within your VPC. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline void SetWebserverAccessMode(const WebserverAccessMode& value) { m_webserverAccessModeHasBeenSet = true; m_webserverAccessMode = value; } /** * <p>The networking access of your Apache Airflow web server. A public network * allows your Airflow UI to be accessed over the Internet by users granted access * in your IAM policy. A private network limits access of your Airflow UI to users * within your VPC. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline void SetWebserverAccessMode(WebserverAccessMode&& value) { m_webserverAccessModeHasBeenSet = true; m_webserverAccessMode = std::move(value); } /** * <p>The networking access of your Apache Airflow web server. A public network * allows your Airflow UI to be accessed over the Internet by users granted access * in your IAM policy. A private network limits access of your Airflow UI to users * within your VPC. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline CreateEnvironmentRequest& WithWebserverAccessMode(const WebserverAccessMode& value) { SetWebserverAccessMode(value); return *this;} /** * <p>The networking access of your Apache Airflow web server. A public network * allows your Airflow UI to be accessed over the Internet by users granted access * in your IAM policy. A private network limits access of your Airflow UI to users * within your VPC. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline CreateEnvironmentRequest& WithWebserverAccessMode(WebserverAccessMode&& value) { SetWebserverAccessMode(std::move(value)); return *this;} /** * <p>The day and time you want MWAA to start weekly maintenance updates on your * environment.</p> */ inline const Aws::String& GetWeeklyMaintenanceWindowStart() const{ return m_weeklyMaintenanceWindowStart; } /** * <p>The day and time you want MWAA to start weekly maintenance updates on your * environment.</p> */ inline bool WeeklyMaintenanceWindowStartHasBeenSet() const { return m_weeklyMaintenanceWindowStartHasBeenSet; } /** * <p>The day and time you want MWAA to start weekly maintenance updates on your * environment.</p> */ inline void SetWeeklyMaintenanceWindowStart(const Aws::String& value) { m_weeklyMaintenanceWindowStartHasBeenSet = true; m_weeklyMaintenanceWindowStart = value; } /** * <p>The day and time you want MWAA to start weekly maintenance updates on your * environment.</p> */ inline void SetWeeklyMaintenanceWindowStart(Aws::String&& value) { m_weeklyMaintenanceWindowStartHasBeenSet = true; m_weeklyMaintenanceWindowStart = std::move(value); } /** * <p>The day and time you want MWAA to start weekly maintenance updates on your * environment.</p> */ inline void SetWeeklyMaintenanceWindowStart(const char* value) { m_weeklyMaintenanceWindowStartHasBeenSet = true; m_weeklyMaintenanceWindowStart.assign(value); } /** * <p>The day and time you want MWAA to start weekly maintenance updates on your * environment.</p> */ inline CreateEnvironmentRequest& WithWeeklyMaintenanceWindowStart(const Aws::String& value) { SetWeeklyMaintenanceWindowStart(value); return *this;} /** * <p>The day and time you want MWAA to start weekly maintenance updates on your * environment.</p> */ inline CreateEnvironmentRequest& WithWeeklyMaintenanceWindowStart(Aws::String&& value) { SetWeeklyMaintenanceWindowStart(std::move(value)); return *this;} /** * <p>The day and time you want MWAA to start weekly maintenance updates on your * environment.</p> */ inline CreateEnvironmentRequest& WithWeeklyMaintenanceWindowStart(const char* value) { SetWeeklyMaintenanceWindowStart(value); return *this;} private: Aws::Map<Aws::String, Aws::String> m_airflowConfigurationOptions; bool m_airflowConfigurationOptionsHasBeenSet; Aws::String m_airflowVersion; bool m_airflowVersionHasBeenSet; Aws::String m_dagS3Path; bool m_dagS3PathHasBeenSet; Aws::String m_environmentClass; bool m_environmentClassHasBeenSet; Aws::String m_executionRoleArn; bool m_executionRoleArnHasBeenSet; Aws::String m_kmsKey; bool m_kmsKeyHasBeenSet; LoggingConfigurationInput m_loggingConfiguration; bool m_loggingConfigurationHasBeenSet; int m_maxWorkers; bool m_maxWorkersHasBeenSet; Aws::String m_name; bool m_nameHasBeenSet; NetworkConfiguration m_networkConfiguration; bool m_networkConfigurationHasBeenSet; Aws::String m_pluginsS3ObjectVersion; bool m_pluginsS3ObjectVersionHasBeenSet; Aws::String m_pluginsS3Path; bool m_pluginsS3PathHasBeenSet; Aws::String m_requirementsS3ObjectVersion; bool m_requirementsS3ObjectVersionHasBeenSet; Aws::String m_requirementsS3Path; bool m_requirementsS3PathHasBeenSet; Aws::String m_sourceBucketArn; bool m_sourceBucketArnHasBeenSet; Aws::Map<Aws::String, Aws::String> m_tags; bool m_tagsHasBeenSet; WebserverAccessMode m_webserverAccessMode; bool m_webserverAccessModeHasBeenSet; Aws::String m_weeklyMaintenanceWindowStart; bool m_weeklyMaintenanceWindowStartHasBeenSet; }; } // namespace Model } // namespace MWAA } // namespace Aws
Java
# Puccinia isoglossae Doidge SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Bothalia 2(1a): 72 (1926) #### Original name Puccinia isoglossae Doidge ### Remarks null
Java
# Uromyces veratri f. adenostylis E. Fisch. FORM #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Uromyces veratri f. adenostylis E. Fisch. ### Remarks null
Java
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Powerfront.Backend.EntityFramework { using System; using System.Collections.Generic; public partial class Type { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Type() { this.CustomerRecords = new HashSet<CustomerRecord>(); } public string TypeId { get; set; } public string Name { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<CustomerRecord> CustomerRecords { get; set; } } }
Java
/* * Copyright (c) 2012. Piraso Alvin R. de Leon. All Rights Reserved. * * See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The Piraso 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.piraso.server.sql; import org.piraso.server.AbstractContextLoggerBeanProcessor; import javax.sql.DataSource; /** * Create a bean post processor which ensures that any bean instance of type {@link DataSource} will * be wrap by a context logger aware instance. * */ public class SQLContextLoggerBeanPostProcessor extends AbstractContextLoggerBeanProcessor<DataSource> { public SQLContextLoggerBeanPostProcessor() { super(DataSource.class); } @Override public DataSource createProxy(DataSource o, String id) { return SQLContextLogger.create(o, id); } }
Java
package org.lionsoul.jcseg.util; import java.io.Serializable; /** * string buffer class * * @author chenxin<chenxin619315@gmail.com> */ public class IStringBuffer implements Serializable { private static final long serialVersionUID = 1L; /** * buffer char array. */ private char buff[]; private int count; /** * create a buffer with a default length 16 */ public IStringBuffer() { this(16); } /** * create a buffer with a specified length * * @param length */ public IStringBuffer( int length ) { if ( length <= 0 ) { throw new IllegalArgumentException("length <= 0"); } buff = new char[length]; count = 0; } /** * create a buffer with a specified string * * @param str */ public IStringBuffer( String str ) { this(str.length()+16); append(str); } /** * resize the buffer * this will have to copy the old chars from the old buffer to the new buffer * * @param length */ private void resizeTo( int length ) { if ( length <= 0 ) throw new IllegalArgumentException("length <= 0"); if ( length != buff.length ) { int len = ( length > buff.length ) ? buff.length : length; //System.out.println("resize:"+length); char[] obuff = buff; buff = new char[length]; /*for ( int j = 0; j < len; j++ ) { buff[j] = obuff[j]; }*/ System.arraycopy(obuff, 0, buff, 0, len); } } /** * append a string to the buffer * * @param str string to append to */ public IStringBuffer append( String str ) { if ( str == null ) throw new NullPointerException(); //check the necessary to resize the buffer. if ( count + str.length() > buff.length ) { resizeTo( (count + str.length()) * 2 + 1 ); } for ( int j = 0; j < str.length(); j++ ) { buff[count++] = str.charAt(j); } return this; } /** * append parts of the chars to the buffer * * @param chars * @param start the start index * @param length length of chars to append to */ public IStringBuffer append( char[] chars, int start, int length ) { if ( chars == null ) throw new NullPointerException(); if ( start < 0 ) throw new IndexOutOfBoundsException(); if ( length <= 0 ) throw new IndexOutOfBoundsException(); if ( start + length > chars.length ) throw new IndexOutOfBoundsException(); //check the necessary to resize the buffer. if ( count + length > buff.length ) { resizeTo( (count + length) * 2 + 1 ); } for ( int j = 0; j < length; j++ ) { buff[count++] = chars[start+j]; } return this; } /** * append the rest of the chars to the buffer * * @param chars * @param start the start index * @return IStringBuffer * */ public IStringBuffer append( char[] chars, int start ) { append(chars, start, chars.length - start); return this; } /** * append some chars to the buffer * * @param chars */ public IStringBuffer append( char[] chars ) { return append(chars, 0, chars.length); } /** * append a char to the buffer * * @param c the char to append to */ public IStringBuffer append( char c ) { if ( count == buff.length ) { resizeTo( buff.length * 2 + 1 ); } buff[count++] = c; return this; } /** * append a boolean value * * @param bool */ public IStringBuffer append(boolean bool) { String str = bool ? "true" : "false"; return append(str); } /** * append a short value * * @param shortv */ public IStringBuffer append(short shortv) { return append(String.valueOf(shortv)); } /** * append a int value * * @param intv */ public IStringBuffer append(int intv) { return append(String.valueOf(intv)); } /** * append a long value * * @param longv */ public IStringBuffer append(long longv) { return append(String.valueOf(longv)); } /** * append a float value * * @param floatv */ public IStringBuffer append(float floatv) { return append(String.valueOf(floatv)); } /** * append a double value * * @param doublev */ public IStringBuffer append(double doublev) { return append(String.valueOf(doublev)); } /** * return the length of the buffer * * @return int the length of the buffer */ public int length() { return count; } /** * set the length of the buffer * actually it just override the count and the actual buffer * has nothing changed * * @param length */ public int setLength(int length) { int oldCount = count; count = length; return oldCount; } /** * get the char at a specified position in the buffer */ public char charAt( int idx ) { if ( idx < 0 ) throw new IndexOutOfBoundsException("idx{"+idx+"} < 0"); if ( idx >= count ) throw new IndexOutOfBoundsException("idx{"+idx+"} >= buffer.length"); return buff[idx]; } /** * always return the last char * * @return char */ public char last() { if ( count == 0 ) { throw new IndexOutOfBoundsException("Empty buffer"); } return buff[count-1]; } /** * always return the first char * * @return char */ public char first() { if ( count == 0 ) { throw new IndexOutOfBoundsException("Empty buffer"); } return buff[0]; } /** * delete the char at the specified position */ public IStringBuffer deleteCharAt( int idx ) { if ( idx < 0 ) throw new IndexOutOfBoundsException("idx < 0"); if ( idx >= count ) throw new IndexOutOfBoundsException("idx >= buffer.length"); //here we got a bug for j < count //change over it to count - 1 //thanks for the feedback of xuyijun@gmail.com //@date 2013-08-22 for ( int j = idx; j < count - 1; j++ ) { buff[j] = buff[j+1]; } count--; return this; } /** * set the char at the specified index * * @param idx * @param chr */ public void set(int idx, char chr) { if ( idx < 0 ) throw new IndexOutOfBoundsException("idx < 0"); if ( idx >= count ) throw new IndexOutOfBoundsException("idx >= buffer.length"); buff[idx] = chr; } /** * return the chars of the buffer * * @return char[] */ public char[] buffer() { return buff; } /** * clear the buffer by reset the count to 0 */ public IStringBuffer clear() { count = 0; return this; } /** * return the string of the current buffer * * @return String * @see Object#toString() */ public String toString() { return new String(buff, 0, count); } }
Java
/* * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef MODULES_VIDEO_CODING_CODECS_STEREO_INCLUDE_STEREO_ENCODER_ADAPTER_H_ #define MODULES_VIDEO_CODING_CODECS_STEREO_INCLUDE_STEREO_ENCODER_ADAPTER_H_ #include <map> #include <memory> #include <vector> #include "api/video_codecs/sdp_video_format.h" #include "api/video_codecs/video_encoder.h" #include "api/video_codecs/video_encoder_factory.h" #include "modules/video_coding/include/video_codec_interface.h" namespace webrtc { enum AlphaCodecStream { kYUVStream = 0, kAXXStream = 1, kAlphaCodecStreams = 2, }; class StereoEncoderAdapter : public VideoEncoder { public: // |factory| is not owned and expected to outlive this class' lifetime. explicit StereoEncoderAdapter(VideoEncoderFactory* factory, const SdpVideoFormat& associated_format); virtual ~StereoEncoderAdapter(); // Implements VideoEncoder int InitEncode(const VideoCodec* inst, int number_of_cores, size_t max_payload_size) override; int Encode(const VideoFrame& input_image, const CodecSpecificInfo* codec_specific_info, const std::vector<FrameType>* frame_types) override; int RegisterEncodeCompleteCallback(EncodedImageCallback* callback) override; int SetChannelParameters(uint32_t packet_loss, int64_t rtt) override; int SetRateAllocation(const BitrateAllocation& bitrate, uint32_t new_framerate) override; int Release() override; const char* ImplementationName() const override; EncodedImageCallback::Result OnEncodedImage( AlphaCodecStream stream_idx, const EncodedImage& encodedImage, const CodecSpecificInfo* codecSpecificInfo, const RTPFragmentationHeader* fragmentation); private: // Wrapper class that redirects OnEncodedImage() calls. class AdapterEncodedImageCallback; VideoEncoderFactory* const factory_; const SdpVideoFormat associated_format_; std::vector<std::unique_ptr<VideoEncoder>> encoders_; std::vector<std::unique_ptr<AdapterEncodedImageCallback>> adapter_callbacks_; EncodedImageCallback* encoded_complete_callback_; // Holds the encoded image info. struct ImageStereoInfo; std::map<uint32_t /* timestamp */, ImageStereoInfo> image_stereo_info_; uint16_t picture_index_ = 0; std::vector<uint8_t> stereo_dummy_planes_; }; } // namespace webrtc #endif // MODULES_VIDEO_CODING_CODECS_STEREO_INCLUDE_STEREO_ENCODER_ADAPTER_H_
Java
package net.happybrackets.core.control; import com.google.gson.Gson; import de.sciss.net.OSCMessage; import net.happybrackets.core.Device; import net.happybrackets.core.OSCVocabulary; import net.happybrackets.core.scheduling.HBScheduler; import net.happybrackets.core.scheduling.ScheduledEventListener; import net.happybrackets.core.scheduling.ScheduledObject; import net.happybrackets.device.HB; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.*; /** * This class facilitates sending message values between sketches, * devices, and a graphical environment. * The values can be represented as sliders, text boxes, check boxes, and buttons * * A message can either be an integer, a double, a string, a boolean, a trigger or a complete class. * * Although similar to the send and receive objects in Max in that the name and type * parameter of the {@link DynamicControl} determines message interconnection, * DynamicControls also have an attribute called {@link ControlScope}, which dictates how far (in * a topological sense) the object can reach in order to communicate with other * DynamicControls. DynamicControls can be bound to different objects, the default being the class that instantiated it. * * <br>The classes are best accessed through {@link DynamicControlParent} abstractions * */ public class DynamicControl implements ScheduledEventListener { static Gson gson = new Gson(); // flag for testing static boolean ignoreName = false; private boolean isPersistentControl = false; /** * Set ignore name for testing * @param ignore true to ignore */ static void setIgnoreName(boolean ignore){ ignoreName = true; } static int deviceSendId = 0; // we will use this to number all messages we send. They can be filtered at receiver by testing last message mapped /** * Define a list of target devices. Can be either device name or IP address * If it is a device name, there will be a lookup of stored device names */ Set<String> targetDevices = new HashSet<>(); // we will map Message ID to device name. If the last ID is in this map, we will ignore message static Map<String, Integer> messageIdMap = new Hashtable<>(); /** * See if we will process a control message based on device name and message_id * If the message_id is mapped against the device_name, ignore message, otherwise store mapping and return true; * @param device_name the device name * @param message_id the message_id * @return true if we are going to process this message */ public static boolean enableProcessControlMessage(String device_name, int message_id){ boolean ret = true; if (messageIdMap.containsKey(device_name)) { if (messageIdMap.get(device_name) == message_id) { ret = false; } } if (ret){ messageIdMap.put(device_name, message_id); } return ret; } // The device name that set last message to this control // A Null value will indicate that it was this device String sendingDevice = null; /** * Get the name of the device that sent the message. If the message was local, will return this device name * @return name of device that sent message */ public String getSendingDevice(){ String ret = sendingDevice; if (ret == null) { ret = deviceName; } return ret; } /** * Define how we want the object displayed in the plugin */ public enum DISPLAY_TYPE { DISPLAY_DEFAULT, DISPLAY_HIDDEN, DISPLAY_DISABLED, DISPLAY_ENABLED_BUDDY, DISPLAY_DISABLED_BUDDY } /** * Return all mapped device addresses for this control * @return returns the set of mapped targeted devices */ public Set<String> getTargetDeviceAddresses(){ return targetDevices; } @Override public void doScheduledEvent(double scheduledTime, Object param) { FutureControlMessage message = (FutureControlMessage) param; this.objVal = message.controlValue; this.executionTime = 0; this.sendingDevice = message.sourceDevice; notifyLocalListeners(); if (!message.localOnly) { notifyValueSetListeners(); } synchronized (futureMessageListLock) { futureMessageList.remove(message); } } /** * Add one or more device names or addresses as strings to use in {@link ControlScope#TARGET} Message * @param deviceNames device name or IP Address */ public synchronized void addTargetDevice(String... deviceNames){ for (String name: deviceNames) { targetDevices.add(name); } } /** * Remove all set target devices and replace with the those provided as arguments * Adds device address as a string or device name to {@link ControlScope#TARGET} Message * @param deviceNames device name or IP Address */ public synchronized void setTargetDevice(String... deviceNames){ targetDevices.clear(); addTargetDevice(deviceNames); } /** * Remove all set target devices and replace with the those provided as arguments * Adds device addresses to {@link ControlScope#TARGET} Message * @param inetAddresses device name or IP Address */ public synchronized void setTargetDevice(InetAddress... inetAddresses){ targetDevices.clear(); addTargetDevice(inetAddresses); } /** * Add one or more device {@link InetAddress} for use in {@link ControlScope#TARGET} Message * @param inetAddresses the target addresses to add */ public void addTargetDevice(InetAddress... inetAddresses){ for (InetAddress address: inetAddresses) { targetDevices.add(address.getHostAddress()); } } /** * Clear all devices as Targets */ public synchronized void clearTargetDevices(){ targetDevices.clear(); } /** * Remove one or more device names or addresses as a string. * For use in {@link ControlScope#TARGET} Messages * @param deviceNames device names or IP Addresses to remove */ public synchronized void removeTargetDevice(String... deviceNames){ for (String name: deviceNames) { targetDevices.remove(name); } } /** * Remove one or more {@link InetAddress} for use in {@link ControlScope#TARGET} Message * @param inetAddresses the target addresses to remove */ public void removeTargetDevice(InetAddress... inetAddresses){ for (InetAddress address: inetAddresses) { targetDevices.remove(address.getHostAddress()); } } /** * Create an Interface to listen to */ public interface DynamicControlListener { void update(DynamicControl control); } public interface ControlScopeChangedListener { void controlScopeChanged(ControlScope new_scope); } /** * The way Create Messages are sent */ private enum CREATE_MESSAGE_ARGS { DEVICE_NAME, MAP_KEY, CONTROL_NAME, PARENT_SKETCH_NAME, PARENT_SKETCH_ID, CONTROL_TYPE, OBJ_VAL, MIN_VAL, MAX_VAL, CONTROL_SCOPE, DISPLAY_TYPE_VAL } // Define the Arguments used in an Update message private enum UPDATE_MESSAGE_ARGS { DEVICE_NAME, CONTROL_NAME, CONTROL_TYPE, MAP_KEY, OBJ_VAL, CONTROL_SCOPE, DISPLAY_TYPE_VAL, MIN_VALUE, MAX_VALUE } // Define Global Message arguments public enum NETWORK_TRANSMIT_MESSAGE_ARGS { DEVICE_NAME, CONTROL_NAME, CONTROL_TYPE, OBJ_VAL, EXECUTE_TIME_MLILI_MS, // Most Significant Int of Milliseconds - stored as int EXECUTE_TIME_MLILI_LS, // Least Significant Bit of Milliseconds - stored as int EXECUTE_TIME_NANO, // Number on Nano Seconds - stored as int MESSAGE_ID // we will increment an integer and send the message multiple times. We will ignore message if last message was this one } // Define Device Name Message arguments private enum DEVICE_NAME_ARGS { DEVICE_NAME } // Define where our first Array type global dynamic control message is in OSC final static int OSC_TRANSMIT_ARRAY_ARG = NETWORK_TRANSMIT_MESSAGE_ARGS.MESSAGE_ID.ordinal() + 1; // When an event is scheduled in the future, we will create one of these and schedule it class FutureControlMessage{ /** * Create a Future Control message * @param source_device the source device name * @param value the value to be executed * @param execution_time the time the value needs to be executed */ public FutureControlMessage(String source_device, Object value, double execution_time){ sourceDevice = source_device; controlValue = value; executionTime = execution_time; } Object controlValue; double executionTime; boolean localOnly = false; // if we are local only, we will not sendValue changed listeners String sourceDevice; /// have a copy of our pending scheduled object in case we want to cancel it ScheduledObject pendingSchedule = null; } static ControlMap controlMap = ControlMap.getInstance(); private static final Object controlMapLock = new Object(); private static int instanceCounter = 0; // we will use this to order the creation of our objects and give them a unique number on device private final Object instanceCounterLock = new Object(); private final Object valueChangedLock = new Object(); private final String controlMapKey; private List<DynamicControlListener> controlListenerList = new ArrayList<>(); private List<DynamicControlListener> globalControlListenerList = new ArrayList<>(); private List<ControlScopeChangedListener> controlScopeChangedList = new ArrayList<>(); private List<FutureControlMessage> futureMessageList = new ArrayList<>(); // This listener is only called when value on control set private List<DynamicControlListener> valueSetListenerList = new ArrayList<>(); // Create Object to lock shared resources private final Object controlScopeChangedLock = new Object(); private final Object controlListenerLock = new Object(); private final Object globalListenerLock = new Object(); private final Object valueSetListenerLock = new Object(); private final Object futureMessageListLock = new Object(); static boolean disableScheduler = false; // set flag if we are going to disable scheduler - eg, in GUI /** * Create the text we will display at the beginning of tooltip * @param tooltipPrefix The starting text of the tooltip * @return this object */ public DynamicControl setTooltipPrefix(String tooltipPrefix) { this.tooltipPrefix = tooltipPrefix; return this; } private String tooltipPrefix = ""; // The Object sketch that this control was created in private Object parentSketch = null; final int parentId; private final String deviceName; private String parentSketchName; private ControlType controlType; final String controlName; private ControlScope controlScope = ControlScope.SKETCH; private Object objVal = 0; private Object maximumDisplayValue = 0; private Object minimumDisplayValue = 0; // This is the time we want to execute the control value private double executionTime = 0; DISPLAY_TYPE displayType = DISPLAY_TYPE.DISPLAY_DEFAULT; // Whether the control is displayType on control Screen /** * Set whether we disable setting all values in context of scheduler * @param disabled set true to disable */ public static void setDisableScheduler(boolean disabled){ disableScheduler = disabled; } /** * Whether we disable the control on the screen * @return How we will disable control on screen */ public DISPLAY_TYPE getDisplayType(){ return displayType; } /** * Set how we will display control object on the screen * @param display_type how we will display control * @return this */ public DynamicControl setDisplayType(DISPLAY_TYPE display_type){ displayType = display_type; notifyValueSetListeners(); //notifyLocalListeners(); return this; } /** * Returns the JVM execution time we last used when we set the value * @return lastExecution time set */ public double getExecutionTime(){ return executionTime; } /** * Convert a float or int into required number type based on control. If not a FLOAT or INT, will just return value * @param control_type the control type * @param source_value the value we want * @return the converted value */ static private Object convertValue (ControlType control_type, Object source_value) { Object ret = source_value; // Convert if we are a float control if (control_type == ControlType.FLOAT) { if (source_value == null){ ret = 0.0; }else if (source_value instanceof Integer) { Integer i = (Integer) source_value; double f = i.doubleValue(); ret = f; }else if (source_value instanceof Double) { Double d = (Double) source_value; ret = d; }else if (source_value instanceof Long) { Long l = (Long) source_value; double f = l.doubleValue(); ret = f; } else if (source_value instanceof Float) { double f = (Float) source_value; ret = f; } else if (source_value instanceof String) { double f = Double.parseDouble((String)source_value); ret = f; } // Convert if we are an int control } else if (control_type == ControlType.INT) { if (source_value == null){ ret = 0; }else if (source_value instanceof Float) { Float f = (Float) source_value; Integer i = f.intValue(); ret = i; }else if (source_value instanceof Double) { Double d = (Double) source_value; Integer i = d.intValue(); ret = i; }else if (source_value instanceof Long) { Long l = (Long) source_value; Integer i = l.intValue(); ret = i; } // Convert if we are a BOOLEAN control } else if (control_type == ControlType.BOOLEAN) { if (source_value == null){ ret = 0; }if (source_value instanceof Integer) { Integer i = (Integer) source_value; Boolean b = i != 0; ret = b; }else if (source_value instanceof Long) { Long l = (Long) source_value; Integer i = l.intValue(); Boolean b = i != 0; ret = b; } // Convert if we are a TRIGGER control }else if (control_type == ControlType.TRIGGER) { if (source_value == null) { ret = System.currentTimeMillis(); } // Convert if we are a TEXT control }else if (control_type == ControlType.TEXT) { if (source_value == null) { ret = ""; } } return ret; } /** * Get the Sketch or class object linked to this control * @return the parentSketch or Object */ public Object getParentSketch() { return parentSketch; } /** * This is a private constructor used to initialise constant attributes of this object * * @param parent_sketch the object calling - typically this * @param control_type The type of control you want to create * @param name The name we will give to differentiate between different controls in this class * @param initial_value The initial value of the control * @param display_type how we want to display the object * */ private DynamicControl(Object parent_sketch, ControlType control_type, String name, Object initial_value, DISPLAY_TYPE display_type) { if (parent_sketch == null){ parent_sketch = new Object(); } displayType = display_type; parentSketch = parent_sketch; parentSketchName = parent_sketch.getClass().getName(); controlType = control_type; controlName = name; objVal = convertValue (control_type, initial_value); parentId = parent_sketch.hashCode(); deviceName = Device.getDeviceName(); synchronized (instanceCounterLock) { controlMapKey = Device.getDeviceName() + instanceCounter; instanceCounter++; } } /** * Ascertain the Control Type based on the Value * @param value the value we are obtaing a control value from * @return a control type */ public static ControlType getControlType(Object value){ ControlType ret = ControlType.OBJECT; if (value == null){ ret = ControlType.TRIGGER; } else if (value instanceof Float || value instanceof Double){ ret = ControlType.FLOAT; } else if (value instanceof Boolean){ ret = ControlType.BOOLEAN; } else if (value instanceof String){ ret = ControlType.TEXT; } else if (value instanceof Integer || value instanceof Long){ ret = ControlType.INT; } return ret; } /** * A dynamic control that can be accessed from outside this sketch * it is created with the sketch object that contains it along with the type * * @param name The name we will give to associate it with other DynamicControls with identical ControlScope and type. * @param initial_value The initial value of the control */ public DynamicControl(String name, Object initial_value) { this(new Object(), getControlType(initial_value), name, initial_value, DISPLAY_TYPE.DISPLAY_DEFAULT); synchronized (controlMapLock) { controlMap.addControl(this); } } /** * A dynamic control that can be accessed from outside this sketch * it is created with the sketch object that contains it along with the type * * @param control_type The type of control message you want to send * @param name The name we will give to associate it with other DynamicControls with identical ControlScope and type. * @param initial_value The initial value of the control */ public DynamicControl(ControlType control_type, String name, Object initial_value) { this(new Object(), control_type, name, initial_value, DISPLAY_TYPE.DISPLAY_DEFAULT); synchronized (controlMapLock) { controlMap.addControl(this); } } /** * A dynamic control that can be accessed from outside this sketch * it is created with the sketch object that contains it along with the type * @param parent_sketch the object calling - typically this, however, you can use any class object * @param control_type The type of control message you want to send * @param name The name we will give to associate it with other DynamicControls with identical ControlScope and type. */ public DynamicControl(Object parent_sketch, ControlType control_type, String name) { this(parent_sketch, control_type, name, null, DISPLAY_TYPE.DISPLAY_DEFAULT); synchronized (controlMapLock) { controlMap.addControl(this); } } /** * A dynamic control that can be accessed from outside this sketch * it is created with the sketch object that contains it along with the type * * @param control_type The type of control message you want to send * @param name The name we will give to associate it with other DynamicControls with identical ControlScope and type. */ public DynamicControl(ControlType control_type, String name) { this(new Object(), control_type, name, convertValue(control_type, null), DISPLAY_TYPE.DISPLAY_DEFAULT); synchronized (controlMapLock) { controlMap.addControl(this); } } /** * A dynamic control that can be accessed from outside this sketch * it is created with the sketch object that contains it along with the type * * @param parent_sketch the object calling - typically this, however, you can use any class object * @param control_type The type of control message you want to send * @param name The name we will give to associate it with other DynamicControls with identical ControlScope and type. * @param initial_value The initial value of the control */ public DynamicControl(Object parent_sketch, ControlType control_type, String name, Object initial_value) { this(parent_sketch, control_type, name, initial_value, DISPLAY_TYPE.DISPLAY_DEFAULT); synchronized (controlMapLock) { controlMap.addControl(this); } } /** * Set this control as a persistentSimulation control so it does not get removed on reset * @return this */ public DynamicControl setPersistentController(){ controlMap.addPersistentControl(this); isPersistentControl = true; return this; } /** * See if control is a persistent control * @return true if a simulator control */ public boolean isPersistentControl() { return isPersistentControl; } /** * A dynamic control that can be accessed from outside * it is created with the sketch object that contains it along with the type * * @param parent_sketch the object calling - typically this, however, you can use any class object * @param control_type The type of control message you want to send * @param name The name we will give to associate it with other DynamicControls with identical ControlScope and type. * @param initial_value The initial value of the control * @param min_value The minimum display value of the control. Only used for display purposes * @param max_value The maximum display value of the control. Only used for display purposes */ public DynamicControl(Object parent_sketch, ControlType control_type, String name, Object initial_value, Object min_value, Object max_value) { this(parent_sketch, control_type, name, initial_value, DISPLAY_TYPE.DISPLAY_DEFAULT); minimumDisplayValue = convertValue (control_type, min_value); maximumDisplayValue = convertValue (control_type, max_value); synchronized (controlMapLock) { controlMap.addControl(this); } } /** * A dynamic control that can be accessed from outside * it is created with the sketch object that contains it along with the type * * @param parent_sketch the object calling - typically this, however, you can use any class object * @param control_type The type of control message you want to send * @param name The name we will give to associate it with other DynamicControls with identical ControlScope and type. * @param initial_value The initial value of the control * @param min_value The minimum display value of the control. Only used for display purposes * @param max_value The maximum display value of the control. Only used for display purposes * @param display_type The way we want the control displayed */ public DynamicControl(Object parent_sketch, ControlType control_type, String name, Object initial_value, Object min_value, Object max_value, DISPLAY_TYPE display_type) { this(parent_sketch, control_type, name, initial_value, display_type); minimumDisplayValue = convertValue (control_type, min_value); maximumDisplayValue = convertValue (control_type, max_value); synchronized (controlMapLock) { controlMap.addControl(this); } } /** * A dynamic control that can be accessed from outside * it is created with the sketch object that contains it along with the type * * @param control_type The type of control message you want to send * @param name The name we will give to associate it with other DynamicControls with identical ControlScope and type. * @param initial_value The initial value of the control * @param min_value The minimum display value of the control. Only used for display purposes * @param max_value The maximum display value of the control. Only used for display purposes */ public DynamicControl(ControlType control_type, String name, Object initial_value, Object min_value, Object max_value) { this(new Object(), control_type, name, initial_value, DISPLAY_TYPE.DISPLAY_DEFAULT); minimumDisplayValue = convertValue (control_type, min_value); maximumDisplayValue = convertValue (control_type, max_value); synchronized (controlMapLock) { controlMap.addControl(this); } } /** * Get the type of control we want * @return The type of value this control is */ public ControlType getControlType(){ return controlType; } /** * Get the scope of this control. Can be Sketch, Class, Device, or global * @return The Scope */ public ControlScope getControlScope(){ return controlScope; } /** * Changed the scope that the control has. It will update control map so the correct events will be generated based on its scope * @param new_scope The new Control Scope * @return this object */ public synchronized DynamicControl setControlScope(ControlScope new_scope) { ControlScope old_scope = controlScope; if (old_scope != new_scope) { controlScope = new_scope; notifyValueSetListeners(); // prevent control scope from changing the value //notifyLocalListeners(); notifyControlChangeListeners(); } return this; } /** * Get the Dynamic control based on Map key * * @param map_key the string that we are using as the key * @return the Object associated with this control */ public static DynamicControl getControl(String map_key) { DynamicControl ret = null; synchronized (controlMapLock) { ret = controlMap.getControl(map_key); } return ret; } /** * Update the parameters of this control with another. This would have been caused by an object having other than SKETCH control scope * If the parameters are changed, this object will notify it's listeners that a change has occurred * @param mirror_control The control that we are copying from * @return this object */ public DynamicControl updateControl(DynamicControl mirror_control){ if (mirror_control != null) { // first check our scope and type are the same boolean scope_matches = getControlScope() == mirror_control.getControlScope() && getControlType() == mirror_control.getControlType(); if (scope_matches) { // Now we need to check whether the scope matches us if (getControlScope() == ControlScope.SKETCH) { scope_matches = this.parentSketch == mirror_control.parentSketch && this.parentSketch != null; } // Now we need to check whether the scope matches us else if (getControlScope() == ControlScope.CLASS) { scope_matches = this.parentSketchName.equals(mirror_control.parentSketchName); } else if (getControlScope() == ControlScope.DEVICE){ scope_matches = this.deviceName.equals(mirror_control.deviceName); } else if (getControlScope() == ControlScope.TARGET){ // check if our mirror has this address scope_matches = mirror_control.targetsThisDevice(); } // Otherwise it must be global. We have a match } if (scope_matches) { // do not use setters as we only want to generate one notifyLocalListeners boolean changed = false; if (mirror_control.executionTime <= 0.0) { // his needs to be done now if (!objVal.equals(mirror_control.objVal)) { //objVal = mirror_control.objVal; // let this get done inside the scheduleValue return changed = true; } if (changed) { scheduleValue(null, mirror_control.objVal, 0); } } else { scheduleValue(null, mirror_control.objVal, mirror_control.executionTime); } } } return this; } /** * Check whether this device is targeted by checking the loopback, localhost and devicenames * @return */ private boolean targetsThisDevice() { boolean ret = false; String device_name = Device.getDeviceName(); String loopback = InetAddress.getLoopbackAddress().getHostAddress(); for (String device: targetDevices) { if (device_name.equalsIgnoreCase(device)){ return true; } if (device_name.equalsIgnoreCase(loopback)){ return true; } try { if (InetAddress.getLocalHost().getHostAddress().equalsIgnoreCase(device)){ return true; } } catch (UnknownHostException e) { //e.printStackTrace(); } } return ret; } /** * Schedule this control to change its value in context of scheduler * @param source_device the device name that was the source of this message - can be null * @param value the value to send * @param execution_time the time it needs to be executed * @param local_only if true, will not send value changed to notifyValueSetListeners */ void scheduleValue(String source_device, Object value, double execution_time, boolean local_only){ // We need to convert the Object value into the exact type. EG, integer must be cast to boolean if that is thr control type Object converted_value = convertValue(controlType, value); if (disableScheduler || execution_time == 0){ this.objVal = converted_value; this.executionTime = 0; this.sendingDevice = source_device; notifyLocalListeners(); if (!local_only) { notifyValueSetListeners(); } } else { FutureControlMessage message = new FutureControlMessage(source_device, converted_value, execution_time); message.localOnly = local_only; message.pendingSchedule = HBScheduler.getGlobalScheduler().addScheduledObject(execution_time, message, this); synchronized (futureMessageListLock) { futureMessageList.add(message); } } } /** * Schedule this control to send a value to it's locallisteners at a scheduled time. Will also notify valueListeners (eg GUI controls) * @param source_device the device name that was the source of this message - can be null * @param value the value to send * @param execution_time the time it needs to be executed */ void scheduleValue(String source_device, Object value, double execution_time) { scheduleValue(source_device, value, execution_time, false); } /** * Process the DynamicControl deviceName message and map device name to IPAddress * We ignore our own device * @param src_address The address of the device * @param msg The OSC Message that has device name */ public static void processDeviceNameMessage(InetAddress src_address, OSCMessage msg) { // do some error checking here if (src_address != null) { String device_name = (String) msg.getArg(DEVICE_NAME_ARGS.DEVICE_NAME.ordinal()); try { if (!Device.getDeviceName().equalsIgnoreCase(device_name)) { HB.HBInstance.addDeviceAddress(device_name, src_address); } } catch(Exception ex){} } } /** * Process the DynamicControl deviceRequest message * Send a deviceName back to src. Test that their name is mapped correctly * If name is not mapped we will request from all devices globally * @param src_address The address of the device * @param msg The OSC Message that has device name */ public static void processRequestNameMessage(InetAddress src_address, OSCMessage msg) { String device_name = (String) msg.getArg(DEVICE_NAME_ARGS.DEVICE_NAME.ordinal()); // ignore ourself if (!Device.getDeviceName().equalsIgnoreCase(device_name)) { // send them our message OSCMessage nameMessage = buildDeviceNameMessage(); ControlMap.getInstance().sendGlobalDynamicControlMessage(nameMessage, null); // See if we have them mapped the same boolean address_changed = HB.HBInstance.addDeviceAddress(device_name, src_address); if (address_changed){ // request all postRequestNamesMessage(); } } } /** * Post a request device name message to other devices so we can target them specifically and update our map */ public static void postRequestNamesMessage(){ OSCMessage requestMessage = buildDeviceRequestNameMessage(); ControlMap.getInstance().sendGlobalDynamicControlMessage(requestMessage, null); } /** * Build OSC Message that gives our device name * @return OSC Message that has name */ public static OSCMessage buildDeviceNameMessage(){ return new OSCMessage(OSCVocabulary.DynamicControlMessage.DEVICE_NAME, new Object[]{ Device.getDeviceName(), }); } /** * Build OSC Message that requests devices send us their name * @return OSC Message to request name */ public static OSCMessage buildDeviceRequestNameMessage(){ return new OSCMessage(OSCVocabulary.DynamicControlMessage.REQUEST_NAME, new Object[]{ Device.getDeviceName(), }); } /** * Convert two halves of a long stored integer values into a long value * @param msi most significant integer * @param lsi least significant integer * @return a long value consisting of the concatenation of both int values */ public static long integersToLong(int msi, int lsi){ return (long) msi << 32 | lsi & 0xFFFFFFFFL; } /** * Convert a long into two integers in an array of two integers * @param l_value the Long values that needs to be encoded * @return an array of two integers. ret[0] will be most significant integer while int [1] will be lease significant */ public static int [] longToIntegers (long l_value){ int msi = (int) (l_value >> 32); // this is most significant integer int lsi = (int) l_value; // This is LSB that has been trimmed down; return new int[]{msi, lsi}; } // We will create a single array that we can cache the size of an array of ints for scheduled time // This is used in numberIntsForScheduledTime private static int [] intArrayCache = null; /** * Return the array size of Integers that would be required to encode a scheduled time * @return the Array */ public static int numberIntsForScheduledTime(){ if (intArrayCache == null) { intArrayCache = scheduleTimeToIntegers(0); } return intArrayCache.length; } /** * Convert a SchedulerTime into integers in an array of three integers * @param d_val the double values that needs to be encoded * @return an array of three integers. ret[0] will be most significant integer while int [1] will be lease significant. int [2] is the number of nano seconds */ public static int [] scheduleTimeToIntegers (double d_val){ long lval = (long)d_val; int msi = (int) (lval >> 32); // this is most significant integer int lsi = (int) lval; // This is LSB that has been trimmed down; double nano = d_val - lval; nano *= 1000000; int n = (int) nano; return new int[]{msi, lsi, n}; } /** * Convert three integers to a double representing scheduler time * @param msi the most significant value of millisecond value * @param lsi the least significant value of millisecond value * @param nano the number of nanoseconds * @return a double representing the scheduler time */ public static double integersToScheduleTime(int msi, int lsi, int nano){ long milliseconds = integersToLong(msi, lsi); double ret = milliseconds; double nanoseconds = nano; return ret + nanoseconds / 1000000d; } /** * Process the {@link ControlScope#GLOBAL} or {@link ControlScope#TARGET} Message from an OSC Message. Examine buildUpdateMessage for parameters inside Message * We will not process messages that have come from this device because they will be actioned through local listeners * @param msg OSC message with new value * @param controlScope the type of {@link ControlScope}; */ public static void processOSCControlMessage(OSCMessage msg, ControlScope controlScope) { String device_name = (String) msg.getArg(NETWORK_TRANSMIT_MESSAGE_ARGS.DEVICE_NAME.ordinal()); int message_id = (int)msg.getArg(NETWORK_TRANSMIT_MESSAGE_ARGS.MESSAGE_ID.ordinal()); // Make sure we ignore messages from this device if (ignoreName || !device_name.equals(Device.getDeviceName())) { if (enableProcessControlMessage(device_name, message_id)) { String control_name = (String) msg.getArg(NETWORK_TRANSMIT_MESSAGE_ARGS.CONTROL_NAME.ordinal()); ControlType control_type = ControlType.values()[(int) msg.getArg(NETWORK_TRANSMIT_MESSAGE_ARGS.CONTROL_TYPE.ordinal())]; Object obj_val = msg.getArg(NETWORK_TRANSMIT_MESSAGE_ARGS.OBJ_VAL.ordinal()); Object ms_max = msg.getArg(NETWORK_TRANSMIT_MESSAGE_ARGS.EXECUTE_TIME_MLILI_MS.ordinal()); Object ms_min = msg.getArg(NETWORK_TRANSMIT_MESSAGE_ARGS.EXECUTE_TIME_MLILI_LS.ordinal()); Object nano = msg.getArg(NETWORK_TRANSMIT_MESSAGE_ARGS.EXECUTE_TIME_NANO.ordinal()); double execution_time = integersToScheduleTime((int) ms_max, (int) ms_min, (int) nano); boolean data_converted = false; // we only want to do data conversion once synchronized (controlMapLock) { List<DynamicControl> named_controls = controlMap.getControlsByName(control_name); for (DynamicControl named_control : named_controls) { if (named_control.controlScope == controlScope && control_type.equals(named_control.controlType)) { // we must NOT call setVal as this will generate a global series again. // Just notifyListeners specific to this control but not globally if (!data_converted) { // we need to see if this is a boolean Object as OSC does not support that if (control_type == ControlType.BOOLEAN) { int osc_val = (int) obj_val; Boolean bool_val = osc_val != 0; obj_val = bool_val; data_converted = true; } else if (control_type == ControlType.OBJECT) { if (!(obj_val instanceof String)) { // This is not a Json Message // We will need to get all the remaining OSC arguments after the schedule time and store that as ObjVal int num_args = msg.getArgCount() - OSC_TRANSMIT_ARRAY_ARG; Object[] restore_args = new Object[num_args]; for (int i = 0; i < num_args; i++) { restore_args[i] = msg.getArg(OSC_TRANSMIT_ARRAY_ARG + i); } obj_val = restore_args; data_converted = true; } } } // We need to schedule this value named_control.scheduleValue(device_name, obj_val, execution_time); } } } } } } /** * Process the Update Message from an OSC Message. Examine buildUpdateMessage for parameters inside Message * The message is directed as a specific control defined by the MAP_KEY parameter in the OSC Message * @param msg OSC message with new value */ public static void processUpdateMessage(OSCMessage msg){ String map_key = (String) msg.getArg(UPDATE_MESSAGE_ARGS.MAP_KEY.ordinal()); String control_name = (String) msg.getArg(UPDATE_MESSAGE_ARGS.CONTROL_NAME.ordinal()); Object obj_val = msg.getArg(UPDATE_MESSAGE_ARGS.OBJ_VAL.ordinal()); ControlScope control_scope = ControlScope.values ()[(int) msg.getArg(UPDATE_MESSAGE_ARGS.CONTROL_SCOPE.ordinal())]; DISPLAY_TYPE display_type = DISPLAY_TYPE.DISPLAY_DEFAULT; DynamicControl control = getControl(map_key); if (control != null) { Object display_min = control.getMinimumDisplayValue(); Object display_max = control.getMaximumDisplayValue(); if (msg.getArgCount() > UPDATE_MESSAGE_ARGS.DISPLAY_TYPE_VAL.ordinal()) { int osc_val = (int) msg.getArg(UPDATE_MESSAGE_ARGS.DISPLAY_TYPE_VAL.ordinal()); display_type = DISPLAY_TYPE.values ()[osc_val]; } if (msg.getArgCount() > UPDATE_MESSAGE_ARGS.MAX_VALUE.ordinal()){ display_max = msg.getArg(UPDATE_MESSAGE_ARGS.MAX_VALUE.ordinal()); } if (msg.getArgCount() > UPDATE_MESSAGE_ARGS.MIN_VALUE.ordinal()){ display_min = msg.getArg(UPDATE_MESSAGE_ARGS.MIN_VALUE.ordinal()); } // do not use setters as we only want to generate one notifyLocalListeners boolean changed = false; boolean control_scope_changed = false; if (control.displayType != display_type) { changed = true; } control.displayType = display_type; obj_val = convertValue(control.controlType, obj_val); display_max = convertValue(control.controlType, display_max); display_min = convertValue(control.controlType, display_min); if (!obj_val.equals(control.objVal) || !display_max.equals(control.maximumDisplayValue) || !display_min.equals(control.minimumDisplayValue) ) { changed = true; } if (!control_scope.equals(control.controlScope)) { control.controlScope = control_scope; //control.executionTime = execution_time; changed = true; control_scope_changed = true; } if (changed) { control.maximumDisplayValue = display_max; control.minimumDisplayValue = display_min; control.scheduleValue(null, obj_val, 0, true); if (control.getControlScope() != ControlScope.UNIQUE){ control.objVal = obj_val; control.notifyGlobalListeners(); } } if (control_scope_changed) { control.notifyControlChangeListeners(); } } } /** * Build OSC Message that specifies a removal of a control * @return OSC Message to notify removal */ public OSCMessage buildRemoveMessage(){ return new OSCMessage(OSCVocabulary.DynamicControlMessage.DESTROY, new Object[]{ deviceName, controlMapKey }); } /** * Return an object that can be sent by OSC based on control TYpe * @param obj_val The object value we want to send * @return the type we will actually send */ private Object OSCArgumentObject (Object obj_val){ Object ret = obj_val; if (obj_val instanceof Boolean) { boolean b = (Boolean) obj_val; return b? 1:0; } else if (obj_val instanceof Double){ String s = ((Double)obj_val).toString(); ret = s; } return ret; } /** * Build OSC Message that specifies an update * @return OSC Message To send to specific control */ public OSCMessage buildUpdateMessage(){ Object sendObjType = objVal; if (controlType == ControlType.OBJECT){ sendObjType = objVal.toString(); } return new OSCMessage(OSCVocabulary.DynamicControlMessage.UPDATE, new Object[]{ deviceName, controlName, controlType.ordinal(), controlMapKey, OSCArgumentObject(sendObjType), controlScope.ordinal(), displayType.ordinal(), OSCArgumentObject(minimumDisplayValue), OSCArgumentObject(maximumDisplayValue), }); } /** * Build OSC Message that specifies a Network update * @return OSC Message directed to controls with same name, scope, but on different devices */ public OSCMessage buildNetworkSendMessage(){ deviceSendId++; String OSC_MessageName = OSCVocabulary.DynamicControlMessage.GLOBAL; // define the arguments for send time int [] execution_args = scheduleTimeToIntegers(executionTime); if (controlScope == ControlScope.TARGET){ OSC_MessageName = OSCVocabulary.DynamicControlMessage.TARGET; } if (controlType == ControlType.OBJECT){ /* DEVICE_NAME, CONTROL_NAME, CONTROL_TYPE, OBJ_VAL, EXECUTE_TIME_MLILI_MS, // Most Significant Int of Milliseconds - stored as int EXECUTE_TIME_MLILI_LS, // Least Significant Bit of Milliseconds - stored as int EXECUTE_TIME_NANO // Number on Nano Seconds - stored as int */ // we need to see if we have a custom encode function if (objVal instanceof CustomGlobalEncoder){ Object [] encode_data = ((CustomGlobalEncoder)objVal).encodeGlobalMessage(); int num_args = OSC_TRANSMIT_ARRAY_ARG + encode_data.length; Object [] osc_args = new Object[num_args]; osc_args[0] = deviceName; osc_args[1] = controlName; osc_args[2] = controlType.ordinal(); osc_args[3] = 0; // by defining zero we are going to say this is NOT json osc_args[4] = execution_args [0]; osc_args[5] = execution_args [1]; osc_args[6] = execution_args [2]; osc_args[7] = deviceSendId; // now encode the object parameters for (int i = 0; i < encode_data.length; i++){ osc_args[OSC_TRANSMIT_ARRAY_ARG + i] = encode_data[i]; } return new OSCMessage(OSC_MessageName, osc_args); } else { String jsonString = gson.toJson(objVal); return new OSCMessage(OSC_MessageName, new Object[]{ deviceName, controlName, controlType.ordinal(), jsonString, execution_args[0], execution_args[1], execution_args[2], deviceSendId }); } } else { return new OSCMessage(OSC_MessageName, new Object[]{ deviceName, controlName, controlType.ordinal(), OSCArgumentObject(objVal), execution_args[0], execution_args[1], execution_args[2], deviceSendId }); } } /** * Build the OSC Message for a create message * @return OSC Message required to create the object */ public OSCMessage buildCreateMessage() { Object sendObjType = objVal; if (controlType == ControlType.OBJECT){ sendObjType = objVal.toString(); } return new OSCMessage(OSCVocabulary.DynamicControlMessage.CREATE, new Object[]{ deviceName, controlMapKey, controlName, parentSketchName, parentId, controlType.ordinal(), OSCArgumentObject(sendObjType), OSCArgumentObject(minimumDisplayValue), OSCArgumentObject(maximumDisplayValue), controlScope.ordinal(), displayType.ordinal() }); } /** * Create a DynamicControl based on OSC Message. This will keep OSC implementation inside this class * The buildUpdateMessage shows how messages are constructed * @param msg the OSC Message with the parameters to make Control */ public DynamicControl (OSCMessage msg) { deviceName = (String) msg.getArg(CREATE_MESSAGE_ARGS.DEVICE_NAME.ordinal()); controlMapKey = (String) msg.getArg(CREATE_MESSAGE_ARGS.MAP_KEY.ordinal()); controlName = (String) msg.getArg(CREATE_MESSAGE_ARGS.CONTROL_NAME.ordinal()); parentSketchName = (String) msg.getArg(CREATE_MESSAGE_ARGS.PARENT_SKETCH_NAME.ordinal()); parentId = (int) msg.getArg(CREATE_MESSAGE_ARGS.PARENT_SKETCH_ID.ordinal()); controlType = ControlType.values ()[(int) msg.getArg(CREATE_MESSAGE_ARGS.CONTROL_TYPE.ordinal())]; objVal = convertValue (controlType, msg.getArg(CREATE_MESSAGE_ARGS.OBJ_VAL.ordinal())); minimumDisplayValue = convertValue (controlType, msg.getArg(CREATE_MESSAGE_ARGS.MIN_VAL.ordinal())); maximumDisplayValue = convertValue (controlType, msg.getArg(CREATE_MESSAGE_ARGS.MAX_VAL.ordinal())); controlScope = ControlScope.values ()[(int) msg.getArg(CREATE_MESSAGE_ARGS.CONTROL_SCOPE.ordinal())]; if (msg.getArgCount() > CREATE_MESSAGE_ARGS.DISPLAY_TYPE_VAL.ordinal()) { int osc_val = (int) msg.getArg(CREATE_MESSAGE_ARGS.DISPLAY_TYPE_VAL.ordinal()); displayType = DISPLAY_TYPE.values ()[osc_val]; } synchronized (controlMapLock) { controlMap.addControl(this); } } /** * Get the map key created in the device as a method for mapping back * @return The unique key to identify this object */ public String getControlMapKey(){ return controlMapKey; } /** * Set the value of the object and notify any listeners * Additionally, the value will propagate to any controls that match the control scope * If we are using a trigger, send a random number or a unique value * @param val the value to set * @return this object */ public DynamicControl setValue(Object val) { return setValue(val, 0); } /** * Set the value of the object and notify any listeners * Additionally, the value will propagate to any controls that match the control scope * If we are using a trigger, send a random number or a unique value * @param val the value to set * @param execution_time the Scheduler time we want this to occur * @return this object */ public DynamicControl setValue(Object val, double execution_time) { executionTime = execution_time; val = convertValue (controlType, val); if (!objVal.equals(val)) { if (controlType == ControlType.FLOAT) { objVal = (Double) val; } else { objVal = val; } notifyGlobalListeners(); scheduleValue(null, val, execution_time); } return this; } /** * Gets the value of the control. The type needs to be cast to the required type in the listener * @return Control Value */ public Object getValue(){ return objVal; } /** * The maximum value that we want as a display, for example, in a slider control. Does not limit values in the messages * @return The maximum value we want a graphical display to be set to */ public Object getMaximumDisplayValue(){ return maximumDisplayValue; } /** * Set the minimum display range for display * @param min minimum display value * * @return this */ public DynamicControl setMinimumValue(Object min) {minimumDisplayValue = min; return this;} /** * Set the maximum display range for display * @param max maximum display value * @return this */ public DynamicControl setMaximumDisplayValue(Object max) {maximumDisplayValue = max; return this;} /** * The minimum value that we want as a display, for example, in a slider control. Does not limit values in the messages * @return The minimum value we want a graphical display to be set to */ public Object getMinimumDisplayValue(){ return minimumDisplayValue; } /** * Get the name of the control used for ControlScope matching. Also displayed in GUI * @return The name of the control for scope matching */ public String getControlName(){ return controlName; } /** * Register Listener to receive changed values in the control * @param listener Listener to register for events * @return this */ public DynamicControl addControlListener(DynamicControlListener listener) { if (listener != null) { synchronized (controlListenerLock) { controlListenerList.add(listener); } } return this; } /** * Register Listener to receive changed values in the control that need to be global type messages * @param listener Listener to register for events * @return this listener that has been created */ public DynamicControl addGlobalControlListener(DynamicControlListener listener) { if (listener != null) { synchronized (globalListenerLock) { globalControlListenerList.add(listener); } } return this; } /** * Register Listener to receive changed values in the control that need to be received when value is specifically set from * Within sketch * @param listener Listener to register for events * @return this */ public DynamicControl addValueSetListener(DynamicControlListener listener) { if (listener != null) { synchronized (valueSetListenerLock) { valueSetListenerList.add(listener); } } return this; } /** * Deregister listener so it no longer receives messages from this control * @param listener The lsitener we are removing * @return this object */ public DynamicControl removeControlListener(DynamicControlListener listener) { if (listener != null) { synchronized (controlListenerLock) { controlListenerList.remove(listener); } } return this; } /** * Deregister listener so it no longer receives messages from this control * @param listener the listener we are remmoving * @return this object */ public DynamicControl removeGlobalControlListener(DynamicControlListener listener) { if (listener != null) { synchronized (globalListenerLock) { globalControlListenerList.remove(listener); } } return this; } /** * Register Listener to receive changed values in the control scope * @param listener Listener to register for events * @return this object */ public DynamicControl addControlScopeListener(ControlScopeChangedListener listener){ if (listener != null) { synchronized (controlScopeChangedLock) { controlScopeChangedList.add(listener); } } return this; } /** * Deregister listener so it no longer receives messages from this control * @param listener the listener * @return this object */ public DynamicControl removeControlScopeChangedListener(ControlScopeChangedListener listener) { if (listener != null) { synchronized (controlScopeChangedLock) { controlScopeChangedList.remove(listener); } } return this; } /** * Erase all listeners from this control * @return this object */ public DynamicControl eraseListeners() { // We need to synchronized (futureMessageListLock){ for (FutureControlMessage message: futureMessageList) { message.pendingSchedule.setCancelled(true); } futureMessageList.clear(); } synchronized (controlListenerLock) {controlListenerList.clear();} synchronized (controlScopeChangedLock) {controlScopeChangedList.clear();} return this; } /** * Notify all registered listeners of object value on this device * @return this object */ public DynamicControl notifyLocalListeners() { synchronized (controlListenerLock) { controlListenerList.forEach(listener -> { try { listener.update(this); } catch (Exception ex) { ex.printStackTrace(); } }); } return this; } /** * Send Update Message when value set */ public void notifyValueSetListeners(){ synchronized (valueSetListenerLock) { valueSetListenerList.forEach(listener -> { try { listener.update(this); } catch (Exception ex) { ex.printStackTrace(); } }); } } /** * Send Global Update Message */ public void notifyGlobalListeners(){ synchronized (globalListenerLock) { globalControlListenerList.forEach(listener -> { try { listener.update(this); } catch (Exception ex) { ex.printStackTrace(); } }); } } /** * Notify all registered listeners of object value * @return this object */ public DynamicControl notifyControlChangeListeners() { synchronized (controlScopeChangedLock) { controlScopeChangedList.forEach(listener -> { try { listener.controlScopeChanged(this.getControlScope()); } catch (Exception ex) { ex.printStackTrace(); } }); } return this; } /** * Get the tooltip to display * @return the tooltip to display */ public String getTooltipText(){ String control_scope_text = ""; if (getControlScope() == ControlScope.UNIQUE) { control_scope_text = "UNIQUE scope"; } else if (getControlScope() == ControlScope.SKETCH) { control_scope_text = "SKETCH scope"; } else if (getControlScope() == ControlScope.CLASS) { control_scope_text = "CLASS scope - " + parentSketchName; } else if (getControlScope() == ControlScope.DEVICE) { control_scope_text = "DEVICE scope - " + deviceName; } else if (getControlScope() == ControlScope.GLOBAL) { control_scope_text = "GLOBAL scope"; } return tooltipPrefix + "\n" + control_scope_text; } }
Java
# Moritzia dasyantha Fresen. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
// Copyright 2020 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // #ifndef IREE_COMPILER_DIALECT_HAL_TARGET_LLVM_LLVMAOTTARGET_H_ #define IREE_COMPILER_DIALECT_HAL_TARGET_LLVM_LLVMAOTTARGET_H_ #include "iree/compiler/Dialect/HAL/Target/LLVM/LLVMTargetOptions.h" namespace mlir { namespace iree_compiler { namespace IREE { namespace HAL { // Registers the LLVM Ahead-Of-Time (AOT) target backends. void registerLLVMAOTTargetBackends( std::function<LLVMTargetOptions()> queryOptions); } // namespace HAL } // namespace IREE } // namespace iree_compiler } // namespace mlir #endif // IREE_COMPILER_DIALECT_HAL_TARGET_LLVM_LLVMAOTTARGET_H_
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_27) on Wed Nov 06 17:51:16 PST 2013 --> <TITLE> QuantileUtil (DataFu 1.1.0) </TITLE> <META NAME="date" CONTENT="2013-11-06"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="QuantileUtil (DataFu 1.1.0)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/QuantileUtil.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../datafu/pig/stats/Quantile.html" title="class in datafu.pig.stats"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../datafu/pig/stats/StreamingMedian.html" title="class in datafu.pig.stats"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?datafu/pig/stats/QuantileUtil.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="QuantileUtil.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> datafu.pig.stats</FONT> <BR> Class QuantileUtil</H2> <PRE> java.lang.Object <IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>datafu.pig.stats.QuantileUtil</B> </PRE> <HR> <DL> <DT><PRE>public class <B>QuantileUtil</B><DT>extends java.lang.Object</DL> </PRE> <P> Methods used by <A HREF="../../../datafu/pig/stats/Quantile.html" title="class in datafu.pig.stats"><CODE>Quantile</CODE></A>. <P> <P> <DL> <DT><B>Author:</B></DT> <DD>"Matthew Hayes <mhayes@linkedin.com>"</DD> </DL> <HR> <P> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../datafu/pig/stats/QuantileUtil.html#QuantileUtil()">QuantileUtil</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.util.ArrayList&lt;java.lang.Double&gt;</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../datafu/pig/stats/QuantileUtil.html#getNQuantiles(int)">getNQuantiles</A></B>(int&nbsp;numQuantiles)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.util.ArrayList&lt;java.lang.Double&gt;</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../datafu/pig/stats/QuantileUtil.html#getQuantilesFromParams(java.lang.String...)">getQuantilesFromParams</A></B>(java.lang.String...&nbsp;k)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="QuantileUtil()"><!-- --></A><H3> QuantileUtil</H3> <PRE> public <B>QuantileUtil</B>()</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="getNQuantiles(int)"><!-- --></A><H3> getNQuantiles</H3> <PRE> public static java.util.ArrayList&lt;java.lang.Double&gt; <B>getNQuantiles</B>(int&nbsp;numQuantiles)</PRE> <DL> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="getQuantilesFromParams(java.lang.String...)"><!-- --></A><H3> getQuantilesFromParams</H3> <PRE> public static java.util.ArrayList&lt;java.lang.Double&gt; <B>getQuantilesFromParams</B>(java.lang.String...&nbsp;k)</PRE> <DL> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/QuantileUtil.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../datafu/pig/stats/Quantile.html" title="class in datafu.pig.stats"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../datafu/pig/stats/StreamingMedian.html" title="class in datafu.pig.stats"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?datafu/pig/stats/QuantileUtil.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="QuantileUtil.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Matthew Hayes, Sam Shah </BODY> </HTML>
Java
# AUTOGENERATED FILE FROM balenalib/artik520-fedora:34-run ENV NODE_VERSION 16.14.0 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && echo "2df94404f4dd22aee67370cd24b2c802f82409434e5ed26061c7aaec74a8ebc2 node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \ && echo "Running test-stack@node" \ && chmod +x test-stack@node.sh \ && bash test-stack@node.sh \ && rm -rf test-stack@node.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Fedora 34 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v16.14.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (version 1.7.0_17) on Tue May 14 03:45:01 CEST 2013 --> <title>AtlasTmxMapLoader (libgdx API)</title> <meta name="date" content="2013-05-14"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="AtlasTmxMapLoader (libgdx API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/AtlasTmxMapLoader.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> libgdx API <style> body, td, th { font-family:Helvetica, Tahoma, Arial, sans-serif; font-size:10pt } pre, code, tt { font-size:9pt; font-family:Lucida Console, Courier New, sans-serif } h1, h2, h3, .FrameTitleFont, .FrameHeadingFont, .TableHeadingColor font { font-size:105%; font-weight:bold } .TableHeadingColor { background:#EEEEFF; } a { text-decoration:none } a:hover { text-decoration:underline } a:link, a:visited { color:blue } table { border:0px } .TableRowColor td:first-child { border-left:1px solid black } .TableRowColor td { border:0px; border-bottom:1px solid black; border-right:1px solid black } hr { border:0px; border-bottom:1px solid #333366; } </style> </em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev Class</li> <li><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html" target="_top">Frames</a></li> <li><a href="AtlasTmxMapLoader.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_class_summary">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.badlogic.gdx.maps.tiled</div> <h2 title="Class AtlasTmxMapLoader" class="title">Class AtlasTmxMapLoader</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../../../../com/badlogic/gdx/assets/loaders/AssetLoader.html" title="class in com.badlogic.gdx.assets.loaders">com.badlogic.gdx.assets.loaders.AssetLoader</a>&lt;T,P&gt;</li> <li> <ul class="inheritance"> <li><a href="../../../../../com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.html" title="class in com.badlogic.gdx.assets.loaders">com.badlogic.gdx.assets.loaders.AsynchronousAssetLoader</a>&lt;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>,<a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&gt;</li> <li> <ul class="inheritance"> <li>com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader</li> </ul> </li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="strong">AtlasTmxMapLoader</span> extends <a href="../../../../../com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.html" title="class in com.badlogic.gdx.assets.loaders">AsynchronousAssetLoader</a>&lt;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>,<a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&gt;</pre> <div class="block">A TiledMap Loader which loads tiles from a TextureAtlas instead of separate images. It requires a map-level property called 'atlas' with its value being the relative path to the TextureAtlas. The atlas must have in it indexed regions named after the tilesets used in the map. The indexes shall be local to the tileset (not the global id). Strip whitespace and rotation should not be used when creating the atlas.</div> <dl><dt><span class="strong">Author:</span></dt> <dd>Justin Shapcott, Manuel Bua</dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested_class_summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation"> <caption><span>Nested Classes</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a></strong></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>protected static int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#FLAG_FLIP_DIAGONALLY">FLAG_FLIP_DIAGONALLY</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected static int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#FLAG_FLIP_HORIZONTALLY">FLAG_FLIP_HORIZONTALLY</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected static int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#FLAG_FLIP_VERTICALLY">FLAG_FLIP_VERTICALLY</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected <a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#map">map</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#mapHeightInPixels">mapHeightInPixels</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#mapWidthInPixels">mapWidthInPixels</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected static int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#MASK_CLEAR">MASK_CLEAR</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#root">root</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../com/badlogic/gdx/utils/Array.html" title="class in com.badlogic.gdx.utils">Array</a>&lt;<a href="../../../../../com/badlogic/gdx/graphics/Texture.html" title="class in com.badlogic.gdx.graphics">Texture</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#trackedTextures">trackedTextures</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected <a href="../../../../../com/badlogic/gdx/utils/XmlReader.html" title="class in com.badlogic.gdx.utils">XmlReader</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#xml">xml</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected boolean</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#yUp">yUp</a></strong></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#AtlasTmxMapLoader()">AtlasTmxMapLoader</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#AtlasTmxMapLoader(com.badlogic.gdx.assets.loaders.FileHandleResolver)">AtlasTmxMapLoader</a></strong>(<a href="../../../../../com/badlogic/gdx/assets/loaders/FileHandleResolver.html" title="interface in com.badlogic.gdx.assets.loaders">FileHandleResolver</a>&nbsp;resolver)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMapTileLayer.Cell.html" title="class in com.badlogic.gdx.maps.tiled">TiledMapTileLayer.Cell</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#createTileLayerCell(boolean, boolean, boolean)">createTileLayerCell</a></strong>(boolean&nbsp;flipHorizontally, boolean&nbsp;flipVertically, boolean&nbsp;flipDiagonally)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/badlogic/gdx/utils/Array.html" title="class in com.badlogic.gdx.utils">Array</a>&lt;<a href="../../../../../com/badlogic/gdx/assets/AssetDescriptor.html" title="class in com.badlogic.gdx.assets">AssetDescriptor</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#getDependencies(java.lang.String, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)">getDependencies</a></strong>(java.lang.String&nbsp;fileName, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#getRelativeFileHandle(com.badlogic.gdx.files.FileHandle, java.lang.String)">getRelativeFileHandle</a></strong>(<a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;file, java.lang.String&nbsp;path)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#load(java.lang.String)">load</a></strong>(java.lang.String&nbsp;fileName)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#load(java.lang.String, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)">load</a></strong>(java.lang.String&nbsp;fileName, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadAsync(com.badlogic.gdx.assets.AssetManager, java.lang.String, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)">loadAsync</a></strong>(<a href="../../../../../com/badlogic/gdx/assets/AssetManager.html" title="class in com.badlogic.gdx.assets">AssetManager</a>&nbsp;manager, java.lang.String&nbsp;fileName, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</code> <div class="block">Loads the non-OpenGL part of the asset and injects any dependencies of the asset into the AssetManager.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadAtlas(com.badlogic.gdx.utils.XmlReader.Element, com.badlogic.gdx.files.FileHandle)">loadAtlas</a></strong>(<a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;root, <a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;tmxFile)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected <a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadMap(com.badlogic.gdx.utils.XmlReader.Element, com.badlogic.gdx.files.FileHandle, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasResolver, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)">loadMap</a></strong>(<a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;root, <a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;tmxFile, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasResolver&nbsp;resolver, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadObject(com.badlogic.gdx.maps.MapLayer, com.badlogic.gdx.utils.XmlReader.Element)">loadObject</a></strong>(<a href="../../../../../com/badlogic/gdx/maps/MapLayer.html" title="class in com.badlogic.gdx.maps">MapLayer</a>&nbsp;layer, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadObjectGroup(com.badlogic.gdx.maps.tiled.TiledMap, com.badlogic.gdx.utils.XmlReader.Element)">loadObjectGroup</a></strong>(<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;map, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadProperties(com.badlogic.gdx.maps.MapProperties, com.badlogic.gdx.utils.XmlReader.Element)">loadProperties</a></strong>(<a href="../../../../../com/badlogic/gdx/maps/MapProperties.html" title="class in com.badlogic.gdx.maps">MapProperties</a>&nbsp;properties, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadSync(com.badlogic.gdx.assets.AssetManager, java.lang.String, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)">loadSync</a></strong>(<a href="../../../../../com/badlogic/gdx/assets/AssetManager.html" title="class in com.badlogic.gdx.assets">AssetManager</a>&nbsp;manager, java.lang.String&nbsp;fileName, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</code> <div class="block">Loads th</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadTileLayer(com.badlogic.gdx.maps.tiled.TiledMap, com.badlogic.gdx.utils.XmlReader.Element)">loadTileLayer</a></strong>(<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;map, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadTileset(com.badlogic.gdx.maps.tiled.TiledMap, com.badlogic.gdx.utils.XmlReader.Element, com.badlogic.gdx.files.FileHandle, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasResolver, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)">loadTileset</a></strong>(<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;map, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element, <a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;tmxFile, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasResolver&nbsp;resolver, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected static int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#unsignedByteToInt(byte)">unsignedByteToInt</a></strong>(byte&nbsp;b)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_com.badlogic.gdx.assets.loaders.AssetLoader"> <!-- --> </a> <h3>Methods inherited from class&nbsp;com.badlogic.gdx.assets.loaders.<a href="../../../../../com/badlogic/gdx/assets/loaders/AssetLoader.html" title="class in com.badlogic.gdx.assets.loaders">AssetLoader</a></h3> <code><a href="../../../../../com/badlogic/gdx/assets/loaders/AssetLoader.html#resolve(java.lang.String)">resolve</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field_detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="FLAG_FLIP_HORIZONTALLY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>FLAG_FLIP_HORIZONTALLY</h4> <pre>protected static final&nbsp;int FLAG_FLIP_HORIZONTALLY</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.FLAG_FLIP_HORIZONTALLY">Constant Field Values</a></dd></dl> </li> </ul> <a name="FLAG_FLIP_VERTICALLY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>FLAG_FLIP_VERTICALLY</h4> <pre>protected static final&nbsp;int FLAG_FLIP_VERTICALLY</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.FLAG_FLIP_VERTICALLY">Constant Field Values</a></dd></dl> </li> </ul> <a name="FLAG_FLIP_DIAGONALLY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>FLAG_FLIP_DIAGONALLY</h4> <pre>protected static final&nbsp;int FLAG_FLIP_DIAGONALLY</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.FLAG_FLIP_DIAGONALLY">Constant Field Values</a></dd></dl> </li> </ul> <a name="MASK_CLEAR"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>MASK_CLEAR</h4> <pre>protected static final&nbsp;int MASK_CLEAR</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.MASK_CLEAR">Constant Field Values</a></dd></dl> </li> </ul> <a name="xml"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>xml</h4> <pre>protected&nbsp;<a href="../../../../../com/badlogic/gdx/utils/XmlReader.html" title="class in com.badlogic.gdx.utils">XmlReader</a> xml</pre> </li> </ul> <a name="root"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>root</h4> <pre>protected&nbsp;<a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a> root</pre> </li> </ul> <a name="yUp"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>yUp</h4> <pre>protected&nbsp;boolean yUp</pre> </li> </ul> <a name="mapWidthInPixels"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>mapWidthInPixels</h4> <pre>protected&nbsp;int mapWidthInPixels</pre> </li> </ul> <a name="mapHeightInPixels"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>mapHeightInPixels</h4> <pre>protected&nbsp;int mapHeightInPixels</pre> </li> </ul> <a name="map"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>map</h4> <pre>protected&nbsp;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a> map</pre> </li> </ul> <a name="trackedTextures"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>trackedTextures</h4> <pre>protected&nbsp;<a href="../../../../../com/badlogic/gdx/utils/Array.html" title="class in com.badlogic.gdx.utils">Array</a>&lt;<a href="../../../../../com/badlogic/gdx/graphics/Texture.html" title="class in com.badlogic.gdx.graphics">Texture</a>&gt; trackedTextures</pre> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="AtlasTmxMapLoader()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>AtlasTmxMapLoader</h4> <pre>public&nbsp;AtlasTmxMapLoader()</pre> </li> </ul> <a name="AtlasTmxMapLoader(com.badlogic.gdx.assets.loaders.FileHandleResolver)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>AtlasTmxMapLoader</h4> <pre>public&nbsp;AtlasTmxMapLoader(<a href="../../../../../com/badlogic/gdx/assets/loaders/FileHandleResolver.html" title="interface in com.badlogic.gdx.assets.loaders">FileHandleResolver</a>&nbsp;resolver)</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="load(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>load</h4> <pre>public&nbsp;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;load(java.lang.String&nbsp;fileName)</pre> </li> </ul> <a name="getDependencies(java.lang.String, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getDependencies</h4> <pre>public&nbsp;<a href="../../../../../com/badlogic/gdx/utils/Array.html" title="class in com.badlogic.gdx.utils">Array</a>&lt;<a href="../../../../../com/badlogic/gdx/assets/AssetDescriptor.html" title="class in com.badlogic.gdx.assets">AssetDescriptor</a>&gt;&nbsp;getDependencies(java.lang.String&nbsp;fileName, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../com/badlogic/gdx/assets/loaders/AssetLoader.html#getDependencies(java.lang.String, P)">getDependencies</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../com/badlogic/gdx/assets/loaders/AssetLoader.html" title="class in com.badlogic.gdx.assets.loaders">AssetLoader</a>&lt;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>,<a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&gt;</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>fileName</code> - name of the asset to load</dd><dd><code>parameter</code> - parameters for loading the asset</dd> <dt><span class="strong">Returns:</span></dt><dd>other assets that the asset depends on and need to be loaded first or null if there are no dependencies.</dd></dl> </li> </ul> <a name="load(java.lang.String, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>load</h4> <pre>public&nbsp;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;load(java.lang.String&nbsp;fileName, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</pre> </li> </ul> <a name="loadAtlas(com.badlogic.gdx.utils.XmlReader.Element, com.badlogic.gdx.files.FileHandle)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadAtlas</h4> <pre>protected&nbsp;<a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;loadAtlas(<a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;root, <a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;tmxFile) throws java.io.IOException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>java.io.IOException</code></dd></dl> </li> </ul> <a name="loadAsync(com.badlogic.gdx.assets.AssetManager, java.lang.String, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadAsync</h4> <pre>public&nbsp;void&nbsp;loadAsync(<a href="../../../../../com/badlogic/gdx/assets/AssetManager.html" title="class in com.badlogic.gdx.assets">AssetManager</a>&nbsp;manager, java.lang.String&nbsp;fileName, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../../com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.html#loadAsync(com.badlogic.gdx.assets.AssetManager, java.lang.String, P)">AsynchronousAssetLoader</a></code></strong></div> <div class="block">Loads the non-OpenGL part of the asset and injects any dependencies of the asset into the AssetManager.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.html#loadAsync(com.badlogic.gdx.assets.AssetManager, java.lang.String, P)">loadAsync</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.html" title="class in com.badlogic.gdx.assets.loaders">AsynchronousAssetLoader</a>&lt;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>,<a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&gt;</code></dd> <dd><code>fileName</code> - the name of the asset to load</dd><dd><code>parameter</code> - the parameters to use for loading the asset</dd></dl> </li> </ul> <a name="loadSync(com.badlogic.gdx.assets.AssetManager, java.lang.String, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadSync</h4> <pre>public&nbsp;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;loadSync(<a href="../../../../../com/badlogic/gdx/assets/AssetManager.html" title="class in com.badlogic.gdx.assets">AssetManager</a>&nbsp;manager, java.lang.String&nbsp;fileName, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../../com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.html#loadSync(com.badlogic.gdx.assets.AssetManager, java.lang.String, P)">AsynchronousAssetLoader</a></code></strong></div> <div class="block">Loads th</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.html#loadSync(com.badlogic.gdx.assets.AssetManager, java.lang.String, P)">loadSync</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.html" title="class in com.badlogic.gdx.assets.loaders">AsynchronousAssetLoader</a>&lt;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>,<a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&gt;</code></dd> </dl> </li> </ul> <a name="loadMap(com.badlogic.gdx.utils.XmlReader.Element, com.badlogic.gdx.files.FileHandle, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasResolver, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadMap</h4> <pre>protected&nbsp;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;loadMap(<a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;root, <a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;tmxFile, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasResolver&nbsp;resolver, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</pre> </li> </ul> <a name="loadTileset(com.badlogic.gdx.maps.tiled.TiledMap, com.badlogic.gdx.utils.XmlReader.Element, com.badlogic.gdx.files.FileHandle, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasResolver, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadTileset</h4> <pre>protected&nbsp;void&nbsp;loadTileset(<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;map, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element, <a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;tmxFile, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasResolver&nbsp;resolver, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</pre> </li> </ul> <a name="loadTileLayer(com.badlogic.gdx.maps.tiled.TiledMap, com.badlogic.gdx.utils.XmlReader.Element)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadTileLayer</h4> <pre>protected&nbsp;void&nbsp;loadTileLayer(<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;map, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element)</pre> </li> </ul> <a name="loadObjectGroup(com.badlogic.gdx.maps.tiled.TiledMap, com.badlogic.gdx.utils.XmlReader.Element)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadObjectGroup</h4> <pre>protected&nbsp;void&nbsp;loadObjectGroup(<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;map, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element)</pre> </li> </ul> <a name="loadObject(com.badlogic.gdx.maps.MapLayer, com.badlogic.gdx.utils.XmlReader.Element)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadObject</h4> <pre>protected&nbsp;void&nbsp;loadObject(<a href="../../../../../com/badlogic/gdx/maps/MapLayer.html" title="class in com.badlogic.gdx.maps">MapLayer</a>&nbsp;layer, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element)</pre> </li> </ul> <a name="loadProperties(com.badlogic.gdx.maps.MapProperties, com.badlogic.gdx.utils.XmlReader.Element)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadProperties</h4> <pre>protected&nbsp;void&nbsp;loadProperties(<a href="../../../../../com/badlogic/gdx/maps/MapProperties.html" title="class in com.badlogic.gdx.maps">MapProperties</a>&nbsp;properties, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element)</pre> </li> </ul> <a name="createTileLayerCell(boolean, boolean, boolean)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>createTileLayerCell</h4> <pre>protected&nbsp;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMapTileLayer.Cell.html" title="class in com.badlogic.gdx.maps.tiled">TiledMapTileLayer.Cell</a>&nbsp;createTileLayerCell(boolean&nbsp;flipHorizontally, boolean&nbsp;flipVertically, boolean&nbsp;flipDiagonally)</pre> </li> </ul> <a name="getRelativeFileHandle(com.badlogic.gdx.files.FileHandle, java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getRelativeFileHandle</h4> <pre>public static&nbsp;<a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;getRelativeFileHandle(<a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;file, java.lang.String&nbsp;path)</pre> </li> </ul> <a name="unsignedByteToInt(byte)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>unsignedByteToInt</h4> <pre>protected static&nbsp;int&nbsp;unsignedByteToInt(byte&nbsp;b)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/AtlasTmxMapLoader.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em>libgdx API</em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev Class</li> <li><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html" target="_top">Frames</a></li> <li><a href="AtlasTmxMapLoader.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_class_summary">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <div style="font-size:9pt"><i> Copyright &copy; 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com) </i></div> </small></p> </body> </html>
Java
<?php declare(strict_types=1); namespace OpenTelemetry\Tests\Unit\Contrib; use AssertWell\PHPUnitGlobalState\EnvironmentVariables; use Grpc\UnaryCall; use Mockery; use Mockery\MockInterface; use OpenTelemetry\Contrib\OtlpGrpc\Exporter; use Opentelemetry\Proto\Collector\Trace\V1\TraceServiceClient; use OpenTelemetry\SDK\Trace\SpanExporterInterface; use OpenTelemetry\Tests\Unit\SDK\Trace\SpanExporter\AbstractExporterTest; use OpenTelemetry\Tests\Unit\SDK\Util\SpanData; use org\bovigo\vfs\vfsStream; /** * @covers OpenTelemetry\Contrib\OtlpGrpc\Exporter */ class OTLPGrpcExporterTest extends AbstractExporterTest { use EnvironmentVariables; public function createExporter(): SpanExporterInterface { return new Exporter(); } public function tearDown(): void { $this->restoreEnvironmentVariables(); } /** * @psalm-suppress UndefinedConstant */ public function test_exporter_happy_path(): void { $exporter = new Exporter( //These first parameters were copied from the constructor's default values 'localhost:4317', true, '', '', false, 10, $this->createMockTraceServiceClient([ 'expectations' => [ 'num_spans' => 1, ], 'return_values' => [ 'status_code' => \Grpc\STATUS_OK, ], ]) ); $exporterStatusCode = $exporter->export([new SpanData()]); $this->assertSame(SpanExporterInterface::STATUS_SUCCESS, $exporterStatusCode); } public function test_exporter_unexpected_grpc_response_status(): void { $exporter = new Exporter( //These first parameters were copied from the constructor's default values 'localhost:4317', true, '', '', false, 10, $this->createMockTraceServiceClient([ 'expectations' => [ 'num_spans' => 1, ], 'return_values' => [ 'status_code' => 'An unexpected status', ], ]) ); $exporterStatusCode = $exporter->export([new SpanData()]); $this->assertSame(SpanExporterInterface::STATUS_FAILED_NOT_RETRYABLE, $exporterStatusCode); } public function test_exporter_grpc_responds_as_unavailable(): void { $this->assertEquals(SpanExporterInterface::STATUS_FAILED_RETRYABLE, (new Exporter())->export([new SpanData()])); } public function test_set_headers_with_environment_variables(): void { $this->setEnvironmentVariable('OTEL_EXPORTER_OTLP_HEADERS', 'x-aaa=foo,x-bbb=barf'); $exporter = new Exporter(); $this->assertEquals(['x-aaa' => 'foo', 'x-bbb' => 'barf'], $exporter->getHeaders()); } public function test_set_header(): void { $exporter = new Exporter(); $exporter->setHeader('foo', 'bar'); $headers = $exporter->getHeaders(); $this->assertArrayHasKey('foo', $headers); $this->assertEquals('bar', $headers['foo']); } public function test_set_headers_in_constructor(): void { $exporter = new Exporter('localhost:4317', true, '', 'x-aaa=foo,x-bbb=bar'); $this->assertEquals(['x-aaa' => 'foo', 'x-bbb' => 'bar'], $exporter->getHeaders()); $exporter->setHeader('key', 'value'); $this->assertEquals(['x-aaa' => 'foo', 'x-bbb' => 'bar', 'key' => 'value'], $exporter->getHeaders()); } public function test_should_be_ok_to_exporter_empty_spans_collection(): void { $this->assertEquals( SpanExporterInterface::STATUS_SUCCESS, (new Exporter('test.otlp'))->export([]) ); } private function isInsecure(Exporter $exporter) : bool { $reflection = new \ReflectionClass($exporter); $property = $reflection->getProperty('insecure'); $property->setAccessible(true); return $property->getValue($exporter); } public function test_client_options(): void { // default options $exporter = new Exporter('localhost:4317'); $opts = $exporter->getClientOptions(); $this->assertEquals(10, $opts['timeout']); $this->assertTrue($this->isInsecure($exporter)); $this->assertArrayNotHasKey('grpc.default_compression_algorithm', $opts); // method args $exporter = new Exporter('localhost:4317', false, '', '', true, 5); $opts = $exporter->getClientOptions(); $this->assertEquals(5, $opts['timeout']); $this->assertFalse($this->isInsecure($exporter)); $this->assertEquals(2, $opts['grpc.default_compression_algorithm']); // env vars $this->setEnvironmentVariable('OTEL_EXPORTER_OTLP_TIMEOUT', '1'); $this->setEnvironmentVariable('OTEL_EXPORTER_OTLP_COMPRESSION', 'gzip'); $this->setEnvironmentVariable('OTEL_EXPORTER_OTLP_INSECURE', 'false'); $exporter = new Exporter('localhost:4317'); $opts = $exporter->getClientOptions(); $this->assertEquals(1, $opts['timeout']); $this->assertFalse($this->isInsecure($exporter)); $this->assertEquals(2, $opts['grpc.default_compression_algorithm']); } /** * @psalm-suppress PossiblyUndefinedMethod * @psalm-suppress UndefinedMagicMethod */ private function createMockTraceServiceClient(array $options = []) { [ 'expectations' => [ 'num_spans' => $expectedNumSpans, ], 'return_values' => [ 'status_code' => $statusCode, ] ] = $options; /** @var MockInterface&TraceServiceClient */ $mockClient = Mockery::mock(TraceServiceClient::class) ->allows('Export') ->withArgs(function ($request) use ($expectedNumSpans) { return (count($request->getResourceSpans()) === $expectedNumSpans); }) ->andReturns( Mockery::mock(UnaryCall::class) ->allows('wait') ->andReturns( [ 'unused response data', new class($statusCode) { public $code; public function __construct($code) { $this->code = $code; } }, ] ) ->getMock() ) ->getMock(); return $mockClient; } public function test_from_connection_string(): void { // @phpstan-ignore-next-line $this->assertNotSame( Exporter::fromConnectionString(), Exporter::fromConnectionString() ); } public function test_create_with_cert_file(): void { $certDir = 'var'; $certFile = 'file.cert'; vfsStream::setup($certDir); $certPath = vfsStream::url(sprintf('%s/%s', $certDir, $certFile)); file_put_contents($certPath, 'foo'); $this->setEnvironmentVariable('OTEL_EXPORTER_OTLP_INSECURE', 'false'); $this->setEnvironmentVariable('OTEL_EXPORTER_OTLP_CERTIFICATE', $certPath); $this->assertSame( $certPath, (new Exporter())->getCertificateFile() ); } }
Java
/* * MMX optimized DSP utils * Copyright (c) 2000, 2001 Fabrice Bellard * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * MMX optimization by Nick Kurshev <nickols_k@mail.ru> */ #include "libavutil/x86_cpu.h" #include "libavcodec/dsputil.h" #include "libavcodec/h264dsp.h" #include "libavcodec/mpegvideo.h" #include "libavcodec/simple_idct.h" #include "dsputil_mmx.h" #include "vp3dsp_mmx.h" #include "vp3dsp_sse2.h" #include "vp6dsp_mmx.h" #include "vp6dsp_sse2.h" #include "idct_xvid.h" //#undef NDEBUG //#include <assert.h> int mm_flags; /* multimedia extension flags */ /* pixel operations */ DECLARE_ALIGNED(8, const uint64_t, ff_bone) = 0x0101010101010101ULL; DECLARE_ALIGNED(8, const uint64_t, ff_wtwo) = 0x0002000200020002ULL; DECLARE_ALIGNED(16, const uint64_t, ff_pdw_80000000)[2] = {0x8000000080000000ULL, 0x8000000080000000ULL}; DECLARE_ALIGNED(8, const uint64_t, ff_pw_3 ) = 0x0003000300030003ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pw_4 ) = 0x0004000400040004ULL; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_5 ) = {0x0005000500050005ULL, 0x0005000500050005ULL}; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_8 ) = {0x0008000800080008ULL, 0x0008000800080008ULL}; DECLARE_ALIGNED(8, const uint64_t, ff_pw_15 ) = 0x000F000F000F000FULL; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_16 ) = {0x0010001000100010ULL, 0x0010001000100010ULL}; DECLARE_ALIGNED(8, const uint64_t, ff_pw_20 ) = 0x0014001400140014ULL; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_28 ) = {0x001C001C001C001CULL, 0x001C001C001C001CULL}; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_32 ) = {0x0020002000200020ULL, 0x0020002000200020ULL}; DECLARE_ALIGNED(8, const uint64_t, ff_pw_42 ) = 0x002A002A002A002AULL; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_64 ) = {0x0040004000400040ULL, 0x0040004000400040ULL}; DECLARE_ALIGNED(8, const uint64_t, ff_pw_96 ) = 0x0060006000600060ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pw_128) = 0x0080008000800080ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pw_255) = 0x00ff00ff00ff00ffULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_1 ) = 0x0101010101010101ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_3 ) = 0x0303030303030303ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_7 ) = 0x0707070707070707ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_1F ) = 0x1F1F1F1F1F1F1F1FULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_3F ) = 0x3F3F3F3F3F3F3F3FULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_81 ) = 0x8181818181818181ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_A1 ) = 0xA1A1A1A1A1A1A1A1ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_FC ) = 0xFCFCFCFCFCFCFCFCULL; DECLARE_ALIGNED(16, const double, ff_pd_1)[2] = { 1.0, 1.0 }; DECLARE_ALIGNED(16, const double, ff_pd_2)[2] = { 2.0, 2.0 }; #define JUMPALIGN() __asm__ volatile (ASMALIGN(3)::) #define MOVQ_ZERO(regd) __asm__ volatile ("pxor %%" #regd ", %%" #regd ::) #define MOVQ_BFE(regd) \ __asm__ volatile ( \ "pcmpeqd %%" #regd ", %%" #regd " \n\t"\ "paddb %%" #regd ", %%" #regd " \n\t" ::) #ifndef PIC #define MOVQ_BONE(regd) __asm__ volatile ("movq %0, %%" #regd " \n\t" ::"m"(ff_bone)) #define MOVQ_WTWO(regd) __asm__ volatile ("movq %0, %%" #regd " \n\t" ::"m"(ff_wtwo)) #else // for shared library it's better to use this way for accessing constants // pcmpeqd -> -1 #define MOVQ_BONE(regd) \ __asm__ volatile ( \ "pcmpeqd %%" #regd ", %%" #regd " \n\t" \ "psrlw $15, %%" #regd " \n\t" \ "packuswb %%" #regd ", %%" #regd " \n\t" ::) #define MOVQ_WTWO(regd) \ __asm__ volatile ( \ "pcmpeqd %%" #regd ", %%" #regd " \n\t" \ "psrlw $15, %%" #regd " \n\t" \ "psllw $1, %%" #regd " \n\t"::) #endif // using regr as temporary and for the output result // first argument is unmodifed and second is trashed // regfe is supposed to contain 0xfefefefefefefefe #define PAVGB_MMX_NO_RND(rega, regb, regr, regfe) \ "movq " #rega ", " #regr " \n\t"\ "pand " #regb ", " #regr " \n\t"\ "pxor " #rega ", " #regb " \n\t"\ "pand " #regfe "," #regb " \n\t"\ "psrlq $1, " #regb " \n\t"\ "paddb " #regb ", " #regr " \n\t" #define PAVGB_MMX(rega, regb, regr, regfe) \ "movq " #rega ", " #regr " \n\t"\ "por " #regb ", " #regr " \n\t"\ "pxor " #rega ", " #regb " \n\t"\ "pand " #regfe "," #regb " \n\t"\ "psrlq $1, " #regb " \n\t"\ "psubb " #regb ", " #regr " \n\t" // mm6 is supposed to contain 0xfefefefefefefefe #define PAVGBP_MMX_NO_RND(rega, regb, regr, regc, regd, regp) \ "movq " #rega ", " #regr " \n\t"\ "movq " #regc ", " #regp " \n\t"\ "pand " #regb ", " #regr " \n\t"\ "pand " #regd ", " #regp " \n\t"\ "pxor " #rega ", " #regb " \n\t"\ "pxor " #regc ", " #regd " \n\t"\ "pand %%mm6, " #regb " \n\t"\ "pand %%mm6, " #regd " \n\t"\ "psrlq $1, " #regb " \n\t"\ "psrlq $1, " #regd " \n\t"\ "paddb " #regb ", " #regr " \n\t"\ "paddb " #regd ", " #regp " \n\t" #define PAVGBP_MMX(rega, regb, regr, regc, regd, regp) \ "movq " #rega ", " #regr " \n\t"\ "movq " #regc ", " #regp " \n\t"\ "por " #regb ", " #regr " \n\t"\ "por " #regd ", " #regp " \n\t"\ "pxor " #rega ", " #regb " \n\t"\ "pxor " #regc ", " #regd " \n\t"\ "pand %%mm6, " #regb " \n\t"\ "pand %%mm6, " #regd " \n\t"\ "psrlq $1, " #regd " \n\t"\ "psrlq $1, " #regb " \n\t"\ "psubb " #regb ", " #regr " \n\t"\ "psubb " #regd ", " #regp " \n\t" /***********************************/ /* MMX no rounding */ #define DEF(x, y) x ## _no_rnd_ ## y ##_mmx #define SET_RND MOVQ_WONE #define PAVGBP(a, b, c, d, e, f) PAVGBP_MMX_NO_RND(a, b, c, d, e, f) #define PAVGB(a, b, c, e) PAVGB_MMX_NO_RND(a, b, c, e) #define OP_AVG(a, b, c, e) PAVGB_MMX(a, b, c, e) #include "dsputil_mmx_rnd_template.c" #undef DEF #undef SET_RND #undef PAVGBP #undef PAVGB /***********************************/ /* MMX rounding */ #define DEF(x, y) x ## _ ## y ##_mmx #define SET_RND MOVQ_WTWO #define PAVGBP(a, b, c, d, e, f) PAVGBP_MMX(a, b, c, d, e, f) #define PAVGB(a, b, c, e) PAVGB_MMX(a, b, c, e) #include "dsputil_mmx_rnd_template.c" #undef DEF #undef SET_RND #undef PAVGBP #undef PAVGB #undef OP_AVG /***********************************/ /* 3Dnow specific */ #define DEF(x) x ## _3dnow #define PAVGB "pavgusb" #define OP_AVG PAVGB #include "dsputil_mmx_avg_template.c" #undef DEF #undef PAVGB #undef OP_AVG /***********************************/ /* MMX2 specific */ #define DEF(x) x ## _mmx2 /* Introduced only in MMX2 set */ #define PAVGB "pavgb" #define OP_AVG PAVGB #include "dsputil_mmx_avg_template.c" #undef DEF #undef PAVGB #undef OP_AVG #define put_no_rnd_pixels16_mmx put_pixels16_mmx #define put_no_rnd_pixels8_mmx put_pixels8_mmx #define put_pixels16_mmx2 put_pixels16_mmx #define put_pixels8_mmx2 put_pixels8_mmx #define put_pixels4_mmx2 put_pixels4_mmx #define put_no_rnd_pixels16_mmx2 put_no_rnd_pixels16_mmx #define put_no_rnd_pixels8_mmx2 put_no_rnd_pixels8_mmx #define put_pixels16_3dnow put_pixels16_mmx #define put_pixels8_3dnow put_pixels8_mmx #define put_pixels4_3dnow put_pixels4_mmx #define put_no_rnd_pixels16_3dnow put_no_rnd_pixels16_mmx #define put_no_rnd_pixels8_3dnow put_no_rnd_pixels8_mmx /***********************************/ /* standard MMX */ void put_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size) { const DCTELEM *p; uint8_t *pix; /* read the pixels */ p = block; pix = pixels; /* unrolled loop */ __asm__ volatile( "movq %3, %%mm0 \n\t" "movq 8%3, %%mm1 \n\t" "movq 16%3, %%mm2 \n\t" "movq 24%3, %%mm3 \n\t" "movq 32%3, %%mm4 \n\t" "movq 40%3, %%mm5 \n\t" "movq 48%3, %%mm6 \n\t" "movq 56%3, %%mm7 \n\t" "packuswb %%mm1, %%mm0 \n\t" "packuswb %%mm3, %%mm2 \n\t" "packuswb %%mm5, %%mm4 \n\t" "packuswb %%mm7, %%mm6 \n\t" "movq %%mm0, (%0) \n\t" "movq %%mm2, (%0, %1) \n\t" "movq %%mm4, (%0, %1, 2) \n\t" "movq %%mm6, (%0, %2) \n\t" ::"r" (pix), "r" ((x86_reg)line_size), "r" ((x86_reg)line_size*3), "m"(*p) :"memory"); pix += line_size*4; p += 32; // if here would be an exact copy of the code above // compiler would generate some very strange code // thus using "r" __asm__ volatile( "movq (%3), %%mm0 \n\t" "movq 8(%3), %%mm1 \n\t" "movq 16(%3), %%mm2 \n\t" "movq 24(%3), %%mm3 \n\t" "movq 32(%3), %%mm4 \n\t" "movq 40(%3), %%mm5 \n\t" "movq 48(%3), %%mm6 \n\t" "movq 56(%3), %%mm7 \n\t" "packuswb %%mm1, %%mm0 \n\t" "packuswb %%mm3, %%mm2 \n\t" "packuswb %%mm5, %%mm4 \n\t" "packuswb %%mm7, %%mm6 \n\t" "movq %%mm0, (%0) \n\t" "movq %%mm2, (%0, %1) \n\t" "movq %%mm4, (%0, %1, 2) \n\t" "movq %%mm6, (%0, %2) \n\t" ::"r" (pix), "r" ((x86_reg)line_size), "r" ((x86_reg)line_size*3), "r"(p) :"memory"); } DECLARE_ASM_CONST(8, uint8_t, ff_vector128)[8] = { 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80 }; #define put_signed_pixels_clamped_mmx_half(off) \ "movq "#off"(%2), %%mm1 \n\t"\ "movq 16+"#off"(%2), %%mm2 \n\t"\ "movq 32+"#off"(%2), %%mm3 \n\t"\ "movq 48+"#off"(%2), %%mm4 \n\t"\ "packsswb 8+"#off"(%2), %%mm1 \n\t"\ "packsswb 24+"#off"(%2), %%mm2 \n\t"\ "packsswb 40+"#off"(%2), %%mm3 \n\t"\ "packsswb 56+"#off"(%2), %%mm4 \n\t"\ "paddb %%mm0, %%mm1 \n\t"\ "paddb %%mm0, %%mm2 \n\t"\ "paddb %%mm0, %%mm3 \n\t"\ "paddb %%mm0, %%mm4 \n\t"\ "movq %%mm1, (%0) \n\t"\ "movq %%mm2, (%0, %3) \n\t"\ "movq %%mm3, (%0, %3, 2) \n\t"\ "movq %%mm4, (%0, %1) \n\t" void put_signed_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size) { x86_reg line_skip = line_size; x86_reg line_skip3; __asm__ volatile ( "movq "MANGLE(ff_vector128)", %%mm0 \n\t" "lea (%3, %3, 2), %1 \n\t" put_signed_pixels_clamped_mmx_half(0) "lea (%0, %3, 4), %0 \n\t" put_signed_pixels_clamped_mmx_half(64) :"+&r" (pixels), "=&r" (line_skip3) :"r" (block), "r"(line_skip) :"memory"); } void add_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size) { const DCTELEM *p; uint8_t *pix; int i; /* read the pixels */ p = block; pix = pixels; MOVQ_ZERO(mm7); i = 4; do { __asm__ volatile( "movq (%2), %%mm0 \n\t" "movq 8(%2), %%mm1 \n\t" "movq 16(%2), %%mm2 \n\t" "movq 24(%2), %%mm3 \n\t" "movq %0, %%mm4 \n\t" "movq %1, %%mm6 \n\t" "movq %%mm4, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "punpckhbw %%mm7, %%mm5 \n\t" "paddsw %%mm4, %%mm0 \n\t" "paddsw %%mm5, %%mm1 \n\t" "movq %%mm6, %%mm5 \n\t" "punpcklbw %%mm7, %%mm6 \n\t" "punpckhbw %%mm7, %%mm5 \n\t" "paddsw %%mm6, %%mm2 \n\t" "paddsw %%mm5, %%mm3 \n\t" "packuswb %%mm1, %%mm0 \n\t" "packuswb %%mm3, %%mm2 \n\t" "movq %%mm0, %0 \n\t" "movq %%mm2, %1 \n\t" :"+m"(*pix), "+m"(*(pix+line_size)) :"r"(p) :"memory"); pix += line_size*2; p += 16; } while (--i); } static void put_pixels4_mmx(uint8_t *block, const uint8_t *pixels, int line_size, int h) { __asm__ volatile( "lea (%3, %3), %%"REG_a" \n\t" ASMALIGN(3) "1: \n\t" "movd (%1), %%mm0 \n\t" "movd (%1, %3), %%mm1 \n\t" "movd %%mm0, (%2) \n\t" "movd %%mm1, (%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "movd (%1), %%mm0 \n\t" "movd (%1, %3), %%mm1 \n\t" "movd %%mm0, (%2) \n\t" "movd %%mm1, (%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "subl $4, %0 \n\t" "jnz 1b \n\t" : "+g"(h), "+r" (pixels), "+r" (block) : "r"((x86_reg)line_size) : "%"REG_a, "memory" ); } static void put_pixels8_mmx(uint8_t *block, const uint8_t *pixels, int line_size, int h) { __asm__ volatile( "lea (%3, %3), %%"REG_a" \n\t" ASMALIGN(3) "1: \n\t" "movq (%1), %%mm0 \n\t" "movq (%1, %3), %%mm1 \n\t" "movq %%mm0, (%2) \n\t" "movq %%mm1, (%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "movq (%1), %%mm0 \n\t" "movq (%1, %3), %%mm1 \n\t" "movq %%mm0, (%2) \n\t" "movq %%mm1, (%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "subl $4, %0 \n\t" "jnz 1b \n\t" : "+g"(h), "+r" (pixels), "+r" (block) : "r"((x86_reg)line_size) : "%"REG_a, "memory" ); } static void put_pixels16_mmx(uint8_t *block, const uint8_t *pixels, int line_size, int h) { __asm__ volatile( "lea (%3, %3), %%"REG_a" \n\t" ASMALIGN(3) "1: \n\t" "movq (%1), %%mm0 \n\t" "movq 8(%1), %%mm4 \n\t" "movq (%1, %3), %%mm1 \n\t" "movq 8(%1, %3), %%mm5 \n\t" "movq %%mm0, (%2) \n\t" "movq %%mm4, 8(%2) \n\t" "movq %%mm1, (%2, %3) \n\t" "movq %%mm5, 8(%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "movq (%1), %%mm0 \n\t" "movq 8(%1), %%mm4 \n\t" "movq (%1, %3), %%mm1 \n\t" "movq 8(%1, %3), %%mm5 \n\t" "movq %%mm0, (%2) \n\t" "movq %%mm4, 8(%2) \n\t" "movq %%mm1, (%2, %3) \n\t" "movq %%mm5, 8(%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "subl $4, %0 \n\t" "jnz 1b \n\t" : "+g"(h), "+r" (pixels), "+r" (block) : "r"((x86_reg)line_size) : "%"REG_a, "memory" ); } static void put_pixels16_sse2(uint8_t *block, const uint8_t *pixels, int line_size, int h) { __asm__ volatile( "1: \n\t" "movdqu (%1), %%xmm0 \n\t" "movdqu (%1,%3), %%xmm1 \n\t" "movdqu (%1,%3,2), %%xmm2 \n\t" "movdqu (%1,%4), %%xmm3 \n\t" "movdqa %%xmm0, (%2) \n\t" "movdqa %%xmm1, (%2,%3) \n\t" "movdqa %%xmm2, (%2,%3,2) \n\t" "movdqa %%xmm3, (%2,%4) \n\t" "subl $4, %0 \n\t" "lea (%1,%3,4), %1 \n\t" "lea (%2,%3,4), %2 \n\t" "jnz 1b \n\t" : "+g"(h), "+r" (pixels), "+r" (block) : "r"((x86_reg)line_size), "r"((x86_reg)3L*line_size) : "memory" ); } static void avg_pixels16_sse2(uint8_t *block, const uint8_t *pixels, int line_size, int h) { __asm__ volatile( "1: \n\t" "movdqu (%1), %%xmm0 \n\t" "movdqu (%1,%3), %%xmm1 \n\t" "movdqu (%1,%3,2), %%xmm2 \n\t" "movdqu (%1,%4), %%xmm3 \n\t" "pavgb (%2), %%xmm0 \n\t" "pavgb (%2,%3), %%xmm1 \n\t" "pavgb (%2,%3,2), %%xmm2 \n\t" "pavgb (%2,%4), %%xmm3 \n\t" "movdqa %%xmm0, (%2) \n\t" "movdqa %%xmm1, (%2,%3) \n\t" "movdqa %%xmm2, (%2,%3,2) \n\t" "movdqa %%xmm3, (%2,%4) \n\t" "subl $4, %0 \n\t" "lea (%1,%3,4), %1 \n\t" "lea (%2,%3,4), %2 \n\t" "jnz 1b \n\t" : "+g"(h), "+r" (pixels), "+r" (block) : "r"((x86_reg)line_size), "r"((x86_reg)3L*line_size) : "memory" ); } #define CLEAR_BLOCKS(name,n) \ static void name(DCTELEM *blocks)\ {\ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n\t"\ "mov %1, %%"REG_a" \n\t"\ "1: \n\t"\ "movq %%mm7, (%0, %%"REG_a") \n\t"\ "movq %%mm7, 8(%0, %%"REG_a") \n\t"\ "movq %%mm7, 16(%0, %%"REG_a") \n\t"\ "movq %%mm7, 24(%0, %%"REG_a") \n\t"\ "add $32, %%"REG_a" \n\t"\ " js 1b \n\t"\ : : "r" (((uint8_t *)blocks)+128*n),\ "i" (-128*n)\ : "%"REG_a\ );\ } CLEAR_BLOCKS(clear_blocks_mmx, 6) CLEAR_BLOCKS(clear_block_mmx, 1) static void clear_block_sse(DCTELEM *block) { __asm__ volatile( "xorps %%xmm0, %%xmm0 \n" "movaps %%xmm0, (%0) \n" "movaps %%xmm0, 16(%0) \n" "movaps %%xmm0, 32(%0) \n" "movaps %%xmm0, 48(%0) \n" "movaps %%xmm0, 64(%0) \n" "movaps %%xmm0, 80(%0) \n" "movaps %%xmm0, 96(%0) \n" "movaps %%xmm0, 112(%0) \n" :: "r"(block) : "memory" ); } static void clear_blocks_sse(DCTELEM *blocks) {\ __asm__ volatile( "xorps %%xmm0, %%xmm0 \n" "mov %1, %%"REG_a" \n" "1: \n" "movaps %%xmm0, (%0, %%"REG_a") \n" "movaps %%xmm0, 16(%0, %%"REG_a") \n" "movaps %%xmm0, 32(%0, %%"REG_a") \n" "movaps %%xmm0, 48(%0, %%"REG_a") \n" "movaps %%xmm0, 64(%0, %%"REG_a") \n" "movaps %%xmm0, 80(%0, %%"REG_a") \n" "movaps %%xmm0, 96(%0, %%"REG_a") \n" "movaps %%xmm0, 112(%0, %%"REG_a") \n" "add $128, %%"REG_a" \n" " js 1b \n" : : "r" (((uint8_t *)blocks)+128*6), "i" (-128*6) : "%"REG_a ); } static void add_bytes_mmx(uint8_t *dst, uint8_t *src, int w){ x86_reg i=0; __asm__ volatile( "jmp 2f \n\t" "1: \n\t" "movq (%1, %0), %%mm0 \n\t" "movq (%2, %0), %%mm1 \n\t" "paddb %%mm0, %%mm1 \n\t" "movq %%mm1, (%2, %0) \n\t" "movq 8(%1, %0), %%mm0 \n\t" "movq 8(%2, %0), %%mm1 \n\t" "paddb %%mm0, %%mm1 \n\t" "movq %%mm1, 8(%2, %0) \n\t" "add $16, %0 \n\t" "2: \n\t" "cmp %3, %0 \n\t" " js 1b \n\t" : "+r" (i) : "r"(src), "r"(dst), "r"((x86_reg)w-15) ); for(; i<w; i++) dst[i+0] += src[i+0]; } static void add_bytes_l2_mmx(uint8_t *dst, uint8_t *src1, uint8_t *src2, int w){ x86_reg i=0; __asm__ volatile( "jmp 2f \n\t" "1: \n\t" "movq (%2, %0), %%mm0 \n\t" "movq 8(%2, %0), %%mm1 \n\t" "paddb (%3, %0), %%mm0 \n\t" "paddb 8(%3, %0), %%mm1 \n\t" "movq %%mm0, (%1, %0) \n\t" "movq %%mm1, 8(%1, %0) \n\t" "add $16, %0 \n\t" "2: \n\t" "cmp %4, %0 \n\t" " js 1b \n\t" : "+r" (i) : "r"(dst), "r"(src1), "r"(src2), "r"((x86_reg)w-15) ); for(; i<w; i++) dst[i] = src1[i] + src2[i]; } #if HAVE_7REGS && HAVE_TEN_OPERANDS static void add_hfyu_median_prediction_cmov(uint8_t *dst, const uint8_t *top, const uint8_t *diff, int w, int *left, int *left_top) { x86_reg w2 = -w; x86_reg x; int l = *left & 0xff; int tl = *left_top & 0xff; int t; __asm__ volatile( "mov %7, %3 \n" "1: \n" "movzx (%3,%4), %2 \n" "mov %2, %k3 \n" "sub %b1, %b3 \n" "add %b0, %b3 \n" "mov %2, %1 \n" "cmp %0, %2 \n" "cmovg %0, %2 \n" "cmovg %1, %0 \n" "cmp %k3, %0 \n" "cmovg %k3, %0 \n" "mov %7, %3 \n" "cmp %2, %0 \n" "cmovl %2, %0 \n" "add (%6,%4), %b0 \n" "mov %b0, (%5,%4) \n" "inc %4 \n" "jl 1b \n" :"+&q"(l), "+&q"(tl), "=&r"(t), "=&q"(x), "+&r"(w2) :"r"(dst+w), "r"(diff+w), "rm"(top+w) ); *left = l; *left_top = tl; } #endif #define H263_LOOP_FILTER \ "pxor %%mm7, %%mm7 \n\t"\ "movq %0, %%mm0 \n\t"\ "movq %0, %%mm1 \n\t"\ "movq %3, %%mm2 \n\t"\ "movq %3, %%mm3 \n\t"\ "punpcklbw %%mm7, %%mm0 \n\t"\ "punpckhbw %%mm7, %%mm1 \n\t"\ "punpcklbw %%mm7, %%mm2 \n\t"\ "punpckhbw %%mm7, %%mm3 \n\t"\ "psubw %%mm2, %%mm0 \n\t"\ "psubw %%mm3, %%mm1 \n\t"\ "movq %1, %%mm2 \n\t"\ "movq %1, %%mm3 \n\t"\ "movq %2, %%mm4 \n\t"\ "movq %2, %%mm5 \n\t"\ "punpcklbw %%mm7, %%mm2 \n\t"\ "punpckhbw %%mm7, %%mm3 \n\t"\ "punpcklbw %%mm7, %%mm4 \n\t"\ "punpckhbw %%mm7, %%mm5 \n\t"\ "psubw %%mm2, %%mm4 \n\t"\ "psubw %%mm3, %%mm5 \n\t"\ "psllw $2, %%mm4 \n\t"\ "psllw $2, %%mm5 \n\t"\ "paddw %%mm0, %%mm4 \n\t"\ "paddw %%mm1, %%mm5 \n\t"\ "pxor %%mm6, %%mm6 \n\t"\ "pcmpgtw %%mm4, %%mm6 \n\t"\ "pcmpgtw %%mm5, %%mm7 \n\t"\ "pxor %%mm6, %%mm4 \n\t"\ "pxor %%mm7, %%mm5 \n\t"\ "psubw %%mm6, %%mm4 \n\t"\ "psubw %%mm7, %%mm5 \n\t"\ "psrlw $3, %%mm4 \n\t"\ "psrlw $3, %%mm5 \n\t"\ "packuswb %%mm5, %%mm4 \n\t"\ "packsswb %%mm7, %%mm6 \n\t"\ "pxor %%mm7, %%mm7 \n\t"\ "movd %4, %%mm2 \n\t"\ "punpcklbw %%mm2, %%mm2 \n\t"\ "punpcklbw %%mm2, %%mm2 \n\t"\ "punpcklbw %%mm2, %%mm2 \n\t"\ "psubusb %%mm4, %%mm2 \n\t"\ "movq %%mm2, %%mm3 \n\t"\ "psubusb %%mm4, %%mm3 \n\t"\ "psubb %%mm3, %%mm2 \n\t"\ "movq %1, %%mm3 \n\t"\ "movq %2, %%mm4 \n\t"\ "pxor %%mm6, %%mm3 \n\t"\ "pxor %%mm6, %%mm4 \n\t"\ "paddusb %%mm2, %%mm3 \n\t"\ "psubusb %%mm2, %%mm4 \n\t"\ "pxor %%mm6, %%mm3 \n\t"\ "pxor %%mm6, %%mm4 \n\t"\ "paddusb %%mm2, %%mm2 \n\t"\ "packsswb %%mm1, %%mm0 \n\t"\ "pcmpgtb %%mm0, %%mm7 \n\t"\ "pxor %%mm7, %%mm0 \n\t"\ "psubb %%mm7, %%mm0 \n\t"\ "movq %%mm0, %%mm1 \n\t"\ "psubusb %%mm2, %%mm0 \n\t"\ "psubb %%mm0, %%mm1 \n\t"\ "pand %5, %%mm1 \n\t"\ "psrlw $2, %%mm1 \n\t"\ "pxor %%mm7, %%mm1 \n\t"\ "psubb %%mm7, %%mm1 \n\t"\ "movq %0, %%mm5 \n\t"\ "movq %3, %%mm6 \n\t"\ "psubb %%mm1, %%mm5 \n\t"\ "paddb %%mm1, %%mm6 \n\t" static void h263_v_loop_filter_mmx(uint8_t *src, int stride, int qscale){ if(CONFIG_H263_DECODER || CONFIG_H263_ENCODER) { const int strength= ff_h263_loop_filter_strength[qscale]; __asm__ volatile( H263_LOOP_FILTER "movq %%mm3, %1 \n\t" "movq %%mm4, %2 \n\t" "movq %%mm5, %0 \n\t" "movq %%mm6, %3 \n\t" : "+m" (*(uint64_t*)(src - 2*stride)), "+m" (*(uint64_t*)(src - 1*stride)), "+m" (*(uint64_t*)(src + 0*stride)), "+m" (*(uint64_t*)(src + 1*stride)) : "g" (2*strength), "m"(ff_pb_FC) ); } } static inline void transpose4x4(uint8_t *dst, uint8_t *src, int dst_stride, int src_stride){ __asm__ volatile( //FIXME could save 1 instruction if done as 8x4 ... "movd %4, %%mm0 \n\t" "movd %5, %%mm1 \n\t" "movd %6, %%mm2 \n\t" "movd %7, %%mm3 \n\t" "punpcklbw %%mm1, %%mm0 \n\t" "punpcklbw %%mm3, %%mm2 \n\t" "movq %%mm0, %%mm1 \n\t" "punpcklwd %%mm2, %%mm0 \n\t" "punpckhwd %%mm2, %%mm1 \n\t" "movd %%mm0, %0 \n\t" "punpckhdq %%mm0, %%mm0 \n\t" "movd %%mm0, %1 \n\t" "movd %%mm1, %2 \n\t" "punpckhdq %%mm1, %%mm1 \n\t" "movd %%mm1, %3 \n\t" : "=m" (*(uint32_t*)(dst + 0*dst_stride)), "=m" (*(uint32_t*)(dst + 1*dst_stride)), "=m" (*(uint32_t*)(dst + 2*dst_stride)), "=m" (*(uint32_t*)(dst + 3*dst_stride)) : "m" (*(uint32_t*)(src + 0*src_stride)), "m" (*(uint32_t*)(src + 1*src_stride)), "m" (*(uint32_t*)(src + 2*src_stride)), "m" (*(uint32_t*)(src + 3*src_stride)) ); } static void h263_h_loop_filter_mmx(uint8_t *src, int stride, int qscale){ if(CONFIG_H263_DECODER || CONFIG_H263_ENCODER) { const int strength= ff_h263_loop_filter_strength[qscale]; DECLARE_ALIGNED(8, uint64_t, temp)[4]; uint8_t *btemp= (uint8_t*)temp; src -= 2; transpose4x4(btemp , src , 8, stride); transpose4x4(btemp+4, src + 4*stride, 8, stride); __asm__ volatile( H263_LOOP_FILTER // 5 3 4 6 : "+m" (temp[0]), "+m" (temp[1]), "+m" (temp[2]), "+m" (temp[3]) : "g" (2*strength), "m"(ff_pb_FC) ); __asm__ volatile( "movq %%mm5, %%mm1 \n\t" "movq %%mm4, %%mm0 \n\t" "punpcklbw %%mm3, %%mm5 \n\t" "punpcklbw %%mm6, %%mm4 \n\t" "punpckhbw %%mm3, %%mm1 \n\t" "punpckhbw %%mm6, %%mm0 \n\t" "movq %%mm5, %%mm3 \n\t" "movq %%mm1, %%mm6 \n\t" "punpcklwd %%mm4, %%mm5 \n\t" "punpcklwd %%mm0, %%mm1 \n\t" "punpckhwd %%mm4, %%mm3 \n\t" "punpckhwd %%mm0, %%mm6 \n\t" "movd %%mm5, (%0) \n\t" "punpckhdq %%mm5, %%mm5 \n\t" "movd %%mm5, (%0,%2) \n\t" "movd %%mm3, (%0,%2,2) \n\t" "punpckhdq %%mm3, %%mm3 \n\t" "movd %%mm3, (%0,%3) \n\t" "movd %%mm1, (%1) \n\t" "punpckhdq %%mm1, %%mm1 \n\t" "movd %%mm1, (%1,%2) \n\t" "movd %%mm6, (%1,%2,2) \n\t" "punpckhdq %%mm6, %%mm6 \n\t" "movd %%mm6, (%1,%3) \n\t" :: "r" (src), "r" (src + 4*stride), "r" ((x86_reg) stride ), "r" ((x86_reg)(3*stride)) ); } } /* draw the edges of width 'w' of an image of size width, height this mmx version can only handle w==8 || w==16 */ static void draw_edges_mmx(uint8_t *buf, int wrap, int width, int height, int w) { uint8_t *ptr, *last_line; int i; last_line = buf + (height - 1) * wrap; /* left and right */ ptr = buf; if(w==8) { __asm__ volatile( "1: \n\t" "movd (%0), %%mm0 \n\t" "punpcklbw %%mm0, %%mm0 \n\t" "punpcklwd %%mm0, %%mm0 \n\t" "punpckldq %%mm0, %%mm0 \n\t" "movq %%mm0, -8(%0) \n\t" "movq -8(%0, %2), %%mm1 \n\t" "punpckhbw %%mm1, %%mm1 \n\t" "punpckhwd %%mm1, %%mm1 \n\t" "punpckhdq %%mm1, %%mm1 \n\t" "movq %%mm1, (%0, %2) \n\t" "add %1, %0 \n\t" "cmp %3, %0 \n\t" " jb 1b \n\t" : "+r" (ptr) : "r" ((x86_reg)wrap), "r" ((x86_reg)width), "r" (ptr + wrap*height) ); } else { __asm__ volatile( "1: \n\t" "movd (%0), %%mm0 \n\t" "punpcklbw %%mm0, %%mm0 \n\t" "punpcklwd %%mm0, %%mm0 \n\t" "punpckldq %%mm0, %%mm0 \n\t" "movq %%mm0, -8(%0) \n\t" "movq %%mm0, -16(%0) \n\t" "movq -8(%0, %2), %%mm1 \n\t" "punpckhbw %%mm1, %%mm1 \n\t" "punpckhwd %%mm1, %%mm1 \n\t" "punpckhdq %%mm1, %%mm1 \n\t" "movq %%mm1, (%0, %2) \n\t" "movq %%mm1, 8(%0, %2) \n\t" "add %1, %0 \n\t" "cmp %3, %0 \n\t" " jb 1b \n\t" : "+r" (ptr) : "r" ((x86_reg)wrap), "r" ((x86_reg)width), "r" (ptr + wrap*height) ); } for(i=0;i<w;i+=4) { /* top and bottom (and hopefully also the corners) */ ptr= buf - (i + 1) * wrap - w; __asm__ volatile( "1: \n\t" "movq (%1, %0), %%mm0 \n\t" "movq %%mm0, (%0) \n\t" "movq %%mm0, (%0, %2) \n\t" "movq %%mm0, (%0, %2, 2) \n\t" "movq %%mm0, (%0, %3) \n\t" "add $8, %0 \n\t" "cmp %4, %0 \n\t" " jb 1b \n\t" : "+r" (ptr) : "r" ((x86_reg)buf - (x86_reg)ptr - w), "r" ((x86_reg)-wrap), "r" ((x86_reg)-wrap*3), "r" (ptr+width+2*w) ); ptr= last_line + (i + 1) * wrap - w; __asm__ volatile( "1: \n\t" "movq (%1, %0), %%mm0 \n\t" "movq %%mm0, (%0) \n\t" "movq %%mm0, (%0, %2) \n\t" "movq %%mm0, (%0, %2, 2) \n\t" "movq %%mm0, (%0, %3) \n\t" "add $8, %0 \n\t" "cmp %4, %0 \n\t" " jb 1b \n\t" : "+r" (ptr) : "r" ((x86_reg)last_line - (x86_reg)ptr - w), "r" ((x86_reg)wrap), "r" ((x86_reg)wrap*3), "r" (ptr+width+2*w) ); } } #define PAETH(cpu, abs3)\ static void add_png_paeth_prediction_##cpu(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp)\ {\ x86_reg i = -bpp;\ x86_reg end = w-3;\ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n"\ "movd (%1,%0), %%mm0 \n"\ "movd (%2,%0), %%mm1 \n"\ "punpcklbw %%mm7, %%mm0 \n"\ "punpcklbw %%mm7, %%mm1 \n"\ "add %4, %0 \n"\ "1: \n"\ "movq %%mm1, %%mm2 \n"\ "movd (%2,%0), %%mm1 \n"\ "movq %%mm2, %%mm3 \n"\ "punpcklbw %%mm7, %%mm1 \n"\ "movq %%mm2, %%mm4 \n"\ "psubw %%mm1, %%mm3 \n"\ "psubw %%mm0, %%mm4 \n"\ "movq %%mm3, %%mm5 \n"\ "paddw %%mm4, %%mm5 \n"\ abs3\ "movq %%mm4, %%mm6 \n"\ "pminsw %%mm5, %%mm6 \n"\ "pcmpgtw %%mm6, %%mm3 \n"\ "pcmpgtw %%mm5, %%mm4 \n"\ "movq %%mm4, %%mm6 \n"\ "pand %%mm3, %%mm4 \n"\ "pandn %%mm3, %%mm6 \n"\ "pandn %%mm0, %%mm3 \n"\ "movd (%3,%0), %%mm0 \n"\ "pand %%mm1, %%mm6 \n"\ "pand %%mm4, %%mm2 \n"\ "punpcklbw %%mm7, %%mm0 \n"\ "movq %6, %%mm5 \n"\ "paddw %%mm6, %%mm0 \n"\ "paddw %%mm2, %%mm3 \n"\ "paddw %%mm3, %%mm0 \n"\ "pand %%mm5, %%mm0 \n"\ "movq %%mm0, %%mm3 \n"\ "packuswb %%mm3, %%mm3 \n"\ "movd %%mm3, (%1,%0) \n"\ "add %4, %0 \n"\ "cmp %5, %0 \n"\ "jle 1b \n"\ :"+r"(i)\ :"r"(dst), "r"(top), "r"(src), "r"((x86_reg)bpp), "g"(end),\ "m"(ff_pw_255)\ :"memory"\ );\ } #define ABS3_MMX2\ "psubw %%mm5, %%mm7 \n"\ "pmaxsw %%mm7, %%mm5 \n"\ "pxor %%mm6, %%mm6 \n"\ "pxor %%mm7, %%mm7 \n"\ "psubw %%mm3, %%mm6 \n"\ "psubw %%mm4, %%mm7 \n"\ "pmaxsw %%mm6, %%mm3 \n"\ "pmaxsw %%mm7, %%mm4 \n"\ "pxor %%mm7, %%mm7 \n" #define ABS3_SSSE3\ "pabsw %%mm3, %%mm3 \n"\ "pabsw %%mm4, %%mm4 \n"\ "pabsw %%mm5, %%mm5 \n" PAETH(mmx2, ABS3_MMX2) #if HAVE_SSSE3 PAETH(ssse3, ABS3_SSSE3) #endif #define QPEL_V_LOW(m3,m4,m5,m6, pw_20, pw_3, rnd, in0, in1, in2, in7, out, OP)\ "paddw " #m4 ", " #m3 " \n\t" /* x1 */\ "movq "MANGLE(ff_pw_20)", %%mm4 \n\t" /* 20 */\ "pmullw " #m3 ", %%mm4 \n\t" /* 20x1 */\ "movq "#in7", " #m3 " \n\t" /* d */\ "movq "#in0", %%mm5 \n\t" /* D */\ "paddw " #m3 ", %%mm5 \n\t" /* x4 */\ "psubw %%mm5, %%mm4 \n\t" /* 20x1 - x4 */\ "movq "#in1", %%mm5 \n\t" /* C */\ "movq "#in2", %%mm6 \n\t" /* B */\ "paddw " #m6 ", %%mm5 \n\t" /* x3 */\ "paddw " #m5 ", %%mm6 \n\t" /* x2 */\ "paddw %%mm6, %%mm6 \n\t" /* 2x2 */\ "psubw %%mm6, %%mm5 \n\t" /* -2x2 + x3 */\ "pmullw "MANGLE(ff_pw_3)", %%mm5 \n\t" /* -6x2 + 3x3 */\ "paddw " #rnd ", %%mm4 \n\t" /* x2 */\ "paddw %%mm4, %%mm5 \n\t" /* 20x1 - 6x2 + 3x3 - x4 */\ "psraw $5, %%mm5 \n\t"\ "packuswb %%mm5, %%mm5 \n\t"\ OP(%%mm5, out, %%mm7, d) #define QPEL_BASE(OPNAME, ROUNDER, RND, OP_MMX2, OP_3DNOW)\ static void OPNAME ## mpeg4_qpel16_h_lowpass_mmx2(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\ uint64_t temp;\ \ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n\t"\ "1: \n\t"\ "movq (%0), %%mm0 \n\t" /* ABCDEFGH */\ "movq %%mm0, %%mm1 \n\t" /* ABCDEFGH */\ "movq %%mm0, %%mm2 \n\t" /* ABCDEFGH */\ "punpcklbw %%mm7, %%mm0 \n\t" /* 0A0B0C0D */\ "punpckhbw %%mm7, %%mm1 \n\t" /* 0E0F0G0H */\ "pshufw $0x90, %%mm0, %%mm5 \n\t" /* 0A0A0B0C */\ "pshufw $0x41, %%mm0, %%mm6 \n\t" /* 0B0A0A0B */\ "movq %%mm2, %%mm3 \n\t" /* ABCDEFGH */\ "movq %%mm2, %%mm4 \n\t" /* ABCDEFGH */\ "psllq $8, %%mm2 \n\t" /* 0ABCDEFG */\ "psllq $16, %%mm3 \n\t" /* 00ABCDEF */\ "psllq $24, %%mm4 \n\t" /* 000ABCDE */\ "punpckhbw %%mm7, %%mm2 \n\t" /* 0D0E0F0G */\ "punpckhbw %%mm7, %%mm3 \n\t" /* 0C0D0E0F */\ "punpckhbw %%mm7, %%mm4 \n\t" /* 0B0C0D0E */\ "paddw %%mm3, %%mm5 \n\t" /* b */\ "paddw %%mm2, %%mm6 \n\t" /* c */\ "paddw %%mm5, %%mm5 \n\t" /* 2b */\ "psubw %%mm5, %%mm6 \n\t" /* c - 2b */\ "pshufw $0x06, %%mm0, %%mm5 \n\t" /* 0C0B0A0A */\ "pmullw "MANGLE(ff_pw_3)", %%mm6 \n\t" /* 3c - 6b */\ "paddw %%mm4, %%mm0 \n\t" /* a */\ "paddw %%mm1, %%mm5 \n\t" /* d */\ "pmullw "MANGLE(ff_pw_20)", %%mm0 \n\t" /* 20a */\ "psubw %%mm5, %%mm0 \n\t" /* 20a - d */\ "paddw %6, %%mm6 \n\t"\ "paddw %%mm6, %%mm0 \n\t" /* 20a - 6b + 3c - d */\ "psraw $5, %%mm0 \n\t"\ "movq %%mm0, %5 \n\t"\ /* mm1=EFGH, mm2=DEFG, mm3=CDEF, mm4=BCDE, mm7=0 */\ \ "movq 5(%0), %%mm0 \n\t" /* FGHIJKLM */\ "movq %%mm0, %%mm5 \n\t" /* FGHIJKLM */\ "movq %%mm0, %%mm6 \n\t" /* FGHIJKLM */\ "psrlq $8, %%mm0 \n\t" /* GHIJKLM0 */\ "psrlq $16, %%mm5 \n\t" /* HIJKLM00 */\ "punpcklbw %%mm7, %%mm0 \n\t" /* 0G0H0I0J */\ "punpcklbw %%mm7, %%mm5 \n\t" /* 0H0I0J0K */\ "paddw %%mm0, %%mm2 \n\t" /* b */\ "paddw %%mm5, %%mm3 \n\t" /* c */\ "paddw %%mm2, %%mm2 \n\t" /* 2b */\ "psubw %%mm2, %%mm3 \n\t" /* c - 2b */\ "movq %%mm6, %%mm2 \n\t" /* FGHIJKLM */\ "psrlq $24, %%mm6 \n\t" /* IJKLM000 */\ "punpcklbw %%mm7, %%mm2 \n\t" /* 0F0G0H0I */\ "punpcklbw %%mm7, %%mm6 \n\t" /* 0I0J0K0L */\ "pmullw "MANGLE(ff_pw_3)", %%mm3 \n\t" /* 3c - 6b */\ "paddw %%mm2, %%mm1 \n\t" /* a */\ "paddw %%mm6, %%mm4 \n\t" /* d */\ "pmullw "MANGLE(ff_pw_20)", %%mm1 \n\t" /* 20a */\ "psubw %%mm4, %%mm3 \n\t" /* - 6b +3c - d */\ "paddw %6, %%mm1 \n\t"\ "paddw %%mm1, %%mm3 \n\t" /* 20a - 6b +3c - d */\ "psraw $5, %%mm3 \n\t"\ "movq %5, %%mm1 \n\t"\ "packuswb %%mm3, %%mm1 \n\t"\ OP_MMX2(%%mm1, (%1),%%mm4, q)\ /* mm0= GHIJ, mm2=FGHI, mm5=HIJK, mm6=IJKL, mm7=0 */\ \ "movq 9(%0), %%mm1 \n\t" /* JKLMNOPQ */\ "movq %%mm1, %%mm4 \n\t" /* JKLMNOPQ */\ "movq %%mm1, %%mm3 \n\t" /* JKLMNOPQ */\ "psrlq $8, %%mm1 \n\t" /* KLMNOPQ0 */\ "psrlq $16, %%mm4 \n\t" /* LMNOPQ00 */\ "punpcklbw %%mm7, %%mm1 \n\t" /* 0K0L0M0N */\ "punpcklbw %%mm7, %%mm4 \n\t" /* 0L0M0N0O */\ "paddw %%mm1, %%mm5 \n\t" /* b */\ "paddw %%mm4, %%mm0 \n\t" /* c */\ "paddw %%mm5, %%mm5 \n\t" /* 2b */\ "psubw %%mm5, %%mm0 \n\t" /* c - 2b */\ "movq %%mm3, %%mm5 \n\t" /* JKLMNOPQ */\ "psrlq $24, %%mm3 \n\t" /* MNOPQ000 */\ "pmullw "MANGLE(ff_pw_3)", %%mm0 \n\t" /* 3c - 6b */\ "punpcklbw %%mm7, %%mm3 \n\t" /* 0M0N0O0P */\ "paddw %%mm3, %%mm2 \n\t" /* d */\ "psubw %%mm2, %%mm0 \n\t" /* -6b + 3c - d */\ "movq %%mm5, %%mm2 \n\t" /* JKLMNOPQ */\ "punpcklbw %%mm7, %%mm2 \n\t" /* 0J0K0L0M */\ "punpckhbw %%mm7, %%mm5 \n\t" /* 0N0O0P0Q */\ "paddw %%mm2, %%mm6 \n\t" /* a */\ "pmullw "MANGLE(ff_pw_20)", %%mm6 \n\t" /* 20a */\ "paddw %6, %%mm0 \n\t"\ "paddw %%mm6, %%mm0 \n\t" /* 20a - 6b + 3c - d */\ "psraw $5, %%mm0 \n\t"\ /* mm1=KLMN, mm2=JKLM, mm3=MNOP, mm4=LMNO, mm5=NOPQ mm7=0 */\ \ "paddw %%mm5, %%mm3 \n\t" /* a */\ "pshufw $0xF9, %%mm5, %%mm6 \n\t" /* 0O0P0Q0Q */\ "paddw %%mm4, %%mm6 \n\t" /* b */\ "pshufw $0xBE, %%mm5, %%mm4 \n\t" /* 0P0Q0Q0P */\ "pshufw $0x6F, %%mm5, %%mm5 \n\t" /* 0Q0Q0P0O */\ "paddw %%mm1, %%mm4 \n\t" /* c */\ "paddw %%mm2, %%mm5 \n\t" /* d */\ "paddw %%mm6, %%mm6 \n\t" /* 2b */\ "psubw %%mm6, %%mm4 \n\t" /* c - 2b */\ "pmullw "MANGLE(ff_pw_20)", %%mm3 \n\t" /* 20a */\ "pmullw "MANGLE(ff_pw_3)", %%mm4 \n\t" /* 3c - 6b */\ "psubw %%mm5, %%mm3 \n\t" /* -6b + 3c - d */\ "paddw %6, %%mm4 \n\t"\ "paddw %%mm3, %%mm4 \n\t" /* 20a - 6b + 3c - d */\ "psraw $5, %%mm4 \n\t"\ "packuswb %%mm4, %%mm0 \n\t"\ OP_MMX2(%%mm0, 8(%1), %%mm4, q)\ \ "add %3, %0 \n\t"\ "add %4, %1 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ : "+a"(src), "+c"(dst), "+D"(h)\ : "d"((x86_reg)srcStride), "S"((x86_reg)dstStride), /*"m"(ff_pw_20), "m"(ff_pw_3),*/ "m"(temp), "m"(ROUNDER)\ : "memory"\ );\ }\ \ static void OPNAME ## mpeg4_qpel16_h_lowpass_3dnow(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\ int i;\ int16_t temp[16];\ /* quick HACK, XXX FIXME MUST be optimized */\ for(i=0; i<h; i++)\ {\ temp[ 0]= (src[ 0]+src[ 1])*20 - (src[ 0]+src[ 2])*6 + (src[ 1]+src[ 3])*3 - (src[ 2]+src[ 4]);\ temp[ 1]= (src[ 1]+src[ 2])*20 - (src[ 0]+src[ 3])*6 + (src[ 0]+src[ 4])*3 - (src[ 1]+src[ 5]);\ temp[ 2]= (src[ 2]+src[ 3])*20 - (src[ 1]+src[ 4])*6 + (src[ 0]+src[ 5])*3 - (src[ 0]+src[ 6]);\ temp[ 3]= (src[ 3]+src[ 4])*20 - (src[ 2]+src[ 5])*6 + (src[ 1]+src[ 6])*3 - (src[ 0]+src[ 7]);\ temp[ 4]= (src[ 4]+src[ 5])*20 - (src[ 3]+src[ 6])*6 + (src[ 2]+src[ 7])*3 - (src[ 1]+src[ 8]);\ temp[ 5]= (src[ 5]+src[ 6])*20 - (src[ 4]+src[ 7])*6 + (src[ 3]+src[ 8])*3 - (src[ 2]+src[ 9]);\ temp[ 6]= (src[ 6]+src[ 7])*20 - (src[ 5]+src[ 8])*6 + (src[ 4]+src[ 9])*3 - (src[ 3]+src[10]);\ temp[ 7]= (src[ 7]+src[ 8])*20 - (src[ 6]+src[ 9])*6 + (src[ 5]+src[10])*3 - (src[ 4]+src[11]);\ temp[ 8]= (src[ 8]+src[ 9])*20 - (src[ 7]+src[10])*6 + (src[ 6]+src[11])*3 - (src[ 5]+src[12]);\ temp[ 9]= (src[ 9]+src[10])*20 - (src[ 8]+src[11])*6 + (src[ 7]+src[12])*3 - (src[ 6]+src[13]);\ temp[10]= (src[10]+src[11])*20 - (src[ 9]+src[12])*6 + (src[ 8]+src[13])*3 - (src[ 7]+src[14]);\ temp[11]= (src[11]+src[12])*20 - (src[10]+src[13])*6 + (src[ 9]+src[14])*3 - (src[ 8]+src[15]);\ temp[12]= (src[12]+src[13])*20 - (src[11]+src[14])*6 + (src[10]+src[15])*3 - (src[ 9]+src[16]);\ temp[13]= (src[13]+src[14])*20 - (src[12]+src[15])*6 + (src[11]+src[16])*3 - (src[10]+src[16]);\ temp[14]= (src[14]+src[15])*20 - (src[13]+src[16])*6 + (src[12]+src[16])*3 - (src[11]+src[15]);\ temp[15]= (src[15]+src[16])*20 - (src[14]+src[16])*6 + (src[13]+src[15])*3 - (src[12]+src[14]);\ __asm__ volatile(\ "movq (%0), %%mm0 \n\t"\ "movq 8(%0), %%mm1 \n\t"\ "paddw %2, %%mm0 \n\t"\ "paddw %2, %%mm1 \n\t"\ "psraw $5, %%mm0 \n\t"\ "psraw $5, %%mm1 \n\t"\ "packuswb %%mm1, %%mm0 \n\t"\ OP_3DNOW(%%mm0, (%1), %%mm1, q)\ "movq 16(%0), %%mm0 \n\t"\ "movq 24(%0), %%mm1 \n\t"\ "paddw %2, %%mm0 \n\t"\ "paddw %2, %%mm1 \n\t"\ "psraw $5, %%mm0 \n\t"\ "psraw $5, %%mm1 \n\t"\ "packuswb %%mm1, %%mm0 \n\t"\ OP_3DNOW(%%mm0, 8(%1), %%mm1, q)\ :: "r"(temp), "r"(dst), "m"(ROUNDER)\ : "memory"\ );\ dst+=dstStride;\ src+=srcStride;\ }\ }\ \ static void OPNAME ## mpeg4_qpel8_h_lowpass_mmx2(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n\t"\ "1: \n\t"\ "movq (%0), %%mm0 \n\t" /* ABCDEFGH */\ "movq %%mm0, %%mm1 \n\t" /* ABCDEFGH */\ "movq %%mm0, %%mm2 \n\t" /* ABCDEFGH */\ "punpcklbw %%mm7, %%mm0 \n\t" /* 0A0B0C0D */\ "punpckhbw %%mm7, %%mm1 \n\t" /* 0E0F0G0H */\ "pshufw $0x90, %%mm0, %%mm5 \n\t" /* 0A0A0B0C */\ "pshufw $0x41, %%mm0, %%mm6 \n\t" /* 0B0A0A0B */\ "movq %%mm2, %%mm3 \n\t" /* ABCDEFGH */\ "movq %%mm2, %%mm4 \n\t" /* ABCDEFGH */\ "psllq $8, %%mm2 \n\t" /* 0ABCDEFG */\ "psllq $16, %%mm3 \n\t" /* 00ABCDEF */\ "psllq $24, %%mm4 \n\t" /* 000ABCDE */\ "punpckhbw %%mm7, %%mm2 \n\t" /* 0D0E0F0G */\ "punpckhbw %%mm7, %%mm3 \n\t" /* 0C0D0E0F */\ "punpckhbw %%mm7, %%mm4 \n\t" /* 0B0C0D0E */\ "paddw %%mm3, %%mm5 \n\t" /* b */\ "paddw %%mm2, %%mm6 \n\t" /* c */\ "paddw %%mm5, %%mm5 \n\t" /* 2b */\ "psubw %%mm5, %%mm6 \n\t" /* c - 2b */\ "pshufw $0x06, %%mm0, %%mm5 \n\t" /* 0C0B0A0A */\ "pmullw "MANGLE(ff_pw_3)", %%mm6 \n\t" /* 3c - 6b */\ "paddw %%mm4, %%mm0 \n\t" /* a */\ "paddw %%mm1, %%mm5 \n\t" /* d */\ "pmullw "MANGLE(ff_pw_20)", %%mm0 \n\t" /* 20a */\ "psubw %%mm5, %%mm0 \n\t" /* 20a - d */\ "paddw %5, %%mm6 \n\t"\ "paddw %%mm6, %%mm0 \n\t" /* 20a - 6b + 3c - d */\ "psraw $5, %%mm0 \n\t"\ /* mm1=EFGH, mm2=DEFG, mm3=CDEF, mm4=BCDE, mm7=0 */\ \ "movd 5(%0), %%mm5 \n\t" /* FGHI */\ "punpcklbw %%mm7, %%mm5 \n\t" /* 0F0G0H0I */\ "pshufw $0xF9, %%mm5, %%mm6 \n\t" /* 0G0H0I0I */\ "paddw %%mm5, %%mm1 \n\t" /* a */\ "paddw %%mm6, %%mm2 \n\t" /* b */\ "pshufw $0xBE, %%mm5, %%mm6 \n\t" /* 0H0I0I0H */\ "pshufw $0x6F, %%mm5, %%mm5 \n\t" /* 0I0I0H0G */\ "paddw %%mm6, %%mm3 \n\t" /* c */\ "paddw %%mm5, %%mm4 \n\t" /* d */\ "paddw %%mm2, %%mm2 \n\t" /* 2b */\ "psubw %%mm2, %%mm3 \n\t" /* c - 2b */\ "pmullw "MANGLE(ff_pw_20)", %%mm1 \n\t" /* 20a */\ "pmullw "MANGLE(ff_pw_3)", %%mm3 \n\t" /* 3c - 6b */\ "psubw %%mm4, %%mm3 \n\t" /* -6b + 3c - d */\ "paddw %5, %%mm1 \n\t"\ "paddw %%mm1, %%mm3 \n\t" /* 20a - 6b + 3c - d */\ "psraw $5, %%mm3 \n\t"\ "packuswb %%mm3, %%mm0 \n\t"\ OP_MMX2(%%mm0, (%1), %%mm4, q)\ \ "add %3, %0 \n\t"\ "add %4, %1 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ : "+a"(src), "+c"(dst), "+d"(h)\ : "S"((x86_reg)srcStride), "D"((x86_reg)dstStride), /*"m"(ff_pw_20), "m"(ff_pw_3),*/ "m"(ROUNDER)\ : "memory"\ );\ }\ \ static void OPNAME ## mpeg4_qpel8_h_lowpass_3dnow(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\ int i;\ int16_t temp[8];\ /* quick HACK, XXX FIXME MUST be optimized */\ for(i=0; i<h; i++)\ {\ temp[ 0]= (src[ 0]+src[ 1])*20 - (src[ 0]+src[ 2])*6 + (src[ 1]+src[ 3])*3 - (src[ 2]+src[ 4]);\ temp[ 1]= (src[ 1]+src[ 2])*20 - (src[ 0]+src[ 3])*6 + (src[ 0]+src[ 4])*3 - (src[ 1]+src[ 5]);\ temp[ 2]= (src[ 2]+src[ 3])*20 - (src[ 1]+src[ 4])*6 + (src[ 0]+src[ 5])*3 - (src[ 0]+src[ 6]);\ temp[ 3]= (src[ 3]+src[ 4])*20 - (src[ 2]+src[ 5])*6 + (src[ 1]+src[ 6])*3 - (src[ 0]+src[ 7]);\ temp[ 4]= (src[ 4]+src[ 5])*20 - (src[ 3]+src[ 6])*6 + (src[ 2]+src[ 7])*3 - (src[ 1]+src[ 8]);\ temp[ 5]= (src[ 5]+src[ 6])*20 - (src[ 4]+src[ 7])*6 + (src[ 3]+src[ 8])*3 - (src[ 2]+src[ 8]);\ temp[ 6]= (src[ 6]+src[ 7])*20 - (src[ 5]+src[ 8])*6 + (src[ 4]+src[ 8])*3 - (src[ 3]+src[ 7]);\ temp[ 7]= (src[ 7]+src[ 8])*20 - (src[ 6]+src[ 8])*6 + (src[ 5]+src[ 7])*3 - (src[ 4]+src[ 6]);\ __asm__ volatile(\ "movq (%0), %%mm0 \n\t"\ "movq 8(%0), %%mm1 \n\t"\ "paddw %2, %%mm0 \n\t"\ "paddw %2, %%mm1 \n\t"\ "psraw $5, %%mm0 \n\t"\ "psraw $5, %%mm1 \n\t"\ "packuswb %%mm1, %%mm0 \n\t"\ OP_3DNOW(%%mm0, (%1), %%mm1, q)\ :: "r"(temp), "r"(dst), "m"(ROUNDER)\ :"memory"\ );\ dst+=dstStride;\ src+=srcStride;\ }\ } #define QPEL_OP(OPNAME, ROUNDER, RND, OP, MMX)\ \ static void OPNAME ## mpeg4_qpel16_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\ uint64_t temp[17*4];\ uint64_t *temp_ptr= temp;\ int count= 17;\ \ /*FIXME unroll */\ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n\t"\ "1: \n\t"\ "movq (%0), %%mm0 \n\t"\ "movq (%0), %%mm1 \n\t"\ "movq 8(%0), %%mm2 \n\t"\ "movq 8(%0), %%mm3 \n\t"\ "punpcklbw %%mm7, %%mm0 \n\t"\ "punpckhbw %%mm7, %%mm1 \n\t"\ "punpcklbw %%mm7, %%mm2 \n\t"\ "punpckhbw %%mm7, %%mm3 \n\t"\ "movq %%mm0, (%1) \n\t"\ "movq %%mm1, 17*8(%1) \n\t"\ "movq %%mm2, 2*17*8(%1) \n\t"\ "movq %%mm3, 3*17*8(%1) \n\t"\ "add $8, %1 \n\t"\ "add %3, %0 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ : "+r" (src), "+r" (temp_ptr), "+r"(count)\ : "r" ((x86_reg)srcStride)\ : "memory"\ );\ \ temp_ptr= temp;\ count=4;\ \ /*FIXME reorder for speed */\ __asm__ volatile(\ /*"pxor %%mm7, %%mm7 \n\t"*/\ "1: \n\t"\ "movq (%0), %%mm0 \n\t"\ "movq 8(%0), %%mm1 \n\t"\ "movq 16(%0), %%mm2 \n\t"\ "movq 24(%0), %%mm3 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 16(%0), 8(%0), (%0), 32(%0), (%1), OP)\ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 8(%0), (%0), (%0), 40(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, (%0), (%0), 8(%0), 48(%0), (%1), OP)\ \ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, (%0), 8(%0), 16(%0), 56(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 8(%0), 16(%0), 24(%0), 64(%0), (%1), OP)\ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 16(%0), 24(%0), 32(%0), 72(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, 24(%0), 32(%0), 40(%0), 80(%0), (%1), OP)\ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, 32(%0), 40(%0), 48(%0), 88(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 40(%0), 48(%0), 56(%0), 96(%0), (%1), OP)\ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 48(%0), 56(%0), 64(%0),104(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, 56(%0), 64(%0), 72(%0),112(%0), (%1), OP)\ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, 64(%0), 72(%0), 80(%0),120(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 72(%0), 80(%0), 88(%0),128(%0), (%1), OP)\ \ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 80(%0), 88(%0), 96(%0),128(%0), (%1, %3), OP)\ "add %4, %1 \n\t" \ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, 88(%0), 96(%0),104(%0),120(%0), (%1), OP)\ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, 96(%0),104(%0),112(%0),112(%0), (%1, %3), OP)\ \ "add $136, %0 \n\t"\ "add %6, %1 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ \ : "+r"(temp_ptr), "+r"(dst), "+g"(count)\ : "r"((x86_reg)dstStride), "r"(2*(x86_reg)dstStride), /*"m"(ff_pw_20), "m"(ff_pw_3),*/ "m"(ROUNDER), "g"(4-14*(x86_reg)dstStride)\ :"memory"\ );\ }\ \ static void OPNAME ## mpeg4_qpel8_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\ uint64_t temp[9*2];\ uint64_t *temp_ptr= temp;\ int count= 9;\ \ /*FIXME unroll */\ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n\t"\ "1: \n\t"\ "movq (%0), %%mm0 \n\t"\ "movq (%0), %%mm1 \n\t"\ "punpcklbw %%mm7, %%mm0 \n\t"\ "punpckhbw %%mm7, %%mm1 \n\t"\ "movq %%mm0, (%1) \n\t"\ "movq %%mm1, 9*8(%1) \n\t"\ "add $8, %1 \n\t"\ "add %3, %0 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ : "+r" (src), "+r" (temp_ptr), "+r"(count)\ : "r" ((x86_reg)srcStride)\ : "memory"\ );\ \ temp_ptr= temp;\ count=2;\ \ /*FIXME reorder for speed */\ __asm__ volatile(\ /*"pxor %%mm7, %%mm7 \n\t"*/\ "1: \n\t"\ "movq (%0), %%mm0 \n\t"\ "movq 8(%0), %%mm1 \n\t"\ "movq 16(%0), %%mm2 \n\t"\ "movq 24(%0), %%mm3 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 16(%0), 8(%0), (%0), 32(%0), (%1), OP)\ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 8(%0), (%0), (%0), 40(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, (%0), (%0), 8(%0), 48(%0), (%1), OP)\ \ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, (%0), 8(%0), 16(%0), 56(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 8(%0), 16(%0), 24(%0), 64(%0), (%1), OP)\ \ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 16(%0), 24(%0), 32(%0), 64(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, 24(%0), 32(%0), 40(%0), 56(%0), (%1), OP)\ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, 32(%0), 40(%0), 48(%0), 48(%0), (%1, %3), OP)\ \ "add $72, %0 \n\t"\ "add %6, %1 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ \ : "+r"(temp_ptr), "+r"(dst), "+g"(count)\ : "r"((x86_reg)dstStride), "r"(2*(x86_reg)dstStride), /*"m"(ff_pw_20), "m"(ff_pw_3),*/ "m"(ROUNDER), "g"(4-6*(x86_reg)dstStride)\ : "memory"\ );\ }\ \ static void OPNAME ## qpel8_mc00_ ## MMX (uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## pixels8_ ## MMX(dst, src, stride, 8);\ }\ \ static void OPNAME ## qpel8_mc10_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[8];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(half, src, 8, stride, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, src, half, stride, stride, 8);\ }\ \ static void OPNAME ## qpel8_mc20_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## mpeg4_qpel8_h_lowpass_ ## MMX(dst, src, stride, stride, 8);\ }\ \ static void OPNAME ## qpel8_mc30_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[8];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(half, src, 8, stride, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, src+1, half, stride, stride, 8);\ }\ \ static void OPNAME ## qpel8_mc01_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[8];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(half, src, 8, stride);\ OPNAME ## pixels8_l2_ ## MMX(dst, src, half, stride, stride, 8);\ }\ \ static void OPNAME ## qpel8_mc02_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## mpeg4_qpel8_v_lowpass_ ## MMX(dst, src, stride, stride);\ }\ \ static void OPNAME ## qpel8_mc03_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[8];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(half, src, 8, stride);\ OPNAME ## pixels8_l2_ ## MMX(dst, src+stride, half, stride, stride, 8);\ }\ static void OPNAME ## qpel8_mc11_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src, halfH, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc31_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src+1, halfH, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc13_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src, halfH, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH+8, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc33_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src+1, halfH, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH+8, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc21_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc23_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH+8, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc12_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src, halfH, 8, stride, 9);\ OPNAME ## mpeg4_qpel8_v_lowpass_ ## MMX(dst, halfH, stride, 8);\ }\ static void OPNAME ## qpel8_mc32_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src+1, halfH, 8, stride, 9);\ OPNAME ## mpeg4_qpel8_v_lowpass_ ## MMX(dst, halfH, stride, 8);\ }\ static void OPNAME ## qpel8_mc22_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[9];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ OPNAME ## mpeg4_qpel8_v_lowpass_ ## MMX(dst, halfH, stride, 8);\ }\ static void OPNAME ## qpel16_mc00_ ## MMX (uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## pixels16_ ## MMX(dst, src, stride, 16);\ }\ \ static void OPNAME ## qpel16_mc10_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[32];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(half, src, 16, stride, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, src, half, stride, stride, 16);\ }\ \ static void OPNAME ## qpel16_mc20_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## mpeg4_qpel16_h_lowpass_ ## MMX(dst, src, stride, stride, 16);\ }\ \ static void OPNAME ## qpel16_mc30_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[32];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(half, src, 16, stride, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, src+1, half, stride, stride, 16);\ }\ \ static void OPNAME ## qpel16_mc01_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[32];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(half, src, 16, stride);\ OPNAME ## pixels16_l2_ ## MMX(dst, src, half, stride, stride, 16);\ }\ \ static void OPNAME ## qpel16_mc02_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## mpeg4_qpel16_v_lowpass_ ## MMX(dst, src, stride, stride);\ }\ \ static void OPNAME ## qpel16_mc03_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[32];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(half, src, 16, stride);\ OPNAME ## pixels16_l2_ ## MMX(dst, src+stride, half, stride, stride, 16);\ }\ static void OPNAME ## qpel16_mc11_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src, halfH, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc31_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src+1, halfH, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc13_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src, halfH, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH+16, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc33_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src+1, halfH, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH+16, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc21_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc23_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH+16, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc12_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[17*2];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src, halfH, 16, stride, 17);\ OPNAME ## mpeg4_qpel16_v_lowpass_ ## MMX(dst, halfH, stride, 16);\ }\ static void OPNAME ## qpel16_mc32_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[17*2];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src+1, halfH, 16, stride, 17);\ OPNAME ## mpeg4_qpel16_v_lowpass_ ## MMX(dst, halfH, stride, 16);\ }\ static void OPNAME ## qpel16_mc22_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[17*2];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ OPNAME ## mpeg4_qpel16_v_lowpass_ ## MMX(dst, halfH, stride, 16);\ } #define PUT_OP(a,b,temp, size) "mov" #size " " #a ", " #b " \n\t" #define AVG_3DNOW_OP(a,b,temp, size) \ "mov" #size " " #b ", " #temp " \n\t"\ "pavgusb " #temp ", " #a " \n\t"\ "mov" #size " " #a ", " #b " \n\t" #define AVG_MMX2_OP(a,b,temp, size) \ "mov" #size " " #b ", " #temp " \n\t"\ "pavgb " #temp ", " #a " \n\t"\ "mov" #size " " #a ", " #b " \n\t" QPEL_BASE(put_ , ff_pw_16, _ , PUT_OP, PUT_OP) QPEL_BASE(avg_ , ff_pw_16, _ , AVG_MMX2_OP, AVG_3DNOW_OP) QPEL_BASE(put_no_rnd_, ff_pw_15, _no_rnd_, PUT_OP, PUT_OP) QPEL_OP(put_ , ff_pw_16, _ , PUT_OP, 3dnow) QPEL_OP(avg_ , ff_pw_16, _ , AVG_3DNOW_OP, 3dnow) QPEL_OP(put_no_rnd_, ff_pw_15, _no_rnd_, PUT_OP, 3dnow) QPEL_OP(put_ , ff_pw_16, _ , PUT_OP, mmx2) QPEL_OP(avg_ , ff_pw_16, _ , AVG_MMX2_OP, mmx2) QPEL_OP(put_no_rnd_, ff_pw_15, _no_rnd_, PUT_OP, mmx2) /***********************************/ /* bilinear qpel: not compliant to any spec, only for -lavdopts fast */ #define QPEL_2TAP_XY(OPNAME, SIZE, MMX, XY, HPEL)\ static void OPNAME ## 2tap_qpel ## SIZE ## _mc ## XY ## _ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## pixels ## SIZE ## HPEL(dst, src, stride, SIZE);\ } #define QPEL_2TAP_L3(OPNAME, SIZE, MMX, XY, S0, S1, S2)\ static void OPNAME ## 2tap_qpel ## SIZE ## _mc ## XY ## _ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## 2tap_qpel ## SIZE ## _l3_ ## MMX(dst, src+S0, stride, SIZE, S1, S2);\ } #define QPEL_2TAP(OPNAME, SIZE, MMX)\ QPEL_2TAP_XY(OPNAME, SIZE, MMX, 20, _x2_ ## MMX)\ QPEL_2TAP_XY(OPNAME, SIZE, MMX, 02, _y2_ ## MMX)\ QPEL_2TAP_XY(OPNAME, SIZE, MMX, 22, _xy2_mmx)\ static const qpel_mc_func OPNAME ## 2tap_qpel ## SIZE ## _mc00_ ## MMX =\ OPNAME ## qpel ## SIZE ## _mc00_ ## MMX;\ static const qpel_mc_func OPNAME ## 2tap_qpel ## SIZE ## _mc21_ ## MMX =\ OPNAME ## 2tap_qpel ## SIZE ## _mc20_ ## MMX;\ static const qpel_mc_func OPNAME ## 2tap_qpel ## SIZE ## _mc12_ ## MMX =\ OPNAME ## 2tap_qpel ## SIZE ## _mc02_ ## MMX;\ static void OPNAME ## 2tap_qpel ## SIZE ## _mc32_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## pixels ## SIZE ## _y2_ ## MMX(dst, src+1, stride, SIZE);\ }\ static void OPNAME ## 2tap_qpel ## SIZE ## _mc23_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## pixels ## SIZE ## _x2_ ## MMX(dst, src+stride, stride, SIZE);\ }\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 10, 0, 1, 0)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 30, 1, -1, 0)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 01, 0, stride, 0)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 03, stride, -stride, 0)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 11, 0, stride, 1)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 31, 1, stride, -1)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 13, stride, -stride, 1)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 33, stride+1, -stride, -1)\ QPEL_2TAP(put_, 16, mmx2) QPEL_2TAP(avg_, 16, mmx2) QPEL_2TAP(put_, 8, mmx2) QPEL_2TAP(avg_, 8, mmx2) QPEL_2TAP(put_, 16, 3dnow) QPEL_2TAP(avg_, 16, 3dnow) QPEL_2TAP(put_, 8, 3dnow) QPEL_2TAP(avg_, 8, 3dnow) #if 0 static void just_return(void) { return; } #endif static void gmc_mmx(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int oy, int dxx, int dxy, int dyx, int dyy, int shift, int r, int width, int height){ const int w = 8; const int ix = ox>>(16+shift); const int iy = oy>>(16+shift); const int oxs = ox>>4; const int oys = oy>>4; const int dxxs = dxx>>4; const int dxys = dxy>>4; const int dyxs = dyx>>4; const int dyys = dyy>>4; const uint16_t r4[4] = {r,r,r,r}; const uint16_t dxy4[4] = {dxys,dxys,dxys,dxys}; const uint16_t dyy4[4] = {dyys,dyys,dyys,dyys}; const uint64_t shift2 = 2*shift; uint8_t edge_buf[(h+1)*stride]; int x, y; const int dxw = (dxx-(1<<(16+shift)))*(w-1); const int dyh = (dyy-(1<<(16+shift)))*(h-1); const int dxh = dxy*(h-1); const int dyw = dyx*(w-1); if( // non-constant fullpel offset (3% of blocks) ((ox^(ox+dxw)) | (ox^(ox+dxh)) | (ox^(ox+dxw+dxh)) | (oy^(oy+dyw)) | (oy^(oy+dyh)) | (oy^(oy+dyw+dyh))) >> (16+shift) // uses more than 16 bits of subpel mv (only at huge resolution) || (dxx|dxy|dyx|dyy)&15 ) { //FIXME could still use mmx for some of the rows ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy, shift, r, width, height); return; } src += ix + iy*stride; if( (unsigned)ix >= width-w || (unsigned)iy >= height-h ) { ff_emulated_edge_mc(edge_buf, src, stride, w+1, h+1, ix, iy, width, height); src = edge_buf; } __asm__ volatile( "movd %0, %%mm6 \n\t" "pxor %%mm7, %%mm7 \n\t" "punpcklwd %%mm6, %%mm6 \n\t" "punpcklwd %%mm6, %%mm6 \n\t" :: "r"(1<<shift) ); for(x=0; x<w; x+=4){ uint16_t dx4[4] = { oxs - dxys + dxxs*(x+0), oxs - dxys + dxxs*(x+1), oxs - dxys + dxxs*(x+2), oxs - dxys + dxxs*(x+3) }; uint16_t dy4[4] = { oys - dyys + dyxs*(x+0), oys - dyys + dyxs*(x+1), oys - dyys + dyxs*(x+2), oys - dyys + dyxs*(x+3) }; for(y=0; y<h; y++){ __asm__ volatile( "movq %0, %%mm4 \n\t" "movq %1, %%mm5 \n\t" "paddw %2, %%mm4 \n\t" "paddw %3, %%mm5 \n\t" "movq %%mm4, %0 \n\t" "movq %%mm5, %1 \n\t" "psrlw $12, %%mm4 \n\t" "psrlw $12, %%mm5 \n\t" : "+m"(*dx4), "+m"(*dy4) : "m"(*dxy4), "m"(*dyy4) ); __asm__ volatile( "movq %%mm6, %%mm2 \n\t" "movq %%mm6, %%mm1 \n\t" "psubw %%mm4, %%mm2 \n\t" "psubw %%mm5, %%mm1 \n\t" "movq %%mm2, %%mm0 \n\t" "movq %%mm4, %%mm3 \n\t" "pmullw %%mm1, %%mm0 \n\t" // (s-dx)*(s-dy) "pmullw %%mm5, %%mm3 \n\t" // dx*dy "pmullw %%mm5, %%mm2 \n\t" // (s-dx)*dy "pmullw %%mm4, %%mm1 \n\t" // dx*(s-dy) "movd %4, %%mm5 \n\t" "movd %3, %%mm4 \n\t" "punpcklbw %%mm7, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "pmullw %%mm5, %%mm3 \n\t" // src[1,1] * dx*dy "pmullw %%mm4, %%mm2 \n\t" // src[0,1] * (s-dx)*dy "movd %2, %%mm5 \n\t" "movd %1, %%mm4 \n\t" "punpcklbw %%mm7, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "pmullw %%mm5, %%mm1 \n\t" // src[1,0] * dx*(s-dy) "pmullw %%mm4, %%mm0 \n\t" // src[0,0] * (s-dx)*(s-dy) "paddw %5, %%mm1 \n\t" "paddw %%mm3, %%mm2 \n\t" "paddw %%mm1, %%mm0 \n\t" "paddw %%mm2, %%mm0 \n\t" "psrlw %6, %%mm0 \n\t" "packuswb %%mm0, %%mm0 \n\t" "movd %%mm0, %0 \n\t" : "=m"(dst[x+y*stride]) : "m"(src[0]), "m"(src[1]), "m"(src[stride]), "m"(src[stride+1]), "m"(*r4), "m"(shift2) ); src += stride; } src += 4-h*stride; } } #define PREFETCH(name, op) \ static void name(void *mem, int stride, int h){\ const uint8_t *p= mem;\ do{\ __asm__ volatile(#op" %0" :: "m"(*p));\ p+= stride;\ }while(--h);\ } PREFETCH(prefetch_mmx2, prefetcht0) PREFETCH(prefetch_3dnow, prefetch) #undef PREFETCH #include "h264dsp_mmx.c" #include "rv40dsp_mmx.c" /* CAVS specific */ void ff_put_cavs_qpel8_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride) { put_pixels8_mmx(dst, src, stride, 8); } void ff_avg_cavs_qpel8_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride) { avg_pixels8_mmx(dst, src, stride, 8); } void ff_put_cavs_qpel16_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride) { put_pixels16_mmx(dst, src, stride, 16); } void ff_avg_cavs_qpel16_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride) { avg_pixels16_mmx(dst, src, stride, 16); } /* VC1 specific */ void ff_put_vc1_mspel_mc00_mmx(uint8_t *dst, const uint8_t *src, int stride, int rnd) { put_pixels8_mmx(dst, src, stride, 8); } void ff_avg_vc1_mspel_mc00_mmx2(uint8_t *dst, const uint8_t *src, int stride, int rnd) { avg_pixels8_mmx2(dst, src, stride, 8); } /* XXX: those functions should be suppressed ASAP when all IDCTs are converted */ #if CONFIG_GPL static void ff_libmpeg2mmx_idct_put(uint8_t *dest, int line_size, DCTELEM *block) { ff_mmx_idct (block); put_pixels_clamped_mmx(block, dest, line_size); } static void ff_libmpeg2mmx_idct_add(uint8_t *dest, int line_size, DCTELEM *block) { ff_mmx_idct (block); add_pixels_clamped_mmx(block, dest, line_size); } static void ff_libmpeg2mmx2_idct_put(uint8_t *dest, int line_size, DCTELEM *block) { ff_mmxext_idct (block); put_pixels_clamped_mmx(block, dest, line_size); } static void ff_libmpeg2mmx2_idct_add(uint8_t *dest, int line_size, DCTELEM *block) { ff_mmxext_idct (block); add_pixels_clamped_mmx(block, dest, line_size); } #endif static void ff_idct_xvid_mmx_put(uint8_t *dest, int line_size, DCTELEM *block) { ff_idct_xvid_mmx (block); put_pixels_clamped_mmx(block, dest, line_size); } static void ff_idct_xvid_mmx_add(uint8_t *dest, int line_size, DCTELEM *block) { ff_idct_xvid_mmx (block); add_pixels_clamped_mmx(block, dest, line_size); } static void ff_idct_xvid_mmx2_put(uint8_t *dest, int line_size, DCTELEM *block) { ff_idct_xvid_mmx2 (block); put_pixels_clamped_mmx(block, dest, line_size); } static void ff_idct_xvid_mmx2_add(uint8_t *dest, int line_size, DCTELEM *block) { ff_idct_xvid_mmx2 (block); add_pixels_clamped_mmx(block, dest, line_size); } static void vorbis_inverse_coupling_3dnow(float *mag, float *ang, int blocksize) { int i; __asm__ volatile("pxor %%mm7, %%mm7":); for(i=0; i<blocksize; i+=2) { __asm__ volatile( "movq %0, %%mm0 \n\t" "movq %1, %%mm1 \n\t" "movq %%mm0, %%mm2 \n\t" "movq %%mm1, %%mm3 \n\t" "pfcmpge %%mm7, %%mm2 \n\t" // m <= 0.0 "pfcmpge %%mm7, %%mm3 \n\t" // a <= 0.0 "pslld $31, %%mm2 \n\t" // keep only the sign bit "pxor %%mm2, %%mm1 \n\t" "movq %%mm3, %%mm4 \n\t" "pand %%mm1, %%mm3 \n\t" "pandn %%mm1, %%mm4 \n\t" "pfadd %%mm0, %%mm3 \n\t" // a = m + ((a<0) & (a ^ sign(m))) "pfsub %%mm4, %%mm0 \n\t" // m = m + ((a>0) & (a ^ sign(m))) "movq %%mm3, %1 \n\t" "movq %%mm0, %0 \n\t" :"+m"(mag[i]), "+m"(ang[i]) ::"memory" ); } __asm__ volatile("femms"); } static void vorbis_inverse_coupling_sse(float *mag, float *ang, int blocksize) { int i; __asm__ volatile( "movaps %0, %%xmm5 \n\t" ::"m"(ff_pdw_80000000[0]) ); for(i=0; i<blocksize; i+=4) { __asm__ volatile( "movaps %0, %%xmm0 \n\t" "movaps %1, %%xmm1 \n\t" "xorps %%xmm2, %%xmm2 \n\t" "xorps %%xmm3, %%xmm3 \n\t" "cmpleps %%xmm0, %%xmm2 \n\t" // m <= 0.0 "cmpleps %%xmm1, %%xmm3 \n\t" // a <= 0.0 "andps %%xmm5, %%xmm2 \n\t" // keep only the sign bit "xorps %%xmm2, %%xmm1 \n\t" "movaps %%xmm3, %%xmm4 \n\t" "andps %%xmm1, %%xmm3 \n\t" "andnps %%xmm1, %%xmm4 \n\t" "addps %%xmm0, %%xmm3 \n\t" // a = m + ((a<0) & (a ^ sign(m))) "subps %%xmm4, %%xmm0 \n\t" // m = m + ((a>0) & (a ^ sign(m))) "movaps %%xmm3, %1 \n\t" "movaps %%xmm0, %0 \n\t" :"+m"(mag[i]), "+m"(ang[i]) ::"memory" ); } } #define IF1(x) x #define IF0(x) #define MIX5(mono,stereo)\ __asm__ volatile(\ "movss 0(%2), %%xmm5 \n"\ "movss 8(%2), %%xmm6 \n"\ "movss 24(%2), %%xmm7 \n"\ "shufps $0, %%xmm5, %%xmm5 \n"\ "shufps $0, %%xmm6, %%xmm6 \n"\ "shufps $0, %%xmm7, %%xmm7 \n"\ "1: \n"\ "movaps (%0,%1), %%xmm0 \n"\ "movaps 0x400(%0,%1), %%xmm1 \n"\ "movaps 0x800(%0,%1), %%xmm2 \n"\ "movaps 0xc00(%0,%1), %%xmm3 \n"\ "movaps 0x1000(%0,%1), %%xmm4 \n"\ "mulps %%xmm5, %%xmm0 \n"\ "mulps %%xmm6, %%xmm1 \n"\ "mulps %%xmm5, %%xmm2 \n"\ "mulps %%xmm7, %%xmm3 \n"\ "mulps %%xmm7, %%xmm4 \n"\ stereo("addps %%xmm1, %%xmm0 \n")\ "addps %%xmm1, %%xmm2 \n"\ "addps %%xmm3, %%xmm0 \n"\ "addps %%xmm4, %%xmm2 \n"\ mono("addps %%xmm2, %%xmm0 \n")\ "movaps %%xmm0, (%0,%1) \n"\ stereo("movaps %%xmm2, 0x400(%0,%1) \n")\ "add $16, %0 \n"\ "jl 1b \n"\ :"+&r"(i)\ :"r"(samples[0]+len), "r"(matrix)\ :"memory"\ ); #define MIX_MISC(stereo)\ __asm__ volatile(\ "1: \n"\ "movaps (%3,%0), %%xmm0 \n"\ stereo("movaps %%xmm0, %%xmm1 \n")\ "mulps %%xmm6, %%xmm0 \n"\ stereo("mulps %%xmm7, %%xmm1 \n")\ "lea 1024(%3,%0), %1 \n"\ "mov %5, %2 \n"\ "2: \n"\ "movaps (%1), %%xmm2 \n"\ stereo("movaps %%xmm2, %%xmm3 \n")\ "mulps (%4,%2), %%xmm2 \n"\ stereo("mulps 16(%4,%2), %%xmm3 \n")\ "addps %%xmm2, %%xmm0 \n"\ stereo("addps %%xmm3, %%xmm1 \n")\ "add $1024, %1 \n"\ "add $32, %2 \n"\ "jl 2b \n"\ "movaps %%xmm0, (%3,%0) \n"\ stereo("movaps %%xmm1, 1024(%3,%0) \n")\ "add $16, %0 \n"\ "jl 1b \n"\ :"+&r"(i), "=&r"(j), "=&r"(k)\ :"r"(samples[0]+len), "r"(matrix_simd+in_ch), "g"((intptr_t)-32*(in_ch-1))\ :"memory"\ ); static void ac3_downmix_sse(float (*samples)[256], float (*matrix)[2], int out_ch, int in_ch, int len) { int (*matrix_cmp)[2] = (int(*)[2])matrix; intptr_t i,j,k; i = -len*sizeof(float); if(in_ch == 5 && out_ch == 2 && !(matrix_cmp[0][1]|matrix_cmp[2][0]|matrix_cmp[3][1]|matrix_cmp[4][0]|(matrix_cmp[1][0]^matrix_cmp[1][1])|(matrix_cmp[0][0]^matrix_cmp[2][1]))) { MIX5(IF0,IF1); } else if(in_ch == 5 && out_ch == 1 && matrix_cmp[0][0]==matrix_cmp[2][0] && matrix_cmp[3][0]==matrix_cmp[4][0]) { MIX5(IF1,IF0); } else { DECLARE_ALIGNED(16, float, matrix_simd)[in_ch][2][4]; j = 2*in_ch*sizeof(float); __asm__ volatile( "1: \n" "sub $8, %0 \n" "movss (%2,%0), %%xmm6 \n" "movss 4(%2,%0), %%xmm7 \n" "shufps $0, %%xmm6, %%xmm6 \n" "shufps $0, %%xmm7, %%xmm7 \n" "movaps %%xmm6, (%1,%0,4) \n" "movaps %%xmm7, 16(%1,%0,4) \n" "jg 1b \n" :"+&r"(j) :"r"(matrix_simd), "r"(matrix) :"memory" ); if(out_ch == 2) { MIX_MISC(IF1); } else { MIX_MISC(IF0); } } } static void vector_fmul_3dnow(float *dst, const float *src, int len){ x86_reg i = (len-4)*4; __asm__ volatile( "1: \n\t" "movq (%1,%0), %%mm0 \n\t" "movq 8(%1,%0), %%mm1 \n\t" "pfmul (%2,%0), %%mm0 \n\t" "pfmul 8(%2,%0), %%mm1 \n\t" "movq %%mm0, (%1,%0) \n\t" "movq %%mm1, 8(%1,%0) \n\t" "sub $16, %0 \n\t" "jge 1b \n\t" "femms \n\t" :"+r"(i) :"r"(dst), "r"(src) :"memory" ); } static void vector_fmul_sse(float *dst, const float *src, int len){ x86_reg i = (len-8)*4; __asm__ volatile( "1: \n\t" "movaps (%1,%0), %%xmm0 \n\t" "movaps 16(%1,%0), %%xmm1 \n\t" "mulps (%2,%0), %%xmm0 \n\t" "mulps 16(%2,%0), %%xmm1 \n\t" "movaps %%xmm0, (%1,%0) \n\t" "movaps %%xmm1, 16(%1,%0) \n\t" "sub $32, %0 \n\t" "jge 1b \n\t" :"+r"(i) :"r"(dst), "r"(src) :"memory" ); } static void vector_fmul_reverse_3dnow2(float *dst, const float *src0, const float *src1, int len){ x86_reg i = len*4-16; __asm__ volatile( "1: \n\t" "pswapd 8(%1), %%mm0 \n\t" "pswapd (%1), %%mm1 \n\t" "pfmul (%3,%0), %%mm0 \n\t" "pfmul 8(%3,%0), %%mm1 \n\t" "movq %%mm0, (%2,%0) \n\t" "movq %%mm1, 8(%2,%0) \n\t" "add $16, %1 \n\t" "sub $16, %0 \n\t" "jge 1b \n\t" :"+r"(i), "+r"(src1) :"r"(dst), "r"(src0) ); __asm__ volatile("femms"); } static void vector_fmul_reverse_sse(float *dst, const float *src0, const float *src1, int len){ x86_reg i = len*4-32; __asm__ volatile( "1: \n\t" "movaps 16(%1), %%xmm0 \n\t" "movaps (%1), %%xmm1 \n\t" "shufps $0x1b, %%xmm0, %%xmm0 \n\t" "shufps $0x1b, %%xmm1, %%xmm1 \n\t" "mulps (%3,%0), %%xmm0 \n\t" "mulps 16(%3,%0), %%xmm1 \n\t" "movaps %%xmm0, (%2,%0) \n\t" "movaps %%xmm1, 16(%2,%0) \n\t" "add $32, %1 \n\t" "sub $32, %0 \n\t" "jge 1b \n\t" :"+r"(i), "+r"(src1) :"r"(dst), "r"(src0) ); } static void vector_fmul_add_3dnow(float *dst, const float *src0, const float *src1, const float *src2, int len){ x86_reg i = (len-4)*4; __asm__ volatile( "1: \n\t" "movq (%2,%0), %%mm0 \n\t" "movq 8(%2,%0), %%mm1 \n\t" "pfmul (%3,%0), %%mm0 \n\t" "pfmul 8(%3,%0), %%mm1 \n\t" "pfadd (%4,%0), %%mm0 \n\t" "pfadd 8(%4,%0), %%mm1 \n\t" "movq %%mm0, (%1,%0) \n\t" "movq %%mm1, 8(%1,%0) \n\t" "sub $16, %0 \n\t" "jge 1b \n\t" :"+r"(i) :"r"(dst), "r"(src0), "r"(src1), "r"(src2) :"memory" ); __asm__ volatile("femms"); } static void vector_fmul_add_sse(float *dst, const float *src0, const float *src1, const float *src2, int len){ x86_reg i = (len-8)*4; __asm__ volatile( "1: \n\t" "movaps (%2,%0), %%xmm0 \n\t" "movaps 16(%2,%0), %%xmm1 \n\t" "mulps (%3,%0), %%xmm0 \n\t" "mulps 16(%3,%0), %%xmm1 \n\t" "addps (%4,%0), %%xmm0 \n\t" "addps 16(%4,%0), %%xmm1 \n\t" "movaps %%xmm0, (%1,%0) \n\t" "movaps %%xmm1, 16(%1,%0) \n\t" "sub $32, %0 \n\t" "jge 1b \n\t" :"+r"(i) :"r"(dst), "r"(src0), "r"(src1), "r"(src2) :"memory" ); } static void vector_fmul_window_3dnow2(float *dst, const float *src0, const float *src1, const float *win, float add_bias, int len){ #if HAVE_6REGS if(add_bias == 0){ x86_reg i = -len*4; x86_reg j = len*4-8; __asm__ volatile( "1: \n" "pswapd (%5,%1), %%mm1 \n" "movq (%5,%0), %%mm0 \n" "pswapd (%4,%1), %%mm5 \n" "movq (%3,%0), %%mm4 \n" "movq %%mm0, %%mm2 \n" "movq %%mm1, %%mm3 \n" "pfmul %%mm4, %%mm2 \n" // src0[len+i]*win[len+i] "pfmul %%mm5, %%mm3 \n" // src1[ j]*win[len+j] "pfmul %%mm4, %%mm1 \n" // src0[len+i]*win[len+j] "pfmul %%mm5, %%mm0 \n" // src1[ j]*win[len+i] "pfadd %%mm3, %%mm2 \n" "pfsub %%mm0, %%mm1 \n" "pswapd %%mm2, %%mm2 \n" "movq %%mm1, (%2,%0) \n" "movq %%mm2, (%2,%1) \n" "sub $8, %1 \n" "add $8, %0 \n" "jl 1b \n" "femms \n" :"+r"(i), "+r"(j) :"r"(dst+len), "r"(src0+len), "r"(src1), "r"(win+len) ); }else #endif ff_vector_fmul_window_c(dst, src0, src1, win, add_bias, len); } static void vector_fmul_window_sse(float *dst, const float *src0, const float *src1, const float *win, float add_bias, int len){ #if HAVE_6REGS if(add_bias == 0){ x86_reg i = -len*4; x86_reg j = len*4-16; __asm__ volatile( "1: \n" "movaps (%5,%1), %%xmm1 \n" "movaps (%5,%0), %%xmm0 \n" "movaps (%4,%1), %%xmm5 \n" "movaps (%3,%0), %%xmm4 \n" "shufps $0x1b, %%xmm1, %%xmm1 \n" "shufps $0x1b, %%xmm5, %%xmm5 \n" "movaps %%xmm0, %%xmm2 \n" "movaps %%xmm1, %%xmm3 \n" "mulps %%xmm4, %%xmm2 \n" // src0[len+i]*win[len+i] "mulps %%xmm5, %%xmm3 \n" // src1[ j]*win[len+j] "mulps %%xmm4, %%xmm1 \n" // src0[len+i]*win[len+j] "mulps %%xmm5, %%xmm0 \n" // src1[ j]*win[len+i] "addps %%xmm3, %%xmm2 \n" "subps %%xmm0, %%xmm1 \n" "shufps $0x1b, %%xmm2, %%xmm2 \n" "movaps %%xmm1, (%2,%0) \n" "movaps %%xmm2, (%2,%1) \n" "sub $16, %1 \n" "add $16, %0 \n" "jl 1b \n" :"+r"(i), "+r"(j) :"r"(dst+len), "r"(src0+len), "r"(src1), "r"(win+len) ); }else #endif ff_vector_fmul_window_c(dst, src0, src1, win, add_bias, len); } static void int32_to_float_fmul_scalar_sse(float *dst, const int *src, float mul, int len) { x86_reg i = -4*len; __asm__ volatile( "movss %3, %%xmm4 \n" "shufps $0, %%xmm4, %%xmm4 \n" "1: \n" "cvtpi2ps (%2,%0), %%xmm0 \n" "cvtpi2ps 8(%2,%0), %%xmm1 \n" "cvtpi2ps 16(%2,%0), %%xmm2 \n" "cvtpi2ps 24(%2,%0), %%xmm3 \n" "movlhps %%xmm1, %%xmm0 \n" "movlhps %%xmm3, %%xmm2 \n" "mulps %%xmm4, %%xmm0 \n" "mulps %%xmm4, %%xmm2 \n" "movaps %%xmm0, (%1,%0) \n" "movaps %%xmm2, 16(%1,%0) \n" "add $32, %0 \n" "jl 1b \n" :"+r"(i) :"r"(dst+len), "r"(src+len), "m"(mul) ); } static void int32_to_float_fmul_scalar_sse2(float *dst, const int *src, float mul, int len) { x86_reg i = -4*len; __asm__ volatile( "movss %3, %%xmm4 \n" "shufps $0, %%xmm4, %%xmm4 \n" "1: \n" "cvtdq2ps (%2,%0), %%xmm0 \n" "cvtdq2ps 16(%2,%0), %%xmm1 \n" "mulps %%xmm4, %%xmm0 \n" "mulps %%xmm4, %%xmm1 \n" "movaps %%xmm0, (%1,%0) \n" "movaps %%xmm1, 16(%1,%0) \n" "add $32, %0 \n" "jl 1b \n" :"+r"(i) :"r"(dst+len), "r"(src+len), "m"(mul) ); } static void vector_clipf_sse(float *dst, const float *src, float min, float max, int len) { x86_reg i = (len-16)*4; __asm__ volatile( "movss %3, %%xmm4 \n" "movss %4, %%xmm5 \n" "shufps $0, %%xmm4, %%xmm4 \n" "shufps $0, %%xmm5, %%xmm5 \n" "1: \n\t" "movaps (%2,%0), %%xmm0 \n\t" // 3/1 on intel "movaps 16(%2,%0), %%xmm1 \n\t" "movaps 32(%2,%0), %%xmm2 \n\t" "movaps 48(%2,%0), %%xmm3 \n\t" "maxps %%xmm4, %%xmm0 \n\t" "maxps %%xmm4, %%xmm1 \n\t" "maxps %%xmm4, %%xmm2 \n\t" "maxps %%xmm4, %%xmm3 \n\t" "minps %%xmm5, %%xmm0 \n\t" "minps %%xmm5, %%xmm1 \n\t" "minps %%xmm5, %%xmm2 \n\t" "minps %%xmm5, %%xmm3 \n\t" "movaps %%xmm0, (%1,%0) \n\t" "movaps %%xmm1, 16(%1,%0) \n\t" "movaps %%xmm2, 32(%1,%0) \n\t" "movaps %%xmm3, 48(%1,%0) \n\t" "sub $64, %0 \n\t" "jge 1b \n\t" :"+&r"(i) :"r"(dst), "r"(src), "m"(min), "m"(max) :"memory" ); } static void float_to_int16_3dnow(int16_t *dst, const float *src, long len){ x86_reg reglen = len; // not bit-exact: pf2id uses different rounding than C and SSE __asm__ volatile( "add %0 , %0 \n\t" "lea (%2,%0,2) , %2 \n\t" "add %0 , %1 \n\t" "neg %0 \n\t" "1: \n\t" "pf2id (%2,%0,2) , %%mm0 \n\t" "pf2id 8(%2,%0,2) , %%mm1 \n\t" "pf2id 16(%2,%0,2) , %%mm2 \n\t" "pf2id 24(%2,%0,2) , %%mm3 \n\t" "packssdw %%mm1 , %%mm0 \n\t" "packssdw %%mm3 , %%mm2 \n\t" "movq %%mm0 , (%1,%0) \n\t" "movq %%mm2 , 8(%1,%0) \n\t" "add $16 , %0 \n\t" " js 1b \n\t" "femms \n\t" :"+r"(reglen), "+r"(dst), "+r"(src) ); } static void float_to_int16_sse(int16_t *dst, const float *src, long len){ x86_reg reglen = len; __asm__ volatile( "add %0 , %0 \n\t" "lea (%2,%0,2) , %2 \n\t" "add %0 , %1 \n\t" "neg %0 \n\t" "1: \n\t" "cvtps2pi (%2,%0,2) , %%mm0 \n\t" "cvtps2pi 8(%2,%0,2) , %%mm1 \n\t" "cvtps2pi 16(%2,%0,2) , %%mm2 \n\t" "cvtps2pi 24(%2,%0,2) , %%mm3 \n\t" "packssdw %%mm1 , %%mm0 \n\t" "packssdw %%mm3 , %%mm2 \n\t" "movq %%mm0 , (%1,%0) \n\t" "movq %%mm2 , 8(%1,%0) \n\t" "add $16 , %0 \n\t" " js 1b \n\t" "emms \n\t" :"+r"(reglen), "+r"(dst), "+r"(src) ); } static void float_to_int16_sse2(int16_t *dst, const float *src, long len){ x86_reg reglen = len; __asm__ volatile( "add %0 , %0 \n\t" "lea (%2,%0,2) , %2 \n\t" "add %0 , %1 \n\t" "neg %0 \n\t" "1: \n\t" "cvtps2dq (%2,%0,2) , %%xmm0 \n\t" "cvtps2dq 16(%2,%0,2) , %%xmm1 \n\t" "packssdw %%xmm1 , %%xmm0 \n\t" "movdqa %%xmm0 , (%1,%0) \n\t" "add $16 , %0 \n\t" " js 1b \n\t" :"+r"(reglen), "+r"(dst), "+r"(src) ); } void ff_float_to_int16_interleave6_sse(int16_t *dst, const float **src, int len); void ff_float_to_int16_interleave6_3dnow(int16_t *dst, const float **src, int len); void ff_float_to_int16_interleave6_3dn2(int16_t *dst, const float **src, int len); int32_t ff_scalarproduct_int16_mmx2(int16_t *v1, int16_t *v2, int order, int shift); int32_t ff_scalarproduct_int16_sse2(int16_t *v1, int16_t *v2, int order, int shift); int32_t ff_scalarproduct_and_madd_int16_mmx2(int16_t *v1, int16_t *v2, int16_t *v3, int order, int mul); int32_t ff_scalarproduct_and_madd_int16_sse2(int16_t *v1, int16_t *v2, int16_t *v3, int order, int mul); int32_t ff_scalarproduct_and_madd_int16_ssse3(int16_t *v1, int16_t *v2, int16_t *v3, int order, int mul); void ff_add_hfyu_median_prediction_mmx2(uint8_t *dst, const uint8_t *top, const uint8_t *diff, int w, int *left, int *left_top); int ff_add_hfyu_left_prediction_ssse3(uint8_t *dst, const uint8_t *src, int w, int left); int ff_add_hfyu_left_prediction_sse4(uint8_t *dst, const uint8_t *src, int w, int left); void ff_x264_deblock_v_luma_sse2(uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0); void ff_x264_deblock_h_luma_sse2(uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0); void ff_x264_deblock_h_luma_intra_mmxext(uint8_t *pix, int stride, int alpha, int beta); void ff_x264_deblock_v_luma_intra_sse2(uint8_t *pix, int stride, int alpha, int beta); void ff_x264_deblock_h_luma_intra_sse2(uint8_t *pix, int stride, int alpha, int beta); #if HAVE_YASM && ARCH_X86_32 void ff_x264_deblock_v8_luma_intra_mmxext(uint8_t *pix, int stride, int alpha, int beta); static void ff_x264_deblock_v_luma_intra_mmxext(uint8_t *pix, int stride, int alpha, int beta) { ff_x264_deblock_v8_luma_intra_mmxext(pix+0, stride, alpha, beta); ff_x264_deblock_v8_luma_intra_mmxext(pix+8, stride, alpha, beta); } #elif !HAVE_YASM #define ff_float_to_int16_interleave6_sse(a,b,c) float_to_int16_interleave_misc_sse(a,b,c,6) #define ff_float_to_int16_interleave6_3dnow(a,b,c) float_to_int16_interleave_misc_3dnow(a,b,c,6) #define ff_float_to_int16_interleave6_3dn2(a,b,c) float_to_int16_interleave_misc_3dnow(a,b,c,6) #endif #define ff_float_to_int16_interleave6_sse2 ff_float_to_int16_interleave6_sse #define FLOAT_TO_INT16_INTERLEAVE(cpu, body) \ /* gcc pessimizes register allocation if this is in the same function as float_to_int16_interleave_sse2*/\ static av_noinline void float_to_int16_interleave_misc_##cpu(int16_t *dst, const float **src, long len, int channels){\ DECLARE_ALIGNED(16, int16_t, tmp)[len];\ int i,j,c;\ for(c=0; c<channels; c++){\ float_to_int16_##cpu(tmp, src[c], len);\ for(i=0, j=c; i<len; i++, j+=channels)\ dst[j] = tmp[i];\ }\ }\ \ static void float_to_int16_interleave_##cpu(int16_t *dst, const float **src, long len, int channels){\ if(channels==1)\ float_to_int16_##cpu(dst, src[0], len);\ else if(channels==2){\ x86_reg reglen = len; \ const float *src0 = src[0];\ const float *src1 = src[1];\ __asm__ volatile(\ "shl $2, %0 \n"\ "add %0, %1 \n"\ "add %0, %2 \n"\ "add %0, %3 \n"\ "neg %0 \n"\ body\ :"+r"(reglen), "+r"(dst), "+r"(src0), "+r"(src1)\ );\ }else if(channels==6){\ ff_float_to_int16_interleave6_##cpu(dst, src, len);\ }else\ float_to_int16_interleave_misc_##cpu(dst, src, len, channels);\ } FLOAT_TO_INT16_INTERLEAVE(3dnow, "1: \n" "pf2id (%2,%0), %%mm0 \n" "pf2id 8(%2,%0), %%mm1 \n" "pf2id (%3,%0), %%mm2 \n" "pf2id 8(%3,%0), %%mm3 \n" "packssdw %%mm1, %%mm0 \n" "packssdw %%mm3, %%mm2 \n" "movq %%mm0, %%mm1 \n" "punpcklwd %%mm2, %%mm0 \n" "punpckhwd %%mm2, %%mm1 \n" "movq %%mm0, (%1,%0)\n" "movq %%mm1, 8(%1,%0)\n" "add $16, %0 \n" "js 1b \n" "femms \n" ) FLOAT_TO_INT16_INTERLEAVE(sse, "1: \n" "cvtps2pi (%2,%0), %%mm0 \n" "cvtps2pi 8(%2,%0), %%mm1 \n" "cvtps2pi (%3,%0), %%mm2 \n" "cvtps2pi 8(%3,%0), %%mm3 \n" "packssdw %%mm1, %%mm0 \n" "packssdw %%mm3, %%mm2 \n" "movq %%mm0, %%mm1 \n" "punpcklwd %%mm2, %%mm0 \n" "punpckhwd %%mm2, %%mm1 \n" "movq %%mm0, (%1,%0)\n" "movq %%mm1, 8(%1,%0)\n" "add $16, %0 \n" "js 1b \n" "emms \n" ) FLOAT_TO_INT16_INTERLEAVE(sse2, "1: \n" "cvtps2dq (%2,%0), %%xmm0 \n" "cvtps2dq (%3,%0), %%xmm1 \n" "packssdw %%xmm1, %%xmm0 \n" "movhlps %%xmm0, %%xmm1 \n" "punpcklwd %%xmm1, %%xmm0 \n" "movdqa %%xmm0, (%1,%0) \n" "add $16, %0 \n" "js 1b \n" ) static void float_to_int16_interleave_3dn2(int16_t *dst, const float **src, long len, int channels){ if(channels==6) ff_float_to_int16_interleave6_3dn2(dst, src, len); else float_to_int16_interleave_3dnow(dst, src, len, channels); } float ff_scalarproduct_float_sse(const float *v1, const float *v2, int order); void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx) { mm_flags = mm_support(); if (avctx->dsp_mask) { if (avctx->dsp_mask & FF_MM_FORCE) mm_flags |= (avctx->dsp_mask & 0xffff); else mm_flags &= ~(avctx->dsp_mask & 0xffff); } #if 0 av_log(avctx, AV_LOG_INFO, "libavcodec: CPU flags:"); if (mm_flags & FF_MM_MMX) av_log(avctx, AV_LOG_INFO, " mmx"); if (mm_flags & FF_MM_MMX2) av_log(avctx, AV_LOG_INFO, " mmx2"); if (mm_flags & FF_MM_3DNOW) av_log(avctx, AV_LOG_INFO, " 3dnow"); if (mm_flags & FF_MM_SSE) av_log(avctx, AV_LOG_INFO, " sse"); if (mm_flags & FF_MM_SSE2) av_log(avctx, AV_LOG_INFO, " sse2"); av_log(avctx, AV_LOG_INFO, "\n"); #endif if (mm_flags & FF_MM_MMX) { const int idct_algo= avctx->idct_algo; if(avctx->lowres==0){ if(idct_algo==FF_IDCT_AUTO || idct_algo==FF_IDCT_SIMPLEMMX){ c->idct_put= ff_simple_idct_put_mmx; c->idct_add= ff_simple_idct_add_mmx; c->idct = ff_simple_idct_mmx; c->idct_permutation_type= FF_SIMPLE_IDCT_PERM; #if CONFIG_GPL }else if(idct_algo==FF_IDCT_LIBMPEG2MMX){ if(mm_flags & FF_MM_MMX2){ c->idct_put= ff_libmpeg2mmx2_idct_put; c->idct_add= ff_libmpeg2mmx2_idct_add; c->idct = ff_mmxext_idct; }else{ c->idct_put= ff_libmpeg2mmx_idct_put; c->idct_add= ff_libmpeg2mmx_idct_add; c->idct = ff_mmx_idct; } c->idct_permutation_type= FF_LIBMPEG2_IDCT_PERM; #endif }else if((CONFIG_VP3_DECODER || CONFIG_VP5_DECODER || CONFIG_VP6_DECODER) && idct_algo==FF_IDCT_VP3){ if(mm_flags & FF_MM_SSE2){ c->idct_put= ff_vp3_idct_put_sse2; c->idct_add= ff_vp3_idct_add_sse2; c->idct = ff_vp3_idct_sse2; c->idct_permutation_type= FF_TRANSPOSE_IDCT_PERM; }else{ c->idct_put= ff_vp3_idct_put_mmx; c->idct_add= ff_vp3_idct_add_mmx; c->idct = ff_vp3_idct_mmx; c->idct_permutation_type= FF_PARTTRANS_IDCT_PERM; } }else if(idct_algo==FF_IDCT_CAVS){ c->idct_permutation_type= FF_TRANSPOSE_IDCT_PERM; }else if(idct_algo==FF_IDCT_XVIDMMX){ if(mm_flags & FF_MM_SSE2){ c->idct_put= ff_idct_xvid_sse2_put; c->idct_add= ff_idct_xvid_sse2_add; c->idct = ff_idct_xvid_sse2; c->idct_permutation_type= FF_SSE2_IDCT_PERM; }else if(mm_flags & FF_MM_MMX2){ c->idct_put= ff_idct_xvid_mmx2_put; c->idct_add= ff_idct_xvid_mmx2_add; c->idct = ff_idct_xvid_mmx2; }else{ c->idct_put= ff_idct_xvid_mmx_put; c->idct_add= ff_idct_xvid_mmx_add; c->idct = ff_idct_xvid_mmx; } } } c->put_pixels_clamped = put_pixels_clamped_mmx; c->put_signed_pixels_clamped = put_signed_pixels_clamped_mmx; c->add_pixels_clamped = add_pixels_clamped_mmx; c->clear_block = clear_block_mmx; c->clear_blocks = clear_blocks_mmx; if ((mm_flags & FF_MM_SSE) && !(CONFIG_MPEG_XVMC_DECODER && avctx->xvmc_acceleration > 1)){ /* XvMCCreateBlocks() may not allocate 16-byte aligned blocks */ c->clear_block = clear_block_sse; c->clear_blocks = clear_blocks_sse; } #define SET_HPEL_FUNCS(PFX, IDX, SIZE, CPU) \ c->PFX ## _pixels_tab[IDX][0] = PFX ## _pixels ## SIZE ## _ ## CPU; \ c->PFX ## _pixels_tab[IDX][1] = PFX ## _pixels ## SIZE ## _x2_ ## CPU; \ c->PFX ## _pixels_tab[IDX][2] = PFX ## _pixels ## SIZE ## _y2_ ## CPU; \ c->PFX ## _pixels_tab[IDX][3] = PFX ## _pixels ## SIZE ## _xy2_ ## CPU SET_HPEL_FUNCS(put, 0, 16, mmx); SET_HPEL_FUNCS(put_no_rnd, 0, 16, mmx); SET_HPEL_FUNCS(avg, 0, 16, mmx); SET_HPEL_FUNCS(avg_no_rnd, 0, 16, mmx); SET_HPEL_FUNCS(put, 1, 8, mmx); SET_HPEL_FUNCS(put_no_rnd, 1, 8, mmx); SET_HPEL_FUNCS(avg, 1, 8, mmx); SET_HPEL_FUNCS(avg_no_rnd, 1, 8, mmx); c->gmc= gmc_mmx; c->add_bytes= add_bytes_mmx; c->add_bytes_l2= add_bytes_l2_mmx; c->draw_edges = draw_edges_mmx; if (CONFIG_H263_DECODER || CONFIG_H263_ENCODER) { c->h263_v_loop_filter= h263_v_loop_filter_mmx; c->h263_h_loop_filter= h263_h_loop_filter_mmx; } c->put_h264_chroma_pixels_tab[0]= put_h264_chroma_mc8_mmx_rnd; c->put_h264_chroma_pixels_tab[1]= put_h264_chroma_mc4_mmx; c->put_no_rnd_vc1_chroma_pixels_tab[0]= put_vc1_chroma_mc8_mmx_nornd; c->put_rv40_chroma_pixels_tab[0]= put_rv40_chroma_mc8_mmx; c->put_rv40_chroma_pixels_tab[1]= put_rv40_chroma_mc4_mmx; if (CONFIG_VP6_DECODER) { c->vp6_filter_diag4 = ff_vp6_filter_diag4_mmx; } if (mm_flags & FF_MM_MMX2) { c->prefetch = prefetch_mmx2; c->put_pixels_tab[0][1] = put_pixels16_x2_mmx2; c->put_pixels_tab[0][2] = put_pixels16_y2_mmx2; c->avg_pixels_tab[0][0] = avg_pixels16_mmx2; c->avg_pixels_tab[0][1] = avg_pixels16_x2_mmx2; c->avg_pixels_tab[0][2] = avg_pixels16_y2_mmx2; c->put_pixels_tab[1][1] = put_pixels8_x2_mmx2; c->put_pixels_tab[1][2] = put_pixels8_y2_mmx2; c->avg_pixels_tab[1][0] = avg_pixels8_mmx2; c->avg_pixels_tab[1][1] = avg_pixels8_x2_mmx2; c->avg_pixels_tab[1][2] = avg_pixels8_y2_mmx2; if(!(avctx->flags & CODEC_FLAG_BITEXACT)){ c->put_no_rnd_pixels_tab[0][1] = put_no_rnd_pixels16_x2_mmx2; c->put_no_rnd_pixels_tab[0][2] = put_no_rnd_pixels16_y2_mmx2; c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_mmx2; c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_mmx2; c->avg_pixels_tab[0][3] = avg_pixels16_xy2_mmx2; c->avg_pixels_tab[1][3] = avg_pixels8_xy2_mmx2; if (CONFIG_VP3_DECODER) { c->vp3_v_loop_filter= ff_vp3_v_loop_filter_mmx2; c->vp3_h_loop_filter= ff_vp3_h_loop_filter_mmx2; } } if (CONFIG_VP3_DECODER) { c->vp3_idct_dc_add = ff_vp3_idct_dc_add_mmx2; } if (CONFIG_VP3_DECODER && (avctx->codec_id == CODEC_ID_VP3 || avctx->codec_id == CODEC_ID_THEORA)) { c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_exact_mmx2; c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_exact_mmx2; } #define SET_QPEL_FUNCS(PFX, IDX, SIZE, CPU) \ c->PFX ## _pixels_tab[IDX][ 0] = PFX ## SIZE ## _mc00_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 1] = PFX ## SIZE ## _mc10_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 2] = PFX ## SIZE ## _mc20_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 3] = PFX ## SIZE ## _mc30_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 4] = PFX ## SIZE ## _mc01_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 5] = PFX ## SIZE ## _mc11_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 6] = PFX ## SIZE ## _mc21_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 7] = PFX ## SIZE ## _mc31_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 8] = PFX ## SIZE ## _mc02_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 9] = PFX ## SIZE ## _mc12_ ## CPU; \ c->PFX ## _pixels_tab[IDX][10] = PFX ## SIZE ## _mc22_ ## CPU; \ c->PFX ## _pixels_tab[IDX][11] = PFX ## SIZE ## _mc32_ ## CPU; \ c->PFX ## _pixels_tab[IDX][12] = PFX ## SIZE ## _mc03_ ## CPU; \ c->PFX ## _pixels_tab[IDX][13] = PFX ## SIZE ## _mc13_ ## CPU; \ c->PFX ## _pixels_tab[IDX][14] = PFX ## SIZE ## _mc23_ ## CPU; \ c->PFX ## _pixels_tab[IDX][15] = PFX ## SIZE ## _mc33_ ## CPU SET_QPEL_FUNCS(put_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(put_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(put_no_rnd_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(put_no_rnd_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(avg_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(avg_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(put_h264_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(put_h264_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(put_h264_qpel, 2, 4, mmx2); SET_QPEL_FUNCS(avg_h264_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(avg_h264_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(avg_h264_qpel, 2, 4, mmx2); SET_QPEL_FUNCS(put_2tap_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(put_2tap_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(avg_2tap_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(avg_2tap_qpel, 1, 8, mmx2); c->avg_rv40_chroma_pixels_tab[0]= avg_rv40_chroma_mc8_mmx2; c->avg_rv40_chroma_pixels_tab[1]= avg_rv40_chroma_mc4_mmx2; c->avg_no_rnd_vc1_chroma_pixels_tab[0]= avg_vc1_chroma_mc8_mmx2_nornd; c->avg_h264_chroma_pixels_tab[0]= avg_h264_chroma_mc8_mmx2_rnd; c->avg_h264_chroma_pixels_tab[1]= avg_h264_chroma_mc4_mmx2; c->avg_h264_chroma_pixels_tab[2]= avg_h264_chroma_mc2_mmx2; c->put_h264_chroma_pixels_tab[2]= put_h264_chroma_mc2_mmx2; #if HAVE_YASM c->add_hfyu_median_prediction = ff_add_hfyu_median_prediction_mmx2; #endif #if HAVE_7REGS && HAVE_TEN_OPERANDS if( mm_flags&FF_MM_3DNOW ) c->add_hfyu_median_prediction = add_hfyu_median_prediction_cmov; #endif if (CONFIG_CAVS_DECODER) ff_cavsdsp_init_mmx2(c, avctx); if (CONFIG_VC1_DECODER) ff_vc1dsp_init_mmx(c, avctx); c->add_png_paeth_prediction= add_png_paeth_prediction_mmx2; } else if (mm_flags & FF_MM_3DNOW) { c->prefetch = prefetch_3dnow; c->put_pixels_tab[0][1] = put_pixels16_x2_3dnow; c->put_pixels_tab[0][2] = put_pixels16_y2_3dnow; c->avg_pixels_tab[0][0] = avg_pixels16_3dnow; c->avg_pixels_tab[0][1] = avg_pixels16_x2_3dnow; c->avg_pixels_tab[0][2] = avg_pixels16_y2_3dnow; c->put_pixels_tab[1][1] = put_pixels8_x2_3dnow; c->put_pixels_tab[1][2] = put_pixels8_y2_3dnow; c->avg_pixels_tab[1][0] = avg_pixels8_3dnow; c->avg_pixels_tab[1][1] = avg_pixels8_x2_3dnow; c->avg_pixels_tab[1][2] = avg_pixels8_y2_3dnow; if(!(avctx->flags & CODEC_FLAG_BITEXACT)){ c->put_no_rnd_pixels_tab[0][1] = put_no_rnd_pixels16_x2_3dnow; c->put_no_rnd_pixels_tab[0][2] = put_no_rnd_pixels16_y2_3dnow; c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_3dnow; c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_3dnow; c->avg_pixels_tab[0][3] = avg_pixels16_xy2_3dnow; c->avg_pixels_tab[1][3] = avg_pixels8_xy2_3dnow; } if (CONFIG_VP3_DECODER && (avctx->codec_id == CODEC_ID_VP3 || avctx->codec_id == CODEC_ID_THEORA)) { c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_exact_3dnow; c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_exact_3dnow; } SET_QPEL_FUNCS(put_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(put_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(put_no_rnd_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(put_no_rnd_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(avg_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(avg_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(put_h264_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(put_h264_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(put_h264_qpel, 2, 4, 3dnow); SET_QPEL_FUNCS(avg_h264_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(avg_h264_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(avg_h264_qpel, 2, 4, 3dnow); SET_QPEL_FUNCS(put_2tap_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(put_2tap_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(avg_2tap_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(avg_2tap_qpel, 1, 8, 3dnow); c->avg_h264_chroma_pixels_tab[0]= avg_h264_chroma_mc8_3dnow_rnd; c->avg_h264_chroma_pixels_tab[1]= avg_h264_chroma_mc4_3dnow; c->avg_rv40_chroma_pixels_tab[0]= avg_rv40_chroma_mc8_3dnow; c->avg_rv40_chroma_pixels_tab[1]= avg_rv40_chroma_mc4_3dnow; if (CONFIG_CAVS_DECODER) ff_cavsdsp_init_3dnow(c, avctx); } #define H264_QPEL_FUNCS(x, y, CPU)\ c->put_h264_qpel_pixels_tab[0][x+y*4] = put_h264_qpel16_mc##x##y##_##CPU;\ c->put_h264_qpel_pixels_tab[1][x+y*4] = put_h264_qpel8_mc##x##y##_##CPU;\ c->avg_h264_qpel_pixels_tab[0][x+y*4] = avg_h264_qpel16_mc##x##y##_##CPU;\ c->avg_h264_qpel_pixels_tab[1][x+y*4] = avg_h264_qpel8_mc##x##y##_##CPU; if((mm_flags & FF_MM_SSE2) && !(mm_flags & FF_MM_3DNOW)){ // these functions are slower than mmx on AMD, but faster on Intel c->put_pixels_tab[0][0] = put_pixels16_sse2; c->avg_pixels_tab[0][0] = avg_pixels16_sse2; H264_QPEL_FUNCS(0, 0, sse2); } if(mm_flags & FF_MM_SSE2){ H264_QPEL_FUNCS(0, 1, sse2); H264_QPEL_FUNCS(0, 2, sse2); H264_QPEL_FUNCS(0, 3, sse2); H264_QPEL_FUNCS(1, 1, sse2); H264_QPEL_FUNCS(1, 2, sse2); H264_QPEL_FUNCS(1, 3, sse2); H264_QPEL_FUNCS(2, 1, sse2); H264_QPEL_FUNCS(2, 2, sse2); H264_QPEL_FUNCS(2, 3, sse2); H264_QPEL_FUNCS(3, 1, sse2); H264_QPEL_FUNCS(3, 2, sse2); H264_QPEL_FUNCS(3, 3, sse2); if (CONFIG_VP6_DECODER) { c->vp6_filter_diag4 = ff_vp6_filter_diag4_sse2; } } #if HAVE_SSSE3 if(mm_flags & FF_MM_SSSE3){ H264_QPEL_FUNCS(1, 0, ssse3); H264_QPEL_FUNCS(1, 1, ssse3); H264_QPEL_FUNCS(1, 2, ssse3); H264_QPEL_FUNCS(1, 3, ssse3); H264_QPEL_FUNCS(2, 0, ssse3); H264_QPEL_FUNCS(2, 1, ssse3); H264_QPEL_FUNCS(2, 2, ssse3); H264_QPEL_FUNCS(2, 3, ssse3); H264_QPEL_FUNCS(3, 0, ssse3); H264_QPEL_FUNCS(3, 1, ssse3); H264_QPEL_FUNCS(3, 2, ssse3); H264_QPEL_FUNCS(3, 3, ssse3); c->put_no_rnd_vc1_chroma_pixels_tab[0]= put_vc1_chroma_mc8_ssse3_nornd; c->avg_no_rnd_vc1_chroma_pixels_tab[0]= avg_vc1_chroma_mc8_ssse3_nornd; c->put_h264_chroma_pixels_tab[0]= put_h264_chroma_mc8_ssse3_rnd; c->avg_h264_chroma_pixels_tab[0]= avg_h264_chroma_mc8_ssse3_rnd; c->put_h264_chroma_pixels_tab[1]= put_h264_chroma_mc4_ssse3; c->avg_h264_chroma_pixels_tab[1]= avg_h264_chroma_mc4_ssse3; c->add_png_paeth_prediction= add_png_paeth_prediction_ssse3; #if HAVE_YASM c->add_hfyu_left_prediction = ff_add_hfyu_left_prediction_ssse3; if (mm_flags & FF_MM_SSE4) // not really sse4, just slow on Conroe c->add_hfyu_left_prediction = ff_add_hfyu_left_prediction_sse4; #endif } #endif if(mm_flags & FF_MM_3DNOW){ c->vorbis_inverse_coupling = vorbis_inverse_coupling_3dnow; c->vector_fmul = vector_fmul_3dnow; if(!(avctx->flags & CODEC_FLAG_BITEXACT)){ c->float_to_int16 = float_to_int16_3dnow; c->float_to_int16_interleave = float_to_int16_interleave_3dnow; } } if(mm_flags & FF_MM_3DNOWEXT){ c->vector_fmul_reverse = vector_fmul_reverse_3dnow2; c->vector_fmul_window = vector_fmul_window_3dnow2; if(!(avctx->flags & CODEC_FLAG_BITEXACT)){ c->float_to_int16_interleave = float_to_int16_interleave_3dn2; } } if(mm_flags & FF_MM_MMX2){ #if HAVE_YASM c->scalarproduct_int16 = ff_scalarproduct_int16_mmx2; c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_mmx2; #endif } if(mm_flags & FF_MM_SSE){ c->vorbis_inverse_coupling = vorbis_inverse_coupling_sse; c->ac3_downmix = ac3_downmix_sse; c->vector_fmul = vector_fmul_sse; c->vector_fmul_reverse = vector_fmul_reverse_sse; c->vector_fmul_add = vector_fmul_add_sse; c->vector_fmul_window = vector_fmul_window_sse; c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_sse; c->vector_clipf = vector_clipf_sse; c->float_to_int16 = float_to_int16_sse; c->float_to_int16_interleave = float_to_int16_interleave_sse; #if HAVE_YASM c->scalarproduct_float = ff_scalarproduct_float_sse; #endif } if(mm_flags & FF_MM_3DNOW) c->vector_fmul_add = vector_fmul_add_3dnow; // faster than sse if(mm_flags & FF_MM_SSE2){ c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_sse2; c->float_to_int16 = float_to_int16_sse2; c->float_to_int16_interleave = float_to_int16_interleave_sse2; #if HAVE_YASM c->scalarproduct_int16 = ff_scalarproduct_int16_sse2; c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_sse2; #endif } if((mm_flags & FF_MM_SSSE3) && !(mm_flags & (FF_MM_SSE42|FF_MM_3DNOW)) && HAVE_YASM) // cachesplit c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_ssse3; } if (CONFIG_ENCODERS) dsputilenc_init_mmx(c, avctx); #if 0 // for speed testing get_pixels = just_return; put_pixels_clamped = just_return; add_pixels_clamped = just_return; pix_abs16x16 = just_return; pix_abs16x16_x2 = just_return; pix_abs16x16_y2 = just_return; pix_abs16x16_xy2 = just_return; put_pixels_tab[0] = just_return; put_pixels_tab[1] = just_return; put_pixels_tab[2] = just_return; put_pixels_tab[3] = just_return; put_no_rnd_pixels_tab[0] = just_return; put_no_rnd_pixels_tab[1] = just_return; put_no_rnd_pixels_tab[2] = just_return; put_no_rnd_pixels_tab[3] = just_return; avg_pixels_tab[0] = just_return; avg_pixels_tab[1] = just_return; avg_pixels_tab[2] = just_return; avg_pixels_tab[3] = just_return; avg_no_rnd_pixels_tab[0] = just_return; avg_no_rnd_pixels_tab[1] = just_return; avg_no_rnd_pixels_tab[2] = just_return; avg_no_rnd_pixels_tab[3] = just_return; //av_fdct = just_return; //ff_idct = just_return; #endif } #if CONFIG_H264DSP void ff_h264dsp_init_x86(H264DSPContext *c) { mm_flags = mm_support(); if (mm_flags & FF_MM_MMX) { c->h264_idct_dc_add= c->h264_idct_add= ff_h264_idct_add_mmx; c->h264_idct8_dc_add= c->h264_idct8_add= ff_h264_idct8_add_mmx; c->h264_idct_add16 = ff_h264_idct_add16_mmx; c->h264_idct8_add4 = ff_h264_idct8_add4_mmx; c->h264_idct_add8 = ff_h264_idct_add8_mmx; c->h264_idct_add16intra= ff_h264_idct_add16intra_mmx; if (mm_flags & FF_MM_MMX2) { c->h264_idct_dc_add= ff_h264_idct_dc_add_mmx2; c->h264_idct8_dc_add= ff_h264_idct8_dc_add_mmx2; c->h264_idct_add16 = ff_h264_idct_add16_mmx2; c->h264_idct8_add4 = ff_h264_idct8_add4_mmx2; c->h264_idct_add8 = ff_h264_idct_add8_mmx2; c->h264_idct_add16intra= ff_h264_idct_add16intra_mmx2; c->h264_v_loop_filter_luma= h264_v_loop_filter_luma_mmx2; c->h264_h_loop_filter_luma= h264_h_loop_filter_luma_mmx2; c->h264_v_loop_filter_chroma= h264_v_loop_filter_chroma_mmx2; c->h264_h_loop_filter_chroma= h264_h_loop_filter_chroma_mmx2; c->h264_v_loop_filter_chroma_intra= h264_v_loop_filter_chroma_intra_mmx2; c->h264_h_loop_filter_chroma_intra= h264_h_loop_filter_chroma_intra_mmx2; c->h264_loop_filter_strength= h264_loop_filter_strength_mmx2; c->weight_h264_pixels_tab[0]= ff_h264_weight_16x16_mmx2; c->weight_h264_pixels_tab[1]= ff_h264_weight_16x8_mmx2; c->weight_h264_pixels_tab[2]= ff_h264_weight_8x16_mmx2; c->weight_h264_pixels_tab[3]= ff_h264_weight_8x8_mmx2; c->weight_h264_pixels_tab[4]= ff_h264_weight_8x4_mmx2; c->weight_h264_pixels_tab[5]= ff_h264_weight_4x8_mmx2; c->weight_h264_pixels_tab[6]= ff_h264_weight_4x4_mmx2; c->weight_h264_pixels_tab[7]= ff_h264_weight_4x2_mmx2; c->biweight_h264_pixels_tab[0]= ff_h264_biweight_16x16_mmx2; c->biweight_h264_pixels_tab[1]= ff_h264_biweight_16x8_mmx2; c->biweight_h264_pixels_tab[2]= ff_h264_biweight_8x16_mmx2; c->biweight_h264_pixels_tab[3]= ff_h264_biweight_8x8_mmx2; c->biweight_h264_pixels_tab[4]= ff_h264_biweight_8x4_mmx2; c->biweight_h264_pixels_tab[5]= ff_h264_biweight_4x8_mmx2; c->biweight_h264_pixels_tab[6]= ff_h264_biweight_4x4_mmx2; c->biweight_h264_pixels_tab[7]= ff_h264_biweight_4x2_mmx2; } if(mm_flags & FF_MM_SSE2){ c->h264_idct8_add = ff_h264_idct8_add_sse2; c->h264_idct8_add4= ff_h264_idct8_add4_sse2; } #if CONFIG_GPL && HAVE_YASM if (mm_flags & FF_MM_MMX2){ #if ARCH_X86_32 c->h264_v_loop_filter_luma_intra = ff_x264_deblock_v_luma_intra_mmxext; c->h264_h_loop_filter_luma_intra = ff_x264_deblock_h_luma_intra_mmxext; #endif if( mm_flags&FF_MM_SSE2 ){ #if ARCH_X86_64 || !defined(__ICC) || __ICC > 1110 c->h264_v_loop_filter_luma = ff_x264_deblock_v_luma_sse2; c->h264_h_loop_filter_luma = ff_x264_deblock_h_luma_sse2; c->h264_v_loop_filter_luma_intra = ff_x264_deblock_v_luma_intra_sse2; c->h264_h_loop_filter_luma_intra = ff_x264_deblock_h_luma_intra_sse2; #endif c->h264_idct_add16 = ff_h264_idct_add16_sse2; c->h264_idct_add8 = ff_h264_idct_add8_sse2; c->h264_idct_add16intra = ff_h264_idct_add16intra_sse2; } } #endif } } #endif /* CONFIG_H264DSP */
Java
#!/bin/bash # Copyright 2015 Google, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.set -x -e # Only run on the master node ROLE=$(/usr/share/google/get_metadata_value attributes/dataproc-role) if [[ "${ROLE}" == 'Master' ]]; then # Install dependencies needed for iPython Notebook apt-get install build-essential python-dev libpng-dev libfreetype6-dev libxft-dev pkg-config python-matplotlib python-requests python-numpy -y curl https://bootstrap.pypa.io/get-pip.py | python # Install iPython Notebook and create a profile mkdir IPythonNB cd IPythonNB pip install "ipython[notebook]" ipython profile create default # Set up configuration for iPython Notebook echo "c = get_config()" > /root/.ipython/profile_default/ipython_notebook_config.py echo "c.NotebookApp.ip = '*'" >> /root/.ipython/profile_default/ipython_notebook_config.py echo "c.NotebookApp.open_browser = False" >> /root/.ipython/profile_default/ipython_notebook_config.py echo "c.NotebookApp.port = 8123" >> /root/.ipython/profile_default/ipython_notebook_config.py # Setup script for iPython Notebook so it uses the cluster's Spark cat > /root/.ipython/profile_default/startup/00-pyspark-setup.py <<'_EOF' import os import sys spark_home = '/usr/lib/spark/' os.environ["SPARK_HOME"] = spark_home sys.path.insert(0, os.path.join(spark_home, 'python')) sys.path.insert(0, os.path.join(spark_home, 'python/lib/py4j-0.8.2.1-src.zip')) execfile(os.path.join(spark_home, 'python/pyspark/shell.py')) _EOF # Start iPython Notebook on port 8123 nohup ipython notebook --no-browser --ip=* --port=8123 > /var/log/python_notebook.log & fi
Java
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 // protoc v3.17.3 // source: github.com/google/cloudprober/surfacers/postgres/proto/config.proto package proto import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type SurfacerConf struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ConnectionString *string `protobuf:"bytes,1,req,name=connection_string,json=connectionString" json:"connection_string,omitempty"` MetricsTableName *string `protobuf:"bytes,2,req,name=metrics_table_name,json=metricsTableName" json:"metrics_table_name,omitempty"` MetricsBufferSize *int64 `protobuf:"varint,3,opt,name=metrics_buffer_size,json=metricsBufferSize,def=10000" json:"metrics_buffer_size,omitempty"` } // Default values for SurfacerConf fields. const ( Default_SurfacerConf_MetricsBufferSize = int64(10000) ) func (x *SurfacerConf) Reset() { *x = SurfacerConf{} if protoimpl.UnsafeEnabled { mi := &file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SurfacerConf) String() string { return protoimpl.X.MessageStringOf(x) } func (*SurfacerConf) ProtoMessage() {} func (x *SurfacerConf) ProtoReflect() protoreflect.Message { mi := &file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SurfacerConf.ProtoReflect.Descriptor instead. func (*SurfacerConf) Descriptor() ([]byte, []int) { return file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDescGZIP(), []int{0} } func (x *SurfacerConf) GetConnectionString() string { if x != nil && x.ConnectionString != nil { return *x.ConnectionString } return "" } func (x *SurfacerConf) GetMetricsTableName() string { if x != nil && x.MetricsTableName != nil { return *x.MetricsTableName } return "" } func (x *SurfacerConf) GetMetricsBufferSize() int64 { if x != nil && x.MetricsBufferSize != nil { return *x.MetricsBufferSize } return Default_SurfacerConf_MetricsBufferSize } var File_github_com_google_cloudprober_surfacers_postgres_proto_config_proto protoreflect.FileDescriptor var file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDesc = []byte{ 0x0a, 0x43, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x70, 0x72, 0x6f, 0x62, 0x65, 0x72, 0x2f, 0x73, 0x75, 0x72, 0x66, 0x61, 0x63, 0x65, 0x72, 0x73, 0x2f, 0x70, 0x6f, 0x73, 0x74, 0x67, 0x72, 0x65, 0x73, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1d, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x70, 0x72, 0x6f, 0x62, 0x65, 0x72, 0x2e, 0x73, 0x75, 0x72, 0x66, 0x61, 0x63, 0x65, 0x72, 0x2e, 0x70, 0x6f, 0x73, 0x74, 0x67, 0x72, 0x65, 0x73, 0x22, 0xa0, 0x01, 0x0a, 0x0c, 0x53, 0x75, 0x72, 0x66, 0x61, 0x63, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x12, 0x2b, 0x0a, 0x11, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x18, 0x01, 0x20, 0x02, 0x28, 0x09, 0x52, 0x10, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x12, 0x2c, 0x0a, 0x12, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x5f, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x02, 0x28, 0x09, 0x52, 0x10, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x35, 0x0a, 0x13, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x5f, 0x62, 0x75, 0x66, 0x66, 0x65, 0x72, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x3a, 0x05, 0x31, 0x30, 0x30, 0x30, 0x30, 0x52, 0x11, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x42, 0x75, 0x66, 0x66, 0x65, 0x72, 0x53, 0x69, 0x7a, 0x65, 0x42, 0x38, 0x5a, 0x36, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x70, 0x72, 0x6f, 0x62, 0x65, 0x72, 0x2f, 0x73, 0x75, 0x72, 0x66, 0x61, 0x63, 0x65, 0x72, 0x73, 0x2f, 0x70, 0x6f, 0x73, 0x74, 0x67, 0x72, 0x65, 0x73, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, } var ( file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDescOnce sync.Once file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDescData = file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDesc ) func file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDescGZIP() []byte { file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDescOnce.Do(func() { file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDescData) }) return file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDescData } var file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_goTypes = []interface{}{ (*SurfacerConf)(nil), // 0: cloudprober.surfacer.postgres.SurfacerConf } var file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_init() } func file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_init() { if File_github_com_google_cloudprober_surfacers_postgres_proto_config_proto != nil { return } if !protoimpl.UnsafeEnabled { file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SurfacerConf); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_goTypes, DependencyIndexes: file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_depIdxs, MessageInfos: file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_msgTypes, }.Build() File_github_com_google_cloudprober_surfacers_postgres_proto_config_proto = out.File file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDesc = nil file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_goTypes = nil file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_depIdxs = nil }
Java
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.elasticmapreduce.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.elasticmapreduce.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * ListBootstrapActionsRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class ListBootstrapActionsRequestMarshaller { private static final MarshallingInfo<String> CLUSTERID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("ClusterId").build(); private static final MarshallingInfo<String> MARKER_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Marker").build(); private static final ListBootstrapActionsRequestMarshaller instance = new ListBootstrapActionsRequestMarshaller(); public static ListBootstrapActionsRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(ListBootstrapActionsRequest listBootstrapActionsRequest, ProtocolMarshaller protocolMarshaller) { if (listBootstrapActionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listBootstrapActionsRequest.getClusterId(), CLUSTERID_BINDING); protocolMarshaller.marshall(listBootstrapActionsRequest.getMarker(), MARKER_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
Java
/** * Server-side support classes for WebSocket requests. */ @NonNullApi @NonNullFields package org.springframework.web.reactive.socket.server.support; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
Java
/** * */ package org.commcare.cases.ledger; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import org.javarosa.core.services.storage.IMetaData; import org.javarosa.core.services.storage.Persistable; import org.javarosa.core.util.externalizable.DeserializationException; import org.javarosa.core.util.externalizable.ExtUtil; import org.javarosa.core.util.externalizable.ExtWrapMap; import org.javarosa.core.util.externalizable.PrototypeFactory; /** * A Ledger is a data model which tracks numeric data organized into * different sections with different meanings. * * @author ctsims * */ public class Ledger implements Persistable, IMetaData { //NOTE: Right now this is (lazily) implemented assuming that each ledger //object tracks _all_ of the sections for an entity, which will likely be a terrible way //to do things long-term. public static final String STORAGE_KEY = "ledger"; public static final String INDEX_ENTITY_ID = "entity-id"; String entityId; int recordId = -1; Hashtable<String, Hashtable<String, Integer>> sections; public Ledger() { } public Ledger(String entityId) { this.entityId = entityId; this.sections = new Hashtable<String, Hashtable<String, Integer>>(); } /** * Get the ID of the linked entity associated with this Ledger record * @return */ public String getEntiyId() { return entityId; } /** * Retrieve an entry from a specific section of the ledger. * * If no entry is defined, the ledger will return the value '0' * * @param sectionId The section containing the entry * @param entryId The Id of the entry to retrieve * @return the entry value. '0' if no entry exists. */ public int getEntry(String sectionId, String entryId) { if(!sections.containsKey(sectionId) || !sections.get(sectionId).containsKey(entryId)) { return 0; } return sections.get(sectionId).get(entryId).intValue(); } /** * @return The list of sections available in this ledger */ public String[] getSectionList() { String[] sectionList = new String[sections.size()]; int i = 0; for(Enumeration e = sections.keys(); e.hasMoreElements();) { sectionList[i] = (String)e.nextElement(); ++i; } return sectionList; } /** * Retrieves a list of all entries (by ID) defined in a * section of the ledger * * @param sectionId The ID of a section * @return The IDs of all entries defined in the provided section */ public String[] getListOfEntries(String sectionId) { Hashtable<String, Integer> entries = sections.get(sectionId); String[] entryList = new String[entries.size()]; int i = 0; for(Enumeration e = entries.keys(); e.hasMoreElements();) { entryList[i] = (String)e.nextElement(); ++i; } return entryList; } /* * (non-Javadoc) * @see org.javarosa.core.util.externalizable.Externalizable#readExternal(java.io.DataInputStream, org.javarosa.core.util.externalizable.PrototypeFactory) */ public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { recordId = ExtUtil.readInt(in); entityId = ExtUtil.readString(in); sections = (Hashtable<String, Hashtable<String, Integer>>) ExtUtil.read(in, new ExtWrapMap(String.class, new ExtWrapMap(String.class, Integer.class))); } /* * (non-Javadoc) * @see org.javarosa.core.util.externalizable.Externalizable#writeExternal(java.io.DataOutputStream) */ public void writeExternal(DataOutputStream out) throws IOException { ExtUtil.writeNumeric(out, recordId); ExtUtil.writeString(out, entityId); ExtUtil.write(out, new ExtWrapMap(sections, new ExtWrapMap(String.class, Integer.class))); } /* * (non-Javadoc) * @see org.javarosa.core.services.storage.Persistable#setID(int) */ public void setID(int ID) { recordId = ID; } /* * (non-Javadoc) * @see org.javarosa.core.services.storage.Persistable#getID() */ public int getID() { return recordId; } /** * Sets the value of an entry in the specified section of this ledger * * @param sectionId * @param entryId * @param quantity */ public void setEntry(String sectionId, String entryId, int quantity) { if(!sections.containsKey(sectionId)) { sections.put(sectionId, new Hashtable<String, Integer>()); } sections.get(sectionId).put(entryId, new Integer(quantity)); } /* * (non-Javadoc) * @see org.javarosa.core.services.storage.IMetaData#getMetaDataFields() */ public String[] getMetaDataFields() { return new String[] {INDEX_ENTITY_ID}; } /* * (non-Javadoc) * @see org.javarosa.core.services.storage.IMetaData#getMetaData(java.lang.String) */ public Object getMetaData(String fieldName) { if(fieldName.equals(INDEX_ENTITY_ID)){ return entityId; } else { throw new IllegalArgumentException("No metadata field " + fieldName + " in the ledger storage system"); } } }
Java
# Copyright 2017 Priscilla Boyd. 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. # ============================================================================== """ The DT_Utils module provides helper functions for Decision Tree algorithms implementation, model creation and analysis. """ import pickle from matplotlib import pyplot as plt from sklearn.metrics import mean_squared_error from tools.Utils import create_folder_if_not_exists # noinspection PyTypeChecker def score_dt(model_name, model, X, y, y_actual, output_folder): """ Score a decision tree model. :param string model_name: title for the model used on the output filename :param dataframe model: model reference :param dataframe X: examples :param dataframe y: targets :param dataframe y_actual: target results :param string output_folder: location of the output / results """ print("Scoring model...") model_score = model.score(X, y) mse = mean_squared_error(y, y_actual) mse_score = model_name, "- Mean Squared Error:", mse accuracy = model_name, "- Accuracy score (%):", "{:.2%}".format(model_score) # write to file path = output_folder + '/models' create_folder_if_not_exists(path) filename = path + '/score_' + model_name + '.txt' with open(filename, 'w') as scores: print(mse_score, file=scores) print(accuracy, file=scores) scores.close() print("Scores saved location:", filename) def plot_dt(model_name, y_actual, y_test, output_folder): """ Plot decision tree, y (training) vs y (test/actual). :param string model_name: title for the model used on the output filename :param dataframe y_actual: target results :param dataframe y_test: test targets :param string output_folder: location of the output / results """ # initialise plot path path = output_folder + '/models' print("Plotting results...") plt.scatter(y_actual, y_test, label='Duration') plt.title('Decision Tree') plt.plot([0, 1], [0, 1], '--k', transform=plt.gca().transAxes) plt.xlabel('y (actual)') plt.ylabel('y (test)') plt.legend() plot_path = path + '/plot_' + model_name + '.png' plt.savefig(plot_path) print("Plot saved location:", plot_path) def save_dt_model(model_name, model, folder): """ Save model using Pickle binary format. :param dataframe model: model reference :param string model_name: title for the model used on the output filename :param string folder: location of model output """ print("Saving model...") model_file = folder + '/models/' + model_name + '.pkl' path = open(model_file, 'wb') pickle.dump(model, path) print("Model saved location:", model_file) def load_dt_model(pickle_model): """ Retrieve model using Pickle binary format. :param string pickle_model: location of Pickle model :return: Pickle model for re-use :rtype: object """ return pickle.loads(pickle_model)
Java
/* * Copyright (c) 2010-2013 Evolveum * * 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.evolveum.midpoint.repo.sql.data.audit; import com.evolveum.midpoint.audit.api.AuditEventRecord; import com.evolveum.midpoint.audit.api.AuditService; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.repo.sql.data.common.enums.ROperationResultStatus; import com.evolveum.midpoint.repo.sql.data.common.other.RObjectType; import com.evolveum.midpoint.repo.sql.util.ClassMapper; import com.evolveum.midpoint.repo.sql.util.DtoTranslationException; import com.evolveum.midpoint.repo.sql.util.RUtil; import com.evolveum.midpoint.schema.ObjectDeltaOperation; import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import org.apache.commons.lang.Validate; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.ForeignKey; import javax.persistence.*; import javax.xml.namespace.QName; import java.io.Serializable; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author lazyman */ @Entity @Table(name = RAuditEventRecord.TABLE_NAME, indexes = { @Index(name = "iTimestampValue", columnList = RAuditEventRecord.COLUMN_TIMESTAMP)}) // TODO correct index name public class RAuditEventRecord implements Serializable { public static final String TABLE_NAME = "m_audit_event"; public static final String COLUMN_TIMESTAMP = "timestampValue"; private long id; private Timestamp timestamp; private String eventIdentifier; private String sessionIdentifier; private String taskIdentifier; private String taskOID; private String hostIdentifier; //prism object - user private String initiatorOid; private String initiatorName; //prism object private String targetOid; private String targetName; private RObjectType targetType; //prism object - user private String targetOwnerOid; private String targetOwnerName; private RAuditEventType eventType; private RAuditEventStage eventStage; //collection of object deltas private Set<RObjectDeltaOperation> deltas; private String channel; private ROperationResultStatus outcome; private String parameter; private String message; private String result; public String getResult() { return result; } @Column(length = 1024) public String getMessage() { return message; } public String getParameter() { return parameter; } public String getChannel() { return channel; } @ForeignKey(name = "fk_audit_delta") @OneToMany(mappedBy = "record", orphanRemoval = true) @Cascade({org.hibernate.annotations.CascadeType.ALL}) public Set<RObjectDeltaOperation> getDeltas() { if (deltas == null) { deltas = new HashSet<RObjectDeltaOperation>(); } return deltas; } public String getEventIdentifier() { return eventIdentifier; } @Enumerated(EnumType.ORDINAL) public RAuditEventStage getEventStage() { return eventStage; } @Enumerated(EnumType.ORDINAL) public RAuditEventType getEventType() { return eventType; } public String getHostIdentifier() { return hostIdentifier; } @Id @GeneratedValue public long getId() { return id; } @Column(length = RUtil.COLUMN_LENGTH_OID) public String getInitiatorOid() { return initiatorOid; } public String getInitiatorName() { return initiatorName; } @Enumerated(EnumType.ORDINAL) public ROperationResultStatus getOutcome() { return outcome; } public String getSessionIdentifier() { return sessionIdentifier; } public String getTargetName() { return targetName; } @Column(length = RUtil.COLUMN_LENGTH_OID) public String getTargetOid() { return targetOid; } @Enumerated(EnumType.ORDINAL) public RObjectType getTargetType() { return targetType; } public String getTargetOwnerName() { return targetOwnerName; } @Column(length = RUtil.COLUMN_LENGTH_OID) public String getTargetOwnerOid() { return targetOwnerOid; } public String getTaskIdentifier() { return taskIdentifier; } public String getTaskOID() { return taskOID; } @Column(name = COLUMN_TIMESTAMP) public Timestamp getTimestamp() { return timestamp; } public void setMessage(String message) { this.message = message; } public void setParameter(String parameter) { this.parameter = parameter; } public void setChannel(String channel) { this.channel = channel; } public void setDeltas(Set<RObjectDeltaOperation> deltas) { this.deltas = deltas; } public void setEventIdentifier(String eventIdentifier) { this.eventIdentifier = eventIdentifier; } public void setEventStage(RAuditEventStage eventStage) { this.eventStage = eventStage; } public void setEventType(RAuditEventType eventType) { this.eventType = eventType; } public void setHostIdentifier(String hostIdentifier) { this.hostIdentifier = hostIdentifier; } public void setId(long id) { this.id = id; } public void setInitiatorName(String initiatorName) { this.initiatorName = initiatorName; } public void setInitiatorOid(String initiatorOid) { this.initiatorOid = initiatorOid; } public void setOutcome(ROperationResultStatus outcome) { this.outcome = outcome; } public void setSessionIdentifier(String sessionIdentifier) { this.sessionIdentifier = sessionIdentifier; } public void setTargetName(String targetName) { this.targetName = targetName; } public void setTargetOid(String targetOid) { this.targetOid = targetOid; } public void setTargetType(RObjectType targetType) { this.targetType = targetType; } public void setTargetOwnerName(String targetOwnerName) { this.targetOwnerName = targetOwnerName; } public void setTargetOwnerOid(String targetOwnerOid) { this.targetOwnerOid = targetOwnerOid; } public void setTaskIdentifier(String taskIdentifier) { this.taskIdentifier = taskIdentifier; } public void setTaskOID(String taskOID) { this.taskOID = taskOID; } public void setTimestamp(Timestamp timestamp) { this.timestamp = timestamp; } public void setResult(String result) { this.result = result; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RAuditEventRecord that = (RAuditEventRecord) o; if (channel != null ? !channel.equals(that.channel) : that.channel != null) return false; if (deltas != null ? !deltas.equals(that.deltas) : that.deltas != null) return false; if (eventIdentifier != null ? !eventIdentifier.equals(that.eventIdentifier) : that.eventIdentifier != null) return false; if (eventStage != that.eventStage) return false; if (eventType != that.eventType) return false; if (hostIdentifier != null ? !hostIdentifier.equals(that.hostIdentifier) : that.hostIdentifier != null) return false; if (initiatorOid != null ? !initiatorOid.equals(that.initiatorOid) : that.initiatorOid != null) return false; if (initiatorName != null ? !initiatorName.equals(that.initiatorName) : that.initiatorName != null) return false; if (outcome != that.outcome) return false; if (sessionIdentifier != null ? !sessionIdentifier.equals(that.sessionIdentifier) : that.sessionIdentifier != null) return false; if (targetOid != null ? !targetOid.equals(that.targetOid) : that.targetOid != null) return false; if (targetName != null ? !targetName.equals(that.targetName) : that.targetName != null) return false; if (targetType != null ? !targetType.equals(that.targetType) : that.targetType != null) return false; if (targetOwnerOid != null ? !targetOwnerOid.equals(that.targetOwnerOid) : that.targetOwnerOid != null) return false; if (targetOwnerName != null ? !targetOwnerName.equals(that.targetOwnerName) : that.targetOwnerName != null) return false; if (taskIdentifier != null ? !taskIdentifier.equals(that.taskIdentifier) : that.taskIdentifier != null) return false; if (taskOID != null ? !taskOID.equals(that.taskOID) : that.taskOID != null) return false; if (timestamp != null ? !timestamp.equals(that.timestamp) : that.timestamp != null) return false; if (parameter != null ? !parameter.equals(that.parameter) : that.parameter != null) return false; if (message != null ? !message.equals(that.message) : that.message != null) return false; if (result != null ? !result.equals(that.result) : that.result != null) return false; return true; } @Override public int hashCode() { int result = timestamp != null ? timestamp.hashCode() : 0; result = 31 * result + (eventIdentifier != null ? eventIdentifier.hashCode() : 0); result = 31 * result + (sessionIdentifier != null ? sessionIdentifier.hashCode() : 0); result = 31 * result + (taskIdentifier != null ? taskIdentifier.hashCode() : 0); result = 31 * result + (taskOID != null ? taskOID.hashCode() : 0); result = 31 * result + (hostIdentifier != null ? hostIdentifier.hashCode() : 0); result = 31 * result + (initiatorName != null ? initiatorName.hashCode() : 0); result = 31 * result + (initiatorOid != null ? initiatorOid.hashCode() : 0); result = 31 * result + (targetOid != null ? targetOid.hashCode() : 0); result = 31 * result + (targetName != null ? targetName.hashCode() : 0); result = 31 * result + (targetType != null ? targetType.hashCode() : 0); result = 31 * result + (targetOwnerOid != null ? targetOwnerOid.hashCode() : 0); result = 31 * result + (targetOwnerName != null ? targetOwnerName.hashCode() : 0); result = 31 * result + (eventType != null ? eventType.hashCode() : 0); result = 31 * result + (eventStage != null ? eventStage.hashCode() : 0); result = 31 * result + (deltas != null ? deltas.hashCode() : 0); result = 31 * result + (channel != null ? channel.hashCode() : 0); result = 31 * result + (outcome != null ? outcome.hashCode() : 0); result = 31 * result + (parameter != null ? parameter.hashCode() : 0); result = 31 * result + (message != null ? message.hashCode() : 0); result = 31 * result + (this.result != null ? this.result.hashCode() : 0); return result; } public static RAuditEventRecord toRepo(AuditEventRecord record, PrismContext prismContext) throws DtoTranslationException { Validate.notNull(record, "Audit event record must not be null."); Validate.notNull(prismContext, "Prism context must not be null."); RAuditEventRecord repo = new RAuditEventRecord(); repo.setChannel(record.getChannel()); if (record.getTimestamp() != null) { repo.setTimestamp(new Timestamp(record.getTimestamp())); } repo.setEventStage(RAuditEventStage.toRepo(record.getEventStage())); repo.setEventType(RAuditEventType.toRepo(record.getEventType())); repo.setSessionIdentifier(record.getSessionIdentifier()); repo.setEventIdentifier(record.getEventIdentifier()); repo.setHostIdentifier(record.getHostIdentifier()); repo.setParameter(record.getParameter()); repo.setMessage(trimMessage(record.getMessage())); if (record.getOutcome() != null) { repo.setOutcome(RUtil.getRepoEnumValue(record.getOutcome().createStatusType(), ROperationResultStatus.class)); } repo.setTaskIdentifier(record.getTaskIdentifier()); repo.setTaskOID(record.getTaskOID()); repo.setResult(record.getResult()); try { if (record.getTarget() != null) { PrismObject target = record.getTarget(); repo.setTargetName(getOrigName(target)); repo.setTargetOid(target.getOid()); QName type = ObjectTypes.getObjectType(target.getCompileTimeClass()).getTypeQName(); repo.setTargetType(ClassMapper.getHQLTypeForQName(type)); } if (record.getTargetOwner() != null) { PrismObject targetOwner = record.getTargetOwner(); repo.setTargetOwnerName(getOrigName(targetOwner)); repo.setTargetOwnerOid(targetOwner.getOid()); } if (record.getInitiator() != null) { PrismObject<UserType> initiator = record.getInitiator(); repo.setInitiatorName(getOrigName(initiator)); repo.setInitiatorOid(initiator.getOid()); } for (ObjectDeltaOperation<?> delta : record.getDeltas()) { if (delta == null) { continue; } RObjectDeltaOperation rDelta = RObjectDeltaOperation.toRepo(repo, delta, prismContext); rDelta.setTransient(true); rDelta.setRecord(repo); repo.getDeltas().add(rDelta); } } catch (Exception ex) { throw new DtoTranslationException(ex.getMessage(), ex); } return repo; } public static AuditEventRecord fromRepo(RAuditEventRecord repo, PrismContext prismContext) throws DtoTranslationException{ AuditEventRecord audit = new AuditEventRecord(); audit.setChannel(repo.getChannel()); audit.setEventIdentifier(repo.getEventIdentifier()); if (repo.getEventStage() != null){ audit.setEventStage(repo.getEventStage().getStage()); } if (repo.getEventType() != null){ audit.setEventType(repo.getEventType().getType()); } audit.setHostIdentifier(repo.getHostIdentifier()); audit.setMessage(repo.getMessage()); if (repo.getOutcome() != null){ audit.setOutcome(repo.getOutcome().getStatus()); } audit.setParameter(repo.getParameter()); audit.setResult(repo.getResult()); audit.setSessionIdentifier(repo.getSessionIdentifier()); audit.setTaskIdentifier(repo.getTaskIdentifier()); audit.setTaskOID(repo.getTaskOID()); if (repo.getTimestamp() != null){ audit.setTimestamp(repo.getTimestamp().getTime()); } List<ObjectDeltaOperation> odos = new ArrayList<ObjectDeltaOperation>(); for (RObjectDeltaOperation rodo : repo.getDeltas()){ try { ObjectDeltaOperation odo = RObjectDeltaOperation.fromRepo(rodo, prismContext); if (odo != null){ odos.add(odo); } } catch (Exception ex){ //TODO: for now thi is OK, if we cannot parse detla, just skipp it.. Have to be resolved later; } } audit.getDeltas().addAll((Collection) odos); return audit; //initiator, target, targetOwner } private static String trimMessage(String message) { if (message == null || message.length() <= AuditService.MAX_MESSAGE_SIZE) { return message; } return message.substring(0, AuditService.MAX_MESSAGE_SIZE - 4) + "..."; } private static String getOrigName(PrismObject object) { PolyString name = (PolyString) object.getPropertyRealValue(ObjectType.F_NAME, PolyString.class); return name != null ? name.getOrig() : null; } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_232) on Tue Sep 15 08:53:05 UTC 2020 --> <title>Uses of Class org.springframework.jmx.export.metadata.ManagedAttribute (Spring Framework 5.1.18.RELEASE API)</title> <meta name="date" content="2020-09-15"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.springframework.jmx.export.metadata.ManagedAttribute (Spring Framework 5.1.18.RELEASE API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/springframework/jmx/export/metadata/ManagedAttribute.html" title="class in org.springframework.jmx.export.metadata">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Spring Framework</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/springframework/jmx/export/metadata/class-use/ManagedAttribute.html" target="_top">Frames</a></li> <li><a href="ManagedAttribute.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.springframework.jmx.export.metadata.ManagedAttribute" class="title">Uses of Class<br>org.springframework.jmx.export.metadata.ManagedAttribute</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../org/springframework/jmx/export/metadata/ManagedAttribute.html" title="class in org.springframework.jmx.export.metadata">ManagedAttribute</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.springframework.jmx.export.annotation">org.springframework.jmx.export.annotation</a></td> <td class="colLast"> <div class="block">Java 5 annotations for MBean exposure.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.springframework.jmx.export.metadata">org.springframework.jmx.export.metadata</a></td> <td class="colLast"> <div class="block">Provides generic JMX metadata classes and basic support for reading JMX metadata in a provider-agnostic manner.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.springframework.jmx.export.annotation"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/springframework/jmx/export/metadata/ManagedAttribute.html" title="class in org.springframework.jmx.export.metadata">ManagedAttribute</a> in <a href="../../../../../../org/springframework/jmx/export/annotation/package-summary.html">org.springframework.jmx.export.annotation</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/springframework/jmx/export/annotation/package-summary.html">org.springframework.jmx.export.annotation</a> that return <a href="../../../../../../org/springframework/jmx/export/metadata/ManagedAttribute.html" title="class in org.springframework.jmx.export.metadata">ManagedAttribute</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/springframework/jmx/export/metadata/ManagedAttribute.html" title="class in org.springframework.jmx.export.metadata">ManagedAttribute</a></code></td> <td class="colLast"><span class="typeNameLabel">AnnotationJmxAttributeSource.</span><code><span class="memberNameLink"><a href="../../../../../../org/springframework/jmx/export/annotation/AnnotationJmxAttributeSource.html#getManagedAttribute-java.lang.reflect.Method-">getManagedAttribute</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html?is-external=true" title="class or interface in java.lang.reflect">Method</a>&nbsp;method)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.springframework.jmx.export.metadata"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/springframework/jmx/export/metadata/ManagedAttribute.html" title="class in org.springframework.jmx.export.metadata">ManagedAttribute</a> in <a href="../../../../../../org/springframework/jmx/export/metadata/package-summary.html">org.springframework.jmx.export.metadata</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../../org/springframework/jmx/export/metadata/package-summary.html">org.springframework.jmx.export.metadata</a> declared as <a href="../../../../../../org/springframework/jmx/export/metadata/ManagedAttribute.html" title="class in org.springframework.jmx.export.metadata">ManagedAttribute</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../../org/springframework/jmx/export/metadata/ManagedAttribute.html" title="class in org.springframework.jmx.export.metadata">ManagedAttribute</a></code></td> <td class="colLast"><span class="typeNameLabel">ManagedAttribute.</span><code><span class="memberNameLink"><a href="../../../../../../org/springframework/jmx/export/metadata/ManagedAttribute.html#EMPTY">EMPTY</a></span></code> <div class="block">Empty attributes.</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/springframework/jmx/export/metadata/package-summary.html">org.springframework.jmx.export.metadata</a> that return <a href="../../../../../../org/springframework/jmx/export/metadata/ManagedAttribute.html" title="class in org.springframework.jmx.export.metadata">ManagedAttribute</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/springframework/jmx/export/metadata/ManagedAttribute.html" title="class in org.springframework.jmx.export.metadata">ManagedAttribute</a></code></td> <td class="colLast"><span class="typeNameLabel">JmxAttributeSource.</span><code><span class="memberNameLink"><a href="../../../../../../org/springframework/jmx/export/metadata/JmxAttributeSource.html#getManagedAttribute-java.lang.reflect.Method-">getManagedAttribute</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html?is-external=true" title="class or interface in java.lang.reflect">Method</a>&nbsp;method)</code> <div class="block">Implementations should return an instance of <code>ManagedAttribute</code> if the supplied <code>Method</code> has the corresponding metadata.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/springframework/jmx/export/metadata/ManagedAttribute.html" title="class in org.springframework.jmx.export.metadata">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Spring Framework</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/springframework/jmx/export/metadata/class-use/ManagedAttribute.html" target="_top">Frames</a></li> <li><a href="ManagedAttribute.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Java
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.worklink.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/worklink-2018-09-25/DescribeDevice" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeDeviceResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The current state of the device. * </p> */ private String status; /** * <p> * The model of the device. * </p> */ private String model; /** * <p> * The manufacturer of the device. * </p> */ private String manufacturer; /** * <p> * The operating system of the device. * </p> */ private String operatingSystem; /** * <p> * The operating system version of the device. * </p> */ private String operatingSystemVersion; /** * <p> * The operating system patch level of the device. * </p> */ private String patchLevel; /** * <p> * The date that the device first signed in to Amazon WorkLink. * </p> */ private java.util.Date firstAccessedTime; /** * <p> * The date that the device last accessed Amazon WorkLink. * </p> */ private java.util.Date lastAccessedTime; /** * <p> * The user name associated with the device. * </p> */ private String username; /** * <p> * The current state of the device. * </p> * * @param status * The current state of the device. * @see DeviceStatus */ public void setStatus(String status) { this.status = status; } /** * <p> * The current state of the device. * </p> * * @return The current state of the device. * @see DeviceStatus */ public String getStatus() { return this.status; } /** * <p> * The current state of the device. * </p> * * @param status * The current state of the device. * @return Returns a reference to this object so that method calls can be chained together. * @see DeviceStatus */ public DescribeDeviceResult withStatus(String status) { setStatus(status); return this; } /** * <p> * The current state of the device. * </p> * * @param status * The current state of the device. * @return Returns a reference to this object so that method calls can be chained together. * @see DeviceStatus */ public DescribeDeviceResult withStatus(DeviceStatus status) { this.status = status.toString(); return this; } /** * <p> * The model of the device. * </p> * * @param model * The model of the device. */ public void setModel(String model) { this.model = model; } /** * <p> * The model of the device. * </p> * * @return The model of the device. */ public String getModel() { return this.model; } /** * <p> * The model of the device. * </p> * * @param model * The model of the device. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDeviceResult withModel(String model) { setModel(model); return this; } /** * <p> * The manufacturer of the device. * </p> * * @param manufacturer * The manufacturer of the device. */ public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } /** * <p> * The manufacturer of the device. * </p> * * @return The manufacturer of the device. */ public String getManufacturer() { return this.manufacturer; } /** * <p> * The manufacturer of the device. * </p> * * @param manufacturer * The manufacturer of the device. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDeviceResult withManufacturer(String manufacturer) { setManufacturer(manufacturer); return this; } /** * <p> * The operating system of the device. * </p> * * @param operatingSystem * The operating system of the device. */ public void setOperatingSystem(String operatingSystem) { this.operatingSystem = operatingSystem; } /** * <p> * The operating system of the device. * </p> * * @return The operating system of the device. */ public String getOperatingSystem() { return this.operatingSystem; } /** * <p> * The operating system of the device. * </p> * * @param operatingSystem * The operating system of the device. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDeviceResult withOperatingSystem(String operatingSystem) { setOperatingSystem(operatingSystem); return this; } /** * <p> * The operating system version of the device. * </p> * * @param operatingSystemVersion * The operating system version of the device. */ public void setOperatingSystemVersion(String operatingSystemVersion) { this.operatingSystemVersion = operatingSystemVersion; } /** * <p> * The operating system version of the device. * </p> * * @return The operating system version of the device. */ public String getOperatingSystemVersion() { return this.operatingSystemVersion; } /** * <p> * The operating system version of the device. * </p> * * @param operatingSystemVersion * The operating system version of the device. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDeviceResult withOperatingSystemVersion(String operatingSystemVersion) { setOperatingSystemVersion(operatingSystemVersion); return this; } /** * <p> * The operating system patch level of the device. * </p> * * @param patchLevel * The operating system patch level of the device. */ public void setPatchLevel(String patchLevel) { this.patchLevel = patchLevel; } /** * <p> * The operating system patch level of the device. * </p> * * @return The operating system patch level of the device. */ public String getPatchLevel() { return this.patchLevel; } /** * <p> * The operating system patch level of the device. * </p> * * @param patchLevel * The operating system patch level of the device. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDeviceResult withPatchLevel(String patchLevel) { setPatchLevel(patchLevel); return this; } /** * <p> * The date that the device first signed in to Amazon WorkLink. * </p> * * @param firstAccessedTime * The date that the device first signed in to Amazon WorkLink. */ public void setFirstAccessedTime(java.util.Date firstAccessedTime) { this.firstAccessedTime = firstAccessedTime; } /** * <p> * The date that the device first signed in to Amazon WorkLink. * </p> * * @return The date that the device first signed in to Amazon WorkLink. */ public java.util.Date getFirstAccessedTime() { return this.firstAccessedTime; } /** * <p> * The date that the device first signed in to Amazon WorkLink. * </p> * * @param firstAccessedTime * The date that the device first signed in to Amazon WorkLink. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDeviceResult withFirstAccessedTime(java.util.Date firstAccessedTime) { setFirstAccessedTime(firstAccessedTime); return this; } /** * <p> * The date that the device last accessed Amazon WorkLink. * </p> * * @param lastAccessedTime * The date that the device last accessed Amazon WorkLink. */ public void setLastAccessedTime(java.util.Date lastAccessedTime) { this.lastAccessedTime = lastAccessedTime; } /** * <p> * The date that the device last accessed Amazon WorkLink. * </p> * * @return The date that the device last accessed Amazon WorkLink. */ public java.util.Date getLastAccessedTime() { return this.lastAccessedTime; } /** * <p> * The date that the device last accessed Amazon WorkLink. * </p> * * @param lastAccessedTime * The date that the device last accessed Amazon WorkLink. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDeviceResult withLastAccessedTime(java.util.Date lastAccessedTime) { setLastAccessedTime(lastAccessedTime); return this; } /** * <p> * The user name associated with the device. * </p> * * @param username * The user name associated with the device. */ public void setUsername(String username) { this.username = username; } /** * <p> * The user name associated with the device. * </p> * * @return The user name associated with the device. */ public String getUsername() { return this.username; } /** * <p> * The user name associated with the device. * </p> * * @param username * The user name associated with the device. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDeviceResult withUsername(String username) { setUsername(username); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getStatus() != null) sb.append("Status: ").append(getStatus()).append(","); if (getModel() != null) sb.append("Model: ").append(getModel()).append(","); if (getManufacturer() != null) sb.append("Manufacturer: ").append(getManufacturer()).append(","); if (getOperatingSystem() != null) sb.append("OperatingSystem: ").append(getOperatingSystem()).append(","); if (getOperatingSystemVersion() != null) sb.append("OperatingSystemVersion: ").append(getOperatingSystemVersion()).append(","); if (getPatchLevel() != null) sb.append("PatchLevel: ").append(getPatchLevel()).append(","); if (getFirstAccessedTime() != null) sb.append("FirstAccessedTime: ").append(getFirstAccessedTime()).append(","); if (getLastAccessedTime() != null) sb.append("LastAccessedTime: ").append(getLastAccessedTime()).append(","); if (getUsername() != null) sb.append("Username: ").append(getUsername()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeDeviceResult == false) return false; DescribeDeviceResult other = (DescribeDeviceResult) obj; if (other.getStatus() == null ^ this.getStatus() == null) return false; if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false) return false; if (other.getModel() == null ^ this.getModel() == null) return false; if (other.getModel() != null && other.getModel().equals(this.getModel()) == false) return false; if (other.getManufacturer() == null ^ this.getManufacturer() == null) return false; if (other.getManufacturer() != null && other.getManufacturer().equals(this.getManufacturer()) == false) return false; if (other.getOperatingSystem() == null ^ this.getOperatingSystem() == null) return false; if (other.getOperatingSystem() != null && other.getOperatingSystem().equals(this.getOperatingSystem()) == false) return false; if (other.getOperatingSystemVersion() == null ^ this.getOperatingSystemVersion() == null) return false; if (other.getOperatingSystemVersion() != null && other.getOperatingSystemVersion().equals(this.getOperatingSystemVersion()) == false) return false; if (other.getPatchLevel() == null ^ this.getPatchLevel() == null) return false; if (other.getPatchLevel() != null && other.getPatchLevel().equals(this.getPatchLevel()) == false) return false; if (other.getFirstAccessedTime() == null ^ this.getFirstAccessedTime() == null) return false; if (other.getFirstAccessedTime() != null && other.getFirstAccessedTime().equals(this.getFirstAccessedTime()) == false) return false; if (other.getLastAccessedTime() == null ^ this.getLastAccessedTime() == null) return false; if (other.getLastAccessedTime() != null && other.getLastAccessedTime().equals(this.getLastAccessedTime()) == false) return false; if (other.getUsername() == null ^ this.getUsername() == null) return false; if (other.getUsername() != null && other.getUsername().equals(this.getUsername()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode()); hashCode = prime * hashCode + ((getModel() == null) ? 0 : getModel().hashCode()); hashCode = prime * hashCode + ((getManufacturer() == null) ? 0 : getManufacturer().hashCode()); hashCode = prime * hashCode + ((getOperatingSystem() == null) ? 0 : getOperatingSystem().hashCode()); hashCode = prime * hashCode + ((getOperatingSystemVersion() == null) ? 0 : getOperatingSystemVersion().hashCode()); hashCode = prime * hashCode + ((getPatchLevel() == null) ? 0 : getPatchLevel().hashCode()); hashCode = prime * hashCode + ((getFirstAccessedTime() == null) ? 0 : getFirstAccessedTime().hashCode()); hashCode = prime * hashCode + ((getLastAccessedTime() == null) ? 0 : getLastAccessedTime().hashCode()); hashCode = prime * hashCode + ((getUsername() == null) ? 0 : getUsername().hashCode()); return hashCode; } @Override public DescribeDeviceResult clone() { try { return (DescribeDeviceResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
Java
// Java Genetic Algorithm Library. // Copyright (c) 2017 Franz Wilhelmstötter // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: // Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at) using System; using System.Collections.Generic; using Jenetics.Internal.Util; using Jenetics.Util; namespace Jenetics { [Serializable] public class DoubleChromosome : BoundedChromosomeBase<double, DoubleGene>, INumericChromosome<double, DoubleGene> { private DoubleChromosome(IImmutableSeq<DoubleGene> genes) : base(genes) { } public DoubleChromosome(double min, double max, int length = 1) : this(DoubleGene.Seq(min, max, length)) { Valid = true; } public override IEnumerator<DoubleGene> GetEnumerator() { return Genes.GetEnumerator(); } public override IChromosome<DoubleGene> NewInstance() { return new DoubleChromosome(Min, Max, Length); } public override IChromosome<DoubleGene> NewInstance(IImmutableSeq<DoubleGene> genes) { return new DoubleChromosome(genes); } public static DoubleChromosome Of(double min, double max) { return new DoubleChromosome(min, max); } public static DoubleChromosome Of(double min, double max, int length) { return new DoubleChromosome(min, max, length); } public static DoubleChromosome Of(DoubleRange range) { return new DoubleChromosome(range.Min, range.Max); } public static DoubleChromosome Of(params DoubleGene[] genes) { return new DoubleChromosome(ImmutableSeq.Of(genes)); } public override bool Equals(object obj) { return Equality.Of(this, obj)(base.Equals); } public override int GetHashCode() { return Hash.Of(GetType()).And(base.GetHashCode()).Value; } } }
Java
/* * Copyright 2012-2014 Netherlands eScience Center. * * 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 the following location: * * 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. * * For the full license, see: LICENSE.txt (located in the root folder of this distribution). * --- */ // source: package nl.esciencecenter.ptk.web; /** * Interface for Managed HTTP Streams. */ public interface WebStream { public boolean autoClose(); //public boolean isChunked(); }
Java
<?php /** * This file is part of the SevenShores/NetSuite library * AND originally from the NetSuite PHP Toolkit. * * New content: * @package ryanwinchester/netsuite-php * @copyright Copyright (c) Ryan Winchester * @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 * @link https://github.com/ryanwinchester/netsuite-php * * Original content: * @copyright Copyright (c) NetSuite Inc. * @license https://raw.githubusercontent.com/ryanwinchester/netsuite-php/master/original/NetSuite%20Application%20Developer%20License%20Agreement.txt * @link http://www.netsuite.com/portal/developers/resources/suitetalk-sample-applications.shtml * * generated: 2020-04-10 09:56:55 PM UTC */ namespace NetSuite\Classes; class Customer extends Record { /** * @var \NetSuite\Classes\RecordRef */ public $customForm; /** * @var string */ public $entityId; /** * @var string */ public $altName; /** * @var boolean */ public $isPerson; /** * @var string */ public $phoneticName; /** * @var string */ public $salutation; /** * @var string */ public $firstName; /** * @var string */ public $middleName; /** * @var string */ public $lastName; /** * @var string */ public $companyName; /** * @var \NetSuite\Classes\RecordRef */ public $entityStatus; /** * @var \NetSuite\Classes\RecordRef */ public $parent; /** * @var string */ public $phone; /** * @var string */ public $fax; /** * @var string */ public $email; /** * @var string */ public $url; /** * @var string */ public $defaultAddress; /** * @var boolean */ public $isInactive; /** * @var \NetSuite\Classes\RecordRef */ public $category; /** * @var string */ public $title; /** * @var string */ public $printOnCheckAs; /** * @var string */ public $altPhone; /** * @var string */ public $homePhone; /** * @var string */ public $mobilePhone; /** * @var string */ public $altEmail; /** * @var \NetSuite\Classes\Language */ public $language; /** * @var string */ public $comments; /** * @var \NetSuite\Classes\CustomerNumberFormat */ public $numberFormat; /** * @var \NetSuite\Classes\CustomerNegativeNumberFormat */ public $negativeNumberFormat; /** * @var string */ public $dateCreated; /** * @var \NetSuite\Classes\RecordRef */ public $image; /** * @var \NetSuite\Classes\EmailPreference */ public $emailPreference; /** * @var \NetSuite\Classes\RecordRef */ public $subsidiary; /** * @var \NetSuite\Classes\RecordRef */ public $representingSubsidiary; /** * @var \NetSuite\Classes\RecordRef */ public $salesRep; /** * @var \NetSuite\Classes\RecordRef */ public $territory; /** * @var string */ public $contribPct; /** * @var \NetSuite\Classes\RecordRef */ public $partner; /** * @var \NetSuite\Classes\RecordRef */ public $salesGroup; /** * @var string */ public $vatRegNumber; /** * @var string */ public $accountNumber; /** * @var boolean */ public $taxExempt; /** * @var \NetSuite\Classes\RecordRef */ public $terms; /** * @var float */ public $creditLimit; /** * @var \NetSuite\Classes\CustomerCreditHoldOverride */ public $creditHoldOverride; /** * @var \NetSuite\Classes\CustomerMonthlyClosing */ public $monthlyClosing; /** * @var boolean */ public $overrideCurrencyFormat; /** * @var string */ public $displaySymbol; /** * @var \NetSuite\Classes\CurrencySymbolPlacement */ public $symbolPlacement; /** * @var float */ public $balance; /** * @var float */ public $overdueBalance; /** * @var integer */ public $daysOverdue; /** * @var float */ public $unbilledOrders; /** * @var float */ public $consolUnbilledOrders; /** * @var float */ public $consolOverdueBalance; /** * @var float */ public $consolDepositBalance; /** * @var float */ public $consolBalance; /** * @var float */ public $consolAging; /** * @var float */ public $consolAging1; /** * @var float */ public $consolAging2; /** * @var float */ public $consolAging3; /** * @var float */ public $consolAging4; /** * @var integer */ public $consolDaysOverdue; /** * @var \NetSuite\Classes\RecordRef */ public $priceLevel; /** * @var \NetSuite\Classes\RecordRef */ public $currency; /** * @var \NetSuite\Classes\RecordRef */ public $prefCCProcessor; /** * @var float */ public $depositBalance; /** * @var boolean */ public $shipComplete; /** * @var boolean */ public $taxable; /** * @var \NetSuite\Classes\RecordRef */ public $taxItem; /** * @var string */ public $resaleNumber; /** * @var float */ public $aging; /** * @var float */ public $aging1; /** * @var float */ public $aging2; /** * @var float */ public $aging3; /** * @var float */ public $aging4; /** * @var string */ public $startDate; /** * @var \NetSuite\Classes\AlcoholRecipientType */ public $alcoholRecipientType; /** * @var string */ public $endDate; /** * @var integer */ public $reminderDays; /** * @var \NetSuite\Classes\RecordRef */ public $shippingItem; /** * @var string */ public $thirdPartyAcct; /** * @var string */ public $thirdPartyZipcode; /** * @var \NetSuite\Classes\Country */ public $thirdPartyCountry; /** * @var boolean */ public $giveAccess; /** * @var float */ public $estimatedBudget; /** * @var \NetSuite\Classes\RecordRef */ public $accessRole; /** * @var boolean */ public $sendEmail; /** * @var \NetSuite\Classes\RecordRef */ public $assignedWebSite; /** * @var string */ public $password; /** * @var string */ public $password2; /** * @var boolean */ public $requirePwdChange; /** * @var \NetSuite\Classes\RecordRef */ public $campaignCategory; /** * @var \NetSuite\Classes\RecordRef */ public $sourceWebSite; /** * @var \NetSuite\Classes\RecordRef */ public $leadSource; /** * @var \NetSuite\Classes\RecordRef */ public $receivablesAccount; /** * @var \NetSuite\Classes\RecordRef */ public $drAccount; /** * @var \NetSuite\Classes\RecordRef */ public $fxAccount; /** * @var float */ public $defaultOrderPriority; /** * @var string */ public $webLead; /** * @var string */ public $referrer; /** * @var string */ public $keywords; /** * @var string */ public $clickStream; /** * @var string */ public $lastPageVisited; /** * @var integer */ public $visits; /** * @var string */ public $firstVisit; /** * @var string */ public $lastVisit; /** * @var boolean */ public $billPay; /** * @var float */ public $openingBalance; /** * @var string */ public $lastModifiedDate; /** * @var string */ public $openingBalanceDate; /** * @var \NetSuite\Classes\RecordRef */ public $openingBalanceAccount; /** * @var \NetSuite\Classes\CustomerStage */ public $stage; /** * @var boolean */ public $emailTransactions; /** * @var boolean */ public $printTransactions; /** * @var boolean */ public $faxTransactions; /** * @var \NetSuite\Classes\RecordRef */ public $defaultTaxReg; /** * @var boolean */ public $syncPartnerTeams; /** * @var boolean */ public $isBudgetApproved; /** * @var \NetSuite\Classes\GlobalSubscriptionStatus */ public $globalSubscriptionStatus; /** * @var \NetSuite\Classes\RecordRef */ public $salesReadiness; /** * @var \NetSuite\Classes\CustomerSalesTeamList */ public $salesTeamList; /** * @var \NetSuite\Classes\RecordRef */ public $buyingReason; /** * @var \NetSuite\Classes\CustomerDownloadList */ public $downloadList; /** * @var \NetSuite\Classes\RecordRef */ public $buyingTimeFrame; /** * @var \NetSuite\Classes\CustomerAddressbookList */ public $addressbookList; /** * @var \NetSuite\Classes\SubscriptionsList */ public $subscriptionsList; /** * @var \NetSuite\Classes\ContactAccessRolesList */ public $contactRolesList; /** * @var \NetSuite\Classes\CustomerCurrencyList */ public $currencyList; /** * @var \NetSuite\Classes\CustomerCreditCardsList */ public $creditCardsList; /** * @var \NetSuite\Classes\CustomerPartnersList */ public $partnersList; /** * @var \NetSuite\Classes\CustomerGroupPricingList */ public $groupPricingList; /** * @var \NetSuite\Classes\CustomerItemPricingList */ public $itemPricingList; /** * @var \NetSuite\Classes\CustomerTaxRegistrationList */ public $taxRegistrationList; /** * @var \NetSuite\Classes\CustomFieldList */ public $customFieldList; /** * @var string */ public $internalId; /** * @var string */ public $externalId; static $paramtypesmap = array( "customForm" => "RecordRef", "entityId" => "string", "altName" => "string", "isPerson" => "boolean", "phoneticName" => "string", "salutation" => "string", "firstName" => "string", "middleName" => "string", "lastName" => "string", "companyName" => "string", "entityStatus" => "RecordRef", "parent" => "RecordRef", "phone" => "string", "fax" => "string", "email" => "string", "url" => "string", "defaultAddress" => "string", "isInactive" => "boolean", "category" => "RecordRef", "title" => "string", "printOnCheckAs" => "string", "altPhone" => "string", "homePhone" => "string", "mobilePhone" => "string", "altEmail" => "string", "language" => "Language", "comments" => "string", "numberFormat" => "CustomerNumberFormat", "negativeNumberFormat" => "CustomerNegativeNumberFormat", "dateCreated" => "dateTime", "image" => "RecordRef", "emailPreference" => "EmailPreference", "subsidiary" => "RecordRef", "representingSubsidiary" => "RecordRef", "salesRep" => "RecordRef", "territory" => "RecordRef", "contribPct" => "string", "partner" => "RecordRef", "salesGroup" => "RecordRef", "vatRegNumber" => "string", "accountNumber" => "string", "taxExempt" => "boolean", "terms" => "RecordRef", "creditLimit" => "float", "creditHoldOverride" => "CustomerCreditHoldOverride", "monthlyClosing" => "CustomerMonthlyClosing", "overrideCurrencyFormat" => "boolean", "displaySymbol" => "string", "symbolPlacement" => "CurrencySymbolPlacement", "balance" => "float", "overdueBalance" => "float", "daysOverdue" => "integer", "unbilledOrders" => "float", "consolUnbilledOrders" => "float", "consolOverdueBalance" => "float", "consolDepositBalance" => "float", "consolBalance" => "float", "consolAging" => "float", "consolAging1" => "float", "consolAging2" => "float", "consolAging3" => "float", "consolAging4" => "float", "consolDaysOverdue" => "integer", "priceLevel" => "RecordRef", "currency" => "RecordRef", "prefCCProcessor" => "RecordRef", "depositBalance" => "float", "shipComplete" => "boolean", "taxable" => "boolean", "taxItem" => "RecordRef", "resaleNumber" => "string", "aging" => "float", "aging1" => "float", "aging2" => "float", "aging3" => "float", "aging4" => "float", "startDate" => "dateTime", "alcoholRecipientType" => "AlcoholRecipientType", "endDate" => "dateTime", "reminderDays" => "integer", "shippingItem" => "RecordRef", "thirdPartyAcct" => "string", "thirdPartyZipcode" => "string", "thirdPartyCountry" => "Country", "giveAccess" => "boolean", "estimatedBudget" => "float", "accessRole" => "RecordRef", "sendEmail" => "boolean", "assignedWebSite" => "RecordRef", "password" => "string", "password2" => "string", "requirePwdChange" => "boolean", "campaignCategory" => "RecordRef", "sourceWebSite" => "RecordRef", "leadSource" => "RecordRef", "receivablesAccount" => "RecordRef", "drAccount" => "RecordRef", "fxAccount" => "RecordRef", "defaultOrderPriority" => "float", "webLead" => "string", "referrer" => "string", "keywords" => "string", "clickStream" => "string", "lastPageVisited" => "string", "visits" => "integer", "firstVisit" => "dateTime", "lastVisit" => "dateTime", "billPay" => "boolean", "openingBalance" => "float", "lastModifiedDate" => "dateTime", "openingBalanceDate" => "dateTime", "openingBalanceAccount" => "RecordRef", "stage" => "CustomerStage", "emailTransactions" => "boolean", "printTransactions" => "boolean", "faxTransactions" => "boolean", "defaultTaxReg" => "RecordRef", "syncPartnerTeams" => "boolean", "isBudgetApproved" => "boolean", "globalSubscriptionStatus" => "GlobalSubscriptionStatus", "salesReadiness" => "RecordRef", "salesTeamList" => "CustomerSalesTeamList", "buyingReason" => "RecordRef", "downloadList" => "CustomerDownloadList", "buyingTimeFrame" => "RecordRef", "addressbookList" => "CustomerAddressbookList", "subscriptionsList" => "SubscriptionsList", "contactRolesList" => "ContactAccessRolesList", "currencyList" => "CustomerCurrencyList", "creditCardsList" => "CustomerCreditCardsList", "partnersList" => "CustomerPartnersList", "groupPricingList" => "CustomerGroupPricingList", "itemPricingList" => "CustomerItemPricingList", "taxRegistrationList" => "CustomerTaxRegistrationList", "customFieldList" => "CustomFieldList", "internalId" => "string", "externalId" => "string", ); }
Java
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.honeycode; import javax.annotation.Generated; import com.amazonaws.ClientConfigurationFactory; import com.amazonaws.annotation.NotThreadSafe; import com.amazonaws.client.builder.AwsSyncClientBuilder; import com.amazonaws.client.AwsSyncClientParams; /** * Fluent builder for {@link com.amazonaws.services.honeycode.AmazonHoneycode}. Use of the builder is preferred over * using constructors of the client class. **/ @NotThreadSafe @Generated("com.amazonaws:aws-java-sdk-code-generator") public final class AmazonHoneycodeClientBuilder extends AwsSyncClientBuilder<AmazonHoneycodeClientBuilder, AmazonHoneycode> { private static final ClientConfigurationFactory CLIENT_CONFIG_FACTORY = new ClientConfigurationFactory(); /** * @return Create new instance of builder with all defaults set. */ public static AmazonHoneycodeClientBuilder standard() { return new AmazonHoneycodeClientBuilder(); } /** * @return Default client using the {@link com.amazonaws.auth.DefaultAWSCredentialsProviderChain} and * {@link com.amazonaws.regions.DefaultAwsRegionProviderChain} chain */ public static AmazonHoneycode defaultClient() { return standard().build(); } private AmazonHoneycodeClientBuilder() { super(CLIENT_CONFIG_FACTORY); } /** * Construct a synchronous implementation of AmazonHoneycode using the current builder configuration. * * @param params * Current builder configuration represented as a parameter object. * @return Fully configured implementation of AmazonHoneycode. */ @Override protected AmazonHoneycode build(AwsSyncClientParams params) { return new AmazonHoneycodeClient(params); } }
Java
namespace ts { describe("TransformAPI", () => { function replaceUndefinedWithVoid0(context: TransformationContext) { const previousOnSubstituteNode = context.onSubstituteNode; context.enableSubstitution(SyntaxKind.Identifier); context.onSubstituteNode = (hint, node) => { node = previousOnSubstituteNode(hint, node); if (hint === EmitHint.Expression && isIdentifier(node) && node.escapedText === "undefined") { node = createPartiallyEmittedExpression( addSyntheticTrailingComment( setTextRange( createVoidZero(), node), SyntaxKind.MultiLineCommentTrivia, "undefined")); } return node; }; return (file: SourceFile) => file; } function replaceNumberWith2(context: TransformationContext) { function visitor(node: Node): Node { if (isNumericLiteral(node)) { return createNumericLiteral("2"); } return visitEachChild(node, visitor, context); } return (file: SourceFile) => visitNode(file, visitor); } function replaceIdentifiersNamedOldNameWithNewName(context: TransformationContext) { const previousOnSubstituteNode = context.onSubstituteNode; context.enableSubstitution(SyntaxKind.Identifier); context.onSubstituteNode = (hint, node) => { node = previousOnSubstituteNode(hint, node); if (isIdentifier(node) && node.escapedText === "oldName") { node = setTextRange(createIdentifier("newName"), node); } return node; }; return (file: SourceFile) => file; } function replaceIdentifiersNamedOldNameWithNewName2(context: TransformationContext) { const visitor: Visitor = (node) => { if (isIdentifier(node) && node.text === "oldName") { return createIdentifier("newName"); } return visitEachChild(node, visitor, context); }; return (node: SourceFile) => visitNode(node, visitor); } function transformSourceFile(sourceText: string, transformers: TransformerFactory<SourceFile>[]) { const transformed = transform(createSourceFile("source.ts", sourceText, ScriptTarget.ES2015), transformers); const printer = createPrinter({ newLine: NewLineKind.CarriageReturnLineFeed }, { onEmitNode: transformed.emitNodeWithNotification, substituteNode: transformed.substituteNode }); const result = printer.printBundle(createBundle(transformed.transformed)); transformed.dispose(); return result; } function testBaseline(testName: string, test: () => string) { it(testName, () => { Harness.Baseline.runBaseline(`transformApi/transformsCorrectly.${testName}.js`, test()); }); } testBaseline("substitution", () => { return transformSourceFile(`var a = undefined;`, [replaceUndefinedWithVoid0]); }); testBaseline("types", () => { return transformSourceFile(`let a: () => void`, [ context => file => visitNode(file, function visitor(node: Node): VisitResult<Node> { return visitEachChild(node, visitor, context); }) ]); }); testBaseline("fromTranspileModule", () => { return transpileModule(`var oldName = undefined;`, { transformers: { before: [replaceUndefinedWithVoid0], after: [replaceIdentifiersNamedOldNameWithNewName] }, compilerOptions: { newLine: NewLineKind.CarriageReturnLineFeed } }).outputText; }); testBaseline("issue27854", () => { return transpileModule(`oldName<{ a: string; }>\` ... \`;`, { transformers: { before: [replaceIdentifiersNamedOldNameWithNewName2] }, compilerOptions: { newLine: NewLineKind.CarriageReturnLineFeed, target: ScriptTarget.Latest } }).outputText; }); testBaseline("rewrittenNamespace", () => { return transpileModule(`namespace Reflect { const x = 1; }`, { transformers: { before: [forceNamespaceRewrite], }, compilerOptions: { newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; }); testBaseline("rewrittenNamespaceFollowingClass", () => { return transpileModule(` class C { foo = 10; static bar = 20 } namespace C { export let x = 10; } `, { transformers: { before: [forceNamespaceRewrite], }, compilerOptions: { target: ScriptTarget.ESNext, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; }); testBaseline("transformTypesInExportDefault", () => { return transpileModule(` export default (foo: string) => { return 1; } `, { transformers: { before: [replaceNumberWith2], }, compilerOptions: { target: ScriptTarget.ESNext, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; }); testBaseline("synthesizedClassAndNamespaceCombination", () => { return transpileModule("", { transformers: { before: [replaceWithClassAndNamespace], }, compilerOptions: { target: ScriptTarget.ESNext, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; function replaceWithClassAndNamespace() { return (sourceFile: SourceFile) => { const result = getMutableClone(sourceFile); result.statements = createNodeArray([ createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, "Foo", /*typeParameters*/ undefined, /*heritageClauses*/ undefined, /*members*/ undefined!), // TODO: GH#18217 createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createIdentifier("Foo"), createModuleBlock([createEmptyStatement()])) ]); return result; }; } }); function forceNamespaceRewrite(context: TransformationContext) { return (sourceFile: SourceFile): SourceFile => { return visitNode(sourceFile); function visitNode<T extends Node>(node: T): T { if (node.kind === SyntaxKind.ModuleBlock) { const block = node as T & ModuleBlock; const statements = createNodeArray([...block.statements]); return updateModuleBlock(block, statements) as typeof block; } return visitEachChild(node, visitNode, context); } }; } testBaseline("transformAwayExportStar", () => { return transpileModule("export * from './helper';", { transformers: { before: [expandExportStar], }, compilerOptions: { target: ScriptTarget.ESNext, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; function expandExportStar(context: TransformationContext) { return (sourceFile: SourceFile): SourceFile => { return visitNode(sourceFile); function visitNode<T extends Node>(node: T): T { if (node.kind === SyntaxKind.ExportDeclaration) { const ed = node as Node as ExportDeclaration; const exports = [{ name: "x" }]; const exportSpecifiers = exports.map(e => createExportSpecifier(e.name, e.name)); const exportClause = createNamedExports(exportSpecifiers); const newEd = updateExportDeclaration(ed, ed.decorators, ed.modifiers, exportClause, ed.moduleSpecifier); return newEd as Node as T; } return visitEachChild(node, visitNode, context); } }; } }); // https://github.com/Microsoft/TypeScript/issues/19618 testBaseline("transformAddImportStar", () => { return transpileModule("", { transformers: { before: [transformAddImportStar], }, compilerOptions: { target: ScriptTarget.ES5, module: ModuleKind.System, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; function transformAddImportStar(_context: TransformationContext) { return (sourceFile: SourceFile): SourceFile => { return visitNode(sourceFile); }; function visitNode(sf: SourceFile) { // produce `import * as i0 from './comp'; const importStar = createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ createImportClause( /*name*/ undefined, createNamespaceImport(createIdentifier("i0")) ), /*moduleSpecifier*/ createLiteral("./comp1")); return updateSourceFileNode(sf, [importStar]); } } }); // https://github.com/Microsoft/TypeScript/issues/17384 testBaseline("transformAddDecoratedNode", () => { return transpileModule("", { transformers: { before: [transformAddDecoratedNode], }, compilerOptions: { target: ScriptTarget.ES5, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; function transformAddDecoratedNode(_context: TransformationContext) { return (sourceFile: SourceFile): SourceFile => { return visitNode(sourceFile); }; function visitNode(sf: SourceFile) { // produce `class Foo { @Bar baz() {} }`; const classDecl = createClassDeclaration([], [], "Foo", /*typeParameters*/ undefined, /*heritageClauses*/ undefined, [ createMethod([createDecorator(createIdentifier("Bar"))], [], /**/ undefined, "baz", /**/ undefined, /**/ undefined, [], /**/ undefined, createBlock([])) ]); return updateSourceFileNode(sf, [classDecl]); } } }); testBaseline("transformDeclarationFile", () => { return baselineDeclarationTransform(`var oldName = undefined;`, { transformers: { afterDeclarations: [replaceIdentifiersNamedOldNameWithNewName] }, compilerOptions: { newLine: NewLineKind.CarriageReturnLineFeed, declaration: true } }); }); function baselineDeclarationTransform(text: string, opts: TranspileOptions) { const fs = vfs.createFromFileSystem(Harness.IO, /*caseSensitive*/ true, { documents: [new documents.TextDocument("/.src/index.ts", text)] }); const host = new fakes.CompilerHost(fs, opts.compilerOptions); const program = createProgram(["/.src/index.ts"], opts.compilerOptions!, host); program.emit(program.getSourceFile("/.src/index.ts"), (p, s, bom) => host.writeFile(p, s, bom), /*cancellationToken*/ undefined, /*onlyDts*/ true, opts.transformers); return fs.readFileSync("/.src/index.d.ts").toString(); } function addSyntheticComment(nodeFilter: (node: Node) => boolean) { return (context: TransformationContext) => { return (sourceFile: SourceFile): SourceFile => { return visitNode(sourceFile, rootTransform, isSourceFile); }; function rootTransform<T extends Node>(node: T): VisitResult<T> { if (nodeFilter(node)) { setEmitFlags(node, EmitFlags.NoLeadingComments); setSyntheticLeadingComments(node, [{ kind: SyntaxKind.MultiLineCommentTrivia, text: "comment", pos: -1, end: -1, hasTrailingNewLine: true }]); } return visitEachChild(node, rootTransform, context); } }; } // https://github.com/Microsoft/TypeScript/issues/24096 testBaseline("transformAddCommentToArrowReturnValue", () => { return transpileModule(`const foo = () => void 0 `, { transformers: { before: [addSyntheticComment(isVoidExpression)], }, compilerOptions: { target: ScriptTarget.ES5, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; }); // https://github.com/Microsoft/TypeScript/issues/17594 testBaseline("transformAddCommentToExportedVar", () => { return transpileModule(`export const exportedDirectly = 1; const exportedSeparately = 2; export {exportedSeparately}; `, { transformers: { before: [addSyntheticComment(isVariableStatement)], }, compilerOptions: { target: ScriptTarget.ES5, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; }); // https://github.com/Microsoft/TypeScript/issues/17594 testBaseline("transformAddCommentToImport", () => { return transpileModule(` // Previous comment on import. import {Value} from 'somewhere'; import * as X from 'somewhere'; // Previous comment on export. export { /* specifier comment */ X, Y} from 'somewhere'; export * from 'somewhere'; export {Value}; `, { transformers: { before: [addSyntheticComment(n => isImportDeclaration(n) || isExportDeclaration(n) || isImportSpecifier(n) || isExportSpecifier(n))], }, compilerOptions: { target: ScriptTarget.ES5, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; }); // https://github.com/Microsoft/TypeScript/issues/17594 testBaseline("transformAddCommentToProperties", () => { return transpileModule(` // class comment. class Clazz { // original comment 1. static staticProp: number = 1; // original comment 2. instanceProp: number = 2; // original comment 3. constructor(readonly field = 1) {} } `, { transformers: { before: [addSyntheticComment(n => isPropertyDeclaration(n) || isParameterPropertyDeclaration(n) || isClassDeclaration(n) || isConstructorDeclaration(n))], }, compilerOptions: { target: ScriptTarget.ES2015, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; }); testBaseline("transformAddCommentToNamespace", () => { return transpileModule(` // namespace comment. namespace Foo { export const x = 1; } // another comment. namespace Foo { export const y = 1; } `, { transformers: { before: [addSyntheticComment(n => isModuleDeclaration(n))], }, compilerOptions: { target: ScriptTarget.ES2015, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; }); }); }
Java
package lm.com.framework.encrypt; import java.io.IOException; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; public class DESEncrypt { private final static String DES = "DES"; /** * des加密 * * @param encryptString * @param key * @return * @throws Exception */ public static String encode(String encryptString, String key) throws Exception { byte[] bt = encrypt(encryptString.getBytes(), key.getBytes()); String strs = new BASE64Encoder().encode(bt); return strs; } /** * des解密 * * @param decryptString * @param key * @return * @throws IOException * @throws Exception */ public static String decode(String decryptString, String key) throws IOException, Exception { if (decryptString == null || decryptString.trim().isEmpty()) return ""; BASE64Decoder decoder = new BASE64Decoder(); byte[] buf = decoder.decodeBuffer(decryptString); byte[] bt = decrypt(buf, key.getBytes()); return new String(bt); } /** * 根据键值进行加密 */ private static byte[] encrypt(byte[] data, byte[] key) throws Exception { Cipher cipher = cipherInit(data, key, Cipher.ENCRYPT_MODE); return cipher.doFinal(data); } /** * 根据键值进行解密 */ private static byte[] decrypt(byte[] data, byte[] key) throws Exception { Cipher cipher = cipherInit(data, key, Cipher.DECRYPT_MODE); return cipher.doFinal(data); } private static Cipher cipherInit(byte[] data, byte[] key, int cipherValue) throws Exception { /** 生成一个可信任的随机数源 **/ SecureRandom sr = new SecureRandom(); /** 从原始密钥数据创建DESKeySpec对象 **/ DESKeySpec dks = new DESKeySpec(key); /** 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象 **/ SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); /** Cipher对象实际完成加密或解密操作 **/ Cipher cipher = Cipher.getInstance(DES); /** 用密钥初始化Cipher对象 **/ cipher.init(cipherValue, securekey, sr); return cipher; } }
Java
package com.desple.view; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class PreviewImageCanvas extends JPanel { private BufferedImage image; public PreviewImageCanvas() { image = null; } public Dimension getPreferredSize() { return new Dimension(512, 512); } public void paintComponent(Graphics g) { super.paintComponent(g); if (this.image != null) { g.drawImage(this.image, 0, 0, 512, 512, this); } } public void loadImage(String imageLocation) throws IOException { this.image = ImageIO.read(new File(imageLocation)); repaint(); } public BufferedImage getImage() { return this.image; } public void setImage(BufferedImage image) { this.image = image; repaint(); } }
Java
// Copyright 2015 CoreOS, 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 rafthttp import ( "errors" "fmt" "io/ioutil" "net/http" "path" "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context" pioutil "github.com/coreos/etcd/pkg/ioutil" "github.com/coreos/etcd/pkg/types" "github.com/coreos/etcd/raft/raftpb" "github.com/coreos/etcd/snap" "github.com/coreos/etcd/version" ) const ( // connReadLimitByte limits the number of bytes // a single read can read out. // // 64KB should be large enough for not causing // throughput bottleneck as well as small enough // for not causing a read timeout. connReadLimitByte = 64 * 1024 ) var ( RaftPrefix = "/raft" ProbingPrefix = path.Join(RaftPrefix, "probing") RaftStreamPrefix = path.Join(RaftPrefix, "stream") RaftSnapshotPrefix = path.Join(RaftPrefix, "snapshot") errIncompatibleVersion = errors.New("incompatible version") errClusterIDMismatch = errors.New("cluster ID mismatch") ) type peerGetter interface { Get(id types.ID) Peer } type writerToResponse interface { WriteTo(w http.ResponseWriter) } type pipelineHandler struct { r Raft cid types.ID } // newPipelineHandler returns a handler for handling raft messages // from pipeline for RaftPrefix. // // The handler reads out the raft message from request body, // and forwards it to the given raft state machine for processing. func newPipelineHandler(r Raft, cid types.ID) http.Handler { return &pipelineHandler{ r: r, cid: cid, } } func (h *pipelineHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { w.Header().Set("Allow", "POST") http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed) return } w.Header().Set("X-Etcd-Cluster-ID", h.cid.String()) if err := checkClusterCompatibilityFromHeader(r.Header, h.cid); err != nil { http.Error(w, err.Error(), http.StatusPreconditionFailed) return } // Limit the data size that could be read from the request body, which ensures that read from // connection will not time out accidentally due to possible blocking in underlying implementation. limitedr := pioutil.NewLimitedBufferReader(r.Body, connReadLimitByte) b, err := ioutil.ReadAll(limitedr) if err != nil { plog.Errorf("failed to read raft message (%v)", err) http.Error(w, "error reading raft message", http.StatusBadRequest) return } var m raftpb.Message if err := m.Unmarshal(b); err != nil { plog.Errorf("failed to unmarshal raft message (%v)", err) http.Error(w, "error unmarshaling raft message", http.StatusBadRequest) return } if err := h.r.Process(context.TODO(), m); err != nil { switch v := err.(type) { case writerToResponse: v.WriteTo(w) default: plog.Warningf("failed to process raft message (%v)", err) http.Error(w, "error processing raft message", http.StatusInternalServerError) } return } // Write StatusNoContet header after the message has been processed by // raft, which facilitates the client to report MsgSnap status. w.WriteHeader(http.StatusNoContent) } type snapshotHandler struct { r Raft snapshotter *snap.Snapshotter cid types.ID } func newSnapshotHandler(r Raft, snapshotter *snap.Snapshotter, cid types.ID) http.Handler { return &snapshotHandler{ r: r, snapshotter: snapshotter, cid: cid, } } // ServeHTTP serves HTTP request to receive and process snapshot message. // // If request sender dies without closing underlying TCP connection, // the handler will keep waiting for the request body until TCP keepalive // finds out that the connection is broken after several minutes. // This is acceptable because // 1. snapshot messages sent through other TCP connections could still be // received and processed. // 2. this case should happen rarely, so no further optimization is done. func (h *snapshotHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { w.Header().Set("Allow", "POST") http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed) return } w.Header().Set("X-Etcd-Cluster-ID", h.cid.String()) if err := checkClusterCompatibilityFromHeader(r.Header, h.cid); err != nil { http.Error(w, err.Error(), http.StatusPreconditionFailed) return } dec := &messageDecoder{r: r.Body} m, err := dec.decode() if err != nil { msg := fmt.Sprintf("failed to decode raft message (%v)", err) plog.Errorf(msg) http.Error(w, msg, http.StatusBadRequest) return } if m.Type != raftpb.MsgSnap { plog.Errorf("unexpected raft message type %s on snapshot path", m.Type) http.Error(w, "wrong raft message type", http.StatusBadRequest) return } // save incoming database snapshot. if err := h.snapshotter.SaveDBFrom(r.Body, m.Snapshot.Metadata.Index); err != nil { msg := fmt.Sprintf("failed to save KV snapshot (%v)", err) plog.Error(msg) http.Error(w, msg, http.StatusInternalServerError) return } plog.Infof("received and saved database snapshot [index: %d, from: %s] successfully", m.Snapshot.Metadata.Index, types.ID(m.From)) if err := h.r.Process(context.TODO(), m); err != nil { switch v := err.(type) { // Process may return writerToResponse error when doing some // additional checks before calling raft.Node.Step. case writerToResponse: v.WriteTo(w) default: msg := fmt.Sprintf("failed to process raft message (%v)", err) plog.Warningf(msg) http.Error(w, msg, http.StatusInternalServerError) } return } // Write StatusNoContet header after the message has been processed by // raft, which facilitates the client to report MsgSnap status. w.WriteHeader(http.StatusNoContent) } type streamHandler struct { peerGetter peerGetter r Raft id types.ID cid types.ID } func newStreamHandler(peerGetter peerGetter, r Raft, id, cid types.ID) http.Handler { return &streamHandler{ peerGetter: peerGetter, r: r, id: id, cid: cid, } } func (h *streamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { w.Header().Set("Allow", "GET") http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed) return } w.Header().Set("X-Server-Version", version.Version) w.Header().Set("X-Etcd-Cluster-ID", h.cid.String()) if err := checkClusterCompatibilityFromHeader(r.Header, h.cid); err != nil { http.Error(w, err.Error(), http.StatusPreconditionFailed) return } var t streamType switch path.Dir(r.URL.Path) { case streamTypeMsgAppV2.endpoint(): t = streamTypeMsgAppV2 case streamTypeMessage.endpoint(): t = streamTypeMessage default: plog.Debugf("ignored unexpected streaming request path %s", r.URL.Path) http.Error(w, "invalid path", http.StatusNotFound) return } fromStr := path.Base(r.URL.Path) from, err := types.IDFromString(fromStr) if err != nil { plog.Errorf("failed to parse from %s into ID (%v)", fromStr, err) http.Error(w, "invalid from", http.StatusNotFound) return } if h.r.IsIDRemoved(uint64(from)) { plog.Warningf("rejected the stream from peer %s since it was removed", from) http.Error(w, "removed member", http.StatusGone) return } p := h.peerGetter.Get(from) if p == nil { // This may happen in following cases: // 1. user starts a remote peer that belongs to a different cluster // with the same cluster ID. // 2. local etcd falls behind of the cluster, and cannot recognize // the members that joined after its current progress. plog.Errorf("failed to find member %s in cluster %s", from, h.cid) http.Error(w, "error sender not found", http.StatusNotFound) return } wto := h.id.String() if gto := r.Header.Get("X-Raft-To"); gto != wto { plog.Errorf("streaming request ignored (ID mismatch got %s want %s)", gto, wto) http.Error(w, "to field mismatch", http.StatusPreconditionFailed) return } w.WriteHeader(http.StatusOK) w.(http.Flusher).Flush() c := newCloseNotifier() conn := &outgoingConn{ t: t, Writer: w, Flusher: w.(http.Flusher), Closer: c, } p.attachOutgoingConn(conn) <-c.closeNotify() } // checkClusterCompatibilityFromHeader checks the cluster compatibility of // the local member from the given header. // It checks whether the version of local member is compatible with // the versions in the header, and whether the cluster ID of local member // matches the one in the header. func checkClusterCompatibilityFromHeader(header http.Header, cid types.ID) error { if err := checkVersionCompability(header.Get("X-Server-From"), serverVersion(header), minClusterVersion(header)); err != nil { plog.Errorf("request version incompatibility (%v)", err) return errIncompatibleVersion } if gcid := header.Get("X-Etcd-Cluster-ID"); gcid != cid.String() { plog.Errorf("request cluster ID mismatch (got %s want %s)", gcid, cid) return errClusterIDMismatch } return nil } type closeNotifier struct { done chan struct{} } func newCloseNotifier() *closeNotifier { return &closeNotifier{ done: make(chan struct{}), } } func (n *closeNotifier) Close() error { close(n.done) return nil } func (n *closeNotifier) closeNotify() <-chan struct{} { return n.done }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_79) on Wed Apr 29 14:47:00 PDT 2015 --> <title>org.apache.nutch.crawl (apache-nutch 1.10 API)</title> <meta name="date" content="2015-04-29"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <h1 class="bar"><a href="../../../../org/apache/nutch/crawl/package-summary.html" target="classFrame">org.apache.nutch.crawl</a></h1> <div class="indexContainer"> <h2 title="Interfaces">Interfaces</h2> <ul title="Interfaces"> <li><a href="FetchSchedule.html" title="interface in org.apache.nutch.crawl" target="classFrame"><i>FetchSchedule</i></a></li> </ul> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="AbstractFetchSchedule.html" title="class in org.apache.nutch.crawl" target="classFrame">AbstractFetchSchedule</a></li> <li><a href="AdaptiveFetchSchedule.html" title="class in org.apache.nutch.crawl" target="classFrame">AdaptiveFetchSchedule</a></li> <li><a href="CrawlDatum.html" title="class in org.apache.nutch.crawl" target="classFrame">CrawlDatum</a></li> <li><a href="CrawlDatum.Comparator.html" title="class in org.apache.nutch.crawl" target="classFrame">CrawlDatum.Comparator</a></li> <li><a href="CrawlDb.html" title="class in org.apache.nutch.crawl" target="classFrame">CrawlDb</a></li> <li><a href="CrawlDbFilter.html" title="class in org.apache.nutch.crawl" target="classFrame">CrawlDbFilter</a></li> <li><a href="CrawlDbMerger.html" title="class in org.apache.nutch.crawl" target="classFrame">CrawlDbMerger</a></li> <li><a href="CrawlDbMerger.Merger.html" title="class in org.apache.nutch.crawl" target="classFrame">CrawlDbMerger.Merger</a></li> <li><a href="CrawlDbReader.html" title="class in org.apache.nutch.crawl" target="classFrame">CrawlDbReader</a></li> <li><a href="CrawlDbReader.CrawlDatumCsvOutputFormat.html" title="class in org.apache.nutch.crawl" target="classFrame">CrawlDbReader.CrawlDatumCsvOutputFormat</a></li> <li><a href="CrawlDbReader.CrawlDatumCsvOutputFormat.LineRecordWriter.html" title="class in org.apache.nutch.crawl" target="classFrame">CrawlDbReader.CrawlDatumCsvOutputFormat.LineRecordWriter</a></li> <li><a href="CrawlDbReader.CrawlDbDumpMapper.html" title="class in org.apache.nutch.crawl" target="classFrame">CrawlDbReader.CrawlDbDumpMapper</a></li> <li><a href="CrawlDbReader.CrawlDbStatCombiner.html" title="class in org.apache.nutch.crawl" target="classFrame">CrawlDbReader.CrawlDbStatCombiner</a></li> <li><a href="CrawlDbReader.CrawlDbStatMapper.html" title="class in org.apache.nutch.crawl" target="classFrame">CrawlDbReader.CrawlDbStatMapper</a></li> <li><a href="CrawlDbReader.CrawlDbStatReducer.html" title="class in org.apache.nutch.crawl" target="classFrame">CrawlDbReader.CrawlDbStatReducer</a></li> <li><a href="CrawlDbReader.CrawlDbTopNMapper.html" title="class in org.apache.nutch.crawl" target="classFrame">CrawlDbReader.CrawlDbTopNMapper</a></li> <li><a href="CrawlDbReader.CrawlDbTopNReducer.html" title="class in org.apache.nutch.crawl" target="classFrame">CrawlDbReader.CrawlDbTopNReducer</a></li> <li><a href="CrawlDbReducer.html" title="class in org.apache.nutch.crawl" target="classFrame">CrawlDbReducer</a></li> <li><a href="DeduplicationJob.html" title="class in org.apache.nutch.crawl" target="classFrame">DeduplicationJob</a></li> <li><a href="DeduplicationJob.DBFilter.html" title="class in org.apache.nutch.crawl" target="classFrame">DeduplicationJob.DBFilter</a></li> <li><a href="DeduplicationJob.DedupReducer.html" title="class in org.apache.nutch.crawl" target="classFrame">DeduplicationJob.DedupReducer</a></li> <li><a href="DeduplicationJob.StatusUpdateReducer.html" title="class in org.apache.nutch.crawl" target="classFrame">DeduplicationJob.StatusUpdateReducer</a></li> <li><a href="DefaultFetchSchedule.html" title="class in org.apache.nutch.crawl" target="classFrame">DefaultFetchSchedule</a></li> <li><a href="FetchScheduleFactory.html" title="class in org.apache.nutch.crawl" target="classFrame">FetchScheduleFactory</a></li> <li><a href="Generator.html" title="class in org.apache.nutch.crawl" target="classFrame">Generator</a></li> <li><a href="Generator.CrawlDbUpdater.html" title="class in org.apache.nutch.crawl" target="classFrame">Generator.CrawlDbUpdater</a></li> <li><a href="Generator.DecreasingFloatComparator.html" title="class in org.apache.nutch.crawl" target="classFrame">Generator.DecreasingFloatComparator</a></li> <li><a href="Generator.GeneratorOutputFormat.html" title="class in org.apache.nutch.crawl" target="classFrame">Generator.GeneratorOutputFormat</a></li> <li><a href="Generator.HashComparator.html" title="class in org.apache.nutch.crawl" target="classFrame">Generator.HashComparator</a></li> <li><a href="Generator.PartitionReducer.html" title="class in org.apache.nutch.crawl" target="classFrame">Generator.PartitionReducer</a></li> <li><a href="Generator.Selector.html" title="class in org.apache.nutch.crawl" target="classFrame">Generator.Selector</a></li> <li><a href="Generator.SelectorEntry.html" title="class in org.apache.nutch.crawl" target="classFrame">Generator.SelectorEntry</a></li> <li><a href="Generator.SelectorInverseMapper.html" title="class in org.apache.nutch.crawl" target="classFrame">Generator.SelectorInverseMapper</a></li> <li><a href="Injector.html" title="class in org.apache.nutch.crawl" target="classFrame">Injector</a></li> <li><a href="Injector.InjectMapper.html" title="class in org.apache.nutch.crawl" target="classFrame">Injector.InjectMapper</a></li> <li><a href="Injector.InjectReducer.html" title="class in org.apache.nutch.crawl" target="classFrame">Injector.InjectReducer</a></li> <li><a href="Inlink.html" title="class in org.apache.nutch.crawl" target="classFrame">Inlink</a></li> <li><a href="Inlinks.html" title="class in org.apache.nutch.crawl" target="classFrame">Inlinks</a></li> <li><a href="LinkDb.html" title="class in org.apache.nutch.crawl" target="classFrame">LinkDb</a></li> <li><a href="LinkDbFilter.html" title="class in org.apache.nutch.crawl" target="classFrame">LinkDbFilter</a></li> <li><a href="LinkDbMerger.html" title="class in org.apache.nutch.crawl" target="classFrame">LinkDbMerger</a></li> <li><a href="LinkDbReader.html" title="class in org.apache.nutch.crawl" target="classFrame">LinkDbReader</a></li> <li><a href="LinkDbReader.LinkDBDumpMapper.html" title="class in org.apache.nutch.crawl" target="classFrame">LinkDbReader.LinkDBDumpMapper</a></li> <li><a href="MapWritable.html" title="class in org.apache.nutch.crawl" target="classFrame">MapWritable</a></li> <li><a href="MD5Signature.html" title="class in org.apache.nutch.crawl" target="classFrame">MD5Signature</a></li> <li><a href="MimeAdaptiveFetchSchedule.html" title="class in org.apache.nutch.crawl" target="classFrame">MimeAdaptiveFetchSchedule</a></li> <li><a href="NutchWritable.html" title="class in org.apache.nutch.crawl" target="classFrame">NutchWritable</a></li> <li><a href="Signature.html" title="class in org.apache.nutch.crawl" target="classFrame">Signature</a></li> <li><a href="SignatureComparator.html" title="class in org.apache.nutch.crawl" target="classFrame">SignatureComparator</a></li> <li><a href="SignatureFactory.html" title="class in org.apache.nutch.crawl" target="classFrame">SignatureFactory</a></li> <li><a href="TextMD5Signature.html" title="class in org.apache.nutch.crawl" target="classFrame">TextMD5Signature</a></li> <li><a href="TextProfileSignature.html" title="class in org.apache.nutch.crawl" target="classFrame">TextProfileSignature</a></li> <li><a href="URLPartitioner.html" title="class in org.apache.nutch.crawl" target="classFrame">URLPartitioner</a></li> </ul> </div> </body> </html>
Java
<?php class _Upload { private static $files = array(); /** * Takes a $_FILES array and standardizes it to be the same regardless of number of uploads * * @param array $files Files array to standardize * @return void */ public static function standardizeFileUploads($files=array()) { if (!count($files)) { return $files; } // loop through files to standardize foreach ($files as $field => $data) { if (!isset(self::$files[$field]) || !is_array(self::$files[$field])) { self::$files[$field] = array(); } $data = array( 'name' => $data['name'], 'type' => $data['type'], 'tmp_name' => $data['tmp_name'], 'size' => $data['size'], 'error' => $data['error'] ); // loop through _FILES to standardize foreach ($data as $key => $value) { self::buildFileArray($key, $value, self::$files[$field], $field); } } // return our cleaner version return self::$files; } /** * Recursively builds an array of files * * @param string $key Upload key that we're processing * @param mixed $value Either a string or an array of the value * @param array $output The referenced array object for manipulation * @param string $path A string for colon-delimited path searching * @return void */ private static function buildFileArray($key, $value, &$output, $path) { if (is_array($value)) { foreach ($value as $sub_key => $sub_value) { if (!isset($output[$sub_key]) || !is_array($output[$sub_key])) { $output[$sub_key] = array(); } $new_path = (empty($path)) ? $sub_key : $path . ':' . $sub_key; self::buildFileArray($key, $sub_value, $output[$sub_key], $new_path); } } else { $output[$key] = $value; // add error message if ($key === 'error') { $error_message = self::getFriendlyErrorMessage($value); $success_status = ($value === UPLOAD_ERR_OK); $output['error_message'] = $error_message; $output['success'] = $success_status; } elseif ($key === 'size') { $human_readable_size = File::getHumanSize($value); $output['size_human_readable'] = $human_readable_size; } } } /** * Create friendly error messages for upload issues * * @param int $error Error int * @return string */ private static function getFriendlyErrorMessage($error) { // these errors are PHP-based if ($error === UPLOAD_ERR_OK) { return ''; } elseif ($error === UPLOAD_ERR_INI_SIZE) { return Localization::fetch('upload_error_ini_size'); } elseif ($error === UPLOAD_ERR_FORM_SIZE) { return Localization::fetch('upload_error_form_size'); } elseif ($error === UPLOAD_ERR_PARTIAL) { return Localization::fetch('upload_error_err_partial'); } elseif ($error === UPLOAD_ERR_NO_FILE) { return Localization::fetch('upload_error_no_file'); } elseif ($error === UPLOAD_ERR_NO_TMP_DIR) { return Localization::fetch('upload_error_no_temp_dir'); } elseif ($error === UPLOAD_ERR_CANT_WRITE) { return Localization::fetch('upload_error_cant_write'); } elseif ($error === UPLOAD_ERR_EXTENSION) { return Localization::fetch('upload_error_extension'); } else { // we should never, ever see this return Localization::fetch('upload_error_unknown'); } } /** * Upload file(s) * * @param string $destination Where the file is going * @param string $id The field took look at in the files array * @return array */ public static function uploadBatch($destination = null, $id = null) { $destination = $destination ?: Request::get('destination'); $id = $id ?: Request::get('id'); $files = self::standardizeFileUploads($_FILES); $results = array(); // Resizing configuration if ($resize = Request::get('resize')) { $width = Request::get('width', null); $height = Request::get('height', null); $ratio = Request::get('ratio', true); $upsize = Request::get('upsize', false); $quality = Request::get('quality', '75'); } // If $files[$id][0] exists, it means there's an array of images. // If there's not, there's just one. We want to change this to an array. if ( ! isset($files[$id][0])) { $tmp = $files[$id]; unset($files[$id]); $files[$id][] = $tmp; } // Process each image foreach ($files[$id] as $file) { // Image data $path = File::upload($file, $destination); $name = basename($path); // Resize if ($resize) { $image = \Intervention\Image\Image::make(Path::assemble(BASE_PATH, $path)); $resize_folder = Path::assemble($image->dirname, 'resized'); if ( ! Folder::exists($resize_folder)) { Folder::make($resize_folder); } $resize_path = Path::assemble($resize_folder, $image->basename); $path = Path::toAsset($resize_path); $name = basename($path); $image->resize($width, $height, $ratio, $upsize)->save($resize_path, $quality); } $results[] = compact('path', 'name'); } return $results; } }
Java
package example.multiview; import io.db.Connect; import io.db.ConnectFactory; import io.db.FormatResultSet; import io.json.JSONStructureMaker; import io.parcoord.db.MakeTableModel; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Map.Entry; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.metal.MetalLookAndFeel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import model.graph.Edge; import model.graph.EdgeSetValueMaker; import model.graph.GraphFilter; import model.graph.GraphModel; import model.graph.impl.SymmetricGraphInstance; import model.matrix.DefaultMatrixTableModel; import model.matrix.MatrixTableModel; import model.shared.selection.LinkedGraphMatrixSelectionModelBridge; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.node.MissingNode; import org.codehaus.jackson.node.ObjectNode; import swingPlus.graph.GraphCellRenderer; import swingPlus.graph.JGraph; import swingPlus.graph.force.impl.BarnesHut2DForceCalculator; import swingPlus.graph.force.impl.EdgeWeightedAttractor; import swingPlus.matrix.JHeaderRenderer; import swingPlus.matrix.JMatrix; import swingPlus.parcoord.JColumnList; import swingPlus.parcoord.JColumnList2; import swingPlus.parcoord.JParCoord; import swingPlus.shared.MyFrame; import swingPlus.tablelist.ColumnSortControl; import swingPlus.tablelist.JEditableVarColTable; import ui.StackedRowTableUI; import util.Messages; import util.colour.ColorUtilities; import util.ui.NewMetalTheme; import util.ui.VerticalLabelUI; import example.graph.renderers.node.NodeDegreeGraphCellRenderer; import example.multiview.renderers.edge.EdgeCountFatEdgeRenderer; import example.multiview.renderers.matrix.JSONObjHeaderRenderer; import example.multiview.renderers.matrix.KeyedDataHeaderRenderer; import example.multiview.renderers.matrix.NumberShadeRenderer; import example.multiview.renderers.node.JSONNodeTypeGraphRenderer; import example.multiview.renderers.node.JSONTooltipGraphCellRenderer; import example.multiview.renderers.node.KeyedDataGraphCellRenderer; import example.multiview.renderers.node.TableTooltipGraphCellRenderer; import example.multiview.renderers.node.valuemakers.NodeTotalEdgeWeightValueMaker; import example.tablelist.renderers.ColourBarCellRenderer; public class NapierDBVis { static final Logger LOGGER = Logger.getLogger (NapierDBVis.class); /** * @param args */ public static void main (final String[] args) { //final MetalLookAndFeel lf = new MetalLookAndFeel(); MetalLookAndFeel.setCurrentTheme (new NewMetalTheme()); PropertyConfigurator.configure (Messages.makeProperties ("log4j")); new NapierDBVis (); } public NapierDBVis () { TableModel tableModel = null; GraphModel graph = null; TableModel listTableModel = null; MatrixTableModel matrixModel = null; Map<JsonNode, String> nodeTypeMap = null; final Properties connectionProperties = Messages.makeProperties ("dbconnect", this.getClass(), false); final Properties queryProperties = Messages.makeProperties ("queries", this.getClass(), false); final Connect connect = ConnectFactory.getConnect (connectionProperties); //ResultSet resultSet = null; Statement stmt; try { stmt = connect.getConnection().createStatement(); //final ResultSet resultSet = stmt.executeQuery ("Select * from people where peopleid>0;"); final String peopleDataQuery = queryProperties.get ("PeopleData").toString(); System.err.println (peopleDataQuery); final ResultSet peopleDataResultSet = stmt.executeQuery (peopleDataQuery); final MakeTableModel mtm2 = new MakeTableModel(); tableModel = mtm2.makeTable (peopleDataResultSet); //final ResultSet resultSet = stmt.executeQuery ("Select * from people where peopleid>0;"); final String pubJoinQuery = queryProperties.get ("PublicationJoin").toString(); System.err.println (pubJoinQuery); final ResultSet pubJoinResultSet = stmt.executeQuery (pubJoinQuery); //FormatResultSet.getInstance().printResultSet (resultSet); final MakeTableModel mtm = new MakeTableModel(); TableModel tableModel2 = mtm.makeTable (pubJoinResultSet); //final DatabaseMetaData dmd = connect.getConnection().getMetaData(); //final ResultSet resultSet2 = dmd.getProcedures (connect.getConnection().getCatalog(), null, "%"); //FormatResultSet.getInstance().printResultSet (resultSet2); final String pubsByYearQuery = queryProperties.get ("PubsByYear").toString(); System.err.println (pubsByYearQuery); final ResultSet pubsByYearResultSet = stmt.executeQuery (pubsByYearQuery); final MakeTableModel mtm3 = new MakeTableModel(); TableModel tableModel3 = mtm3.makeTable (pubsByYearResultSet); listTableModel = makePubByYearTable (tableModel3); Map<Object, KeyedData> keyDataMap = makeKeyedDataMap (tableModel, 0, 1); graph = makeGraph (keyDataMap, "peopleid", tableModel2); matrixModel = new DefaultMatrixTableModel (graph); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); connect.close(); } connect.close(); System.err.println (tableModel == null ? "no model" : "tableModel rows: "+tableModel.getRowCount()+", cols: "+tableModel.getColumnCount()); /* try { final ObjectMapper objMapper = new ObjectMapper (); final JsonNode rootNode = objMapper.readValue (new File (fileName), JsonNode.class); LOGGER.info ("rootnode: "+rootNode); final JSONStructureMaker structureMaker = new JSONStructureMaker (rootNode); graph = structureMaker.makeGraph (new String[] {"people"}, new String[] {"publications", "grants"}); //graph = structureMaker.makeGraph (new String[] {"grants"}, new String[] {"publications", "people"}); //graph = structureMaker.makeGraph (new String[] {"publications", "people", "grants"}, new String[] {"people"}); //tableModel = structureMaker.makeTable ("publications"); tableModel = structureMaker.makeTable ("people"); matrixModel = new DefaultMatrixTableModel (graph); nodeTypeMap = structureMaker.makeNodeTypeMap (new String[] {"publications", "people", "grants"}); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } */ Map<Object, Integer> keyRowMap = makeKeyRowMap (tableModel, 0); final JGraph jgraph = new JGraph (graph); final EdgeWeightedAttractor edgeWeighter = new EdgeWeightedAttractor (); jgraph.setAttractiveForceCalculator (edgeWeighter); jgraph.setShowEdges (true); final EdgeSetValueMaker weightedEdgeMaker = new NodeTotalEdgeWeightValueMaker (); //final GraphCellRenderer tableTupleRenderer = new TableTupleGraphRenderer (tableModel, keyRowMap); final GraphCellRenderer jsonGraphRenderer = new JSONNodeTypeGraphRenderer (nodeTypeMap); jgraph.setDefaultNodeRenderer (String.class, new NodeDegreeGraphCellRenderer (10.0)); jgraph.setDefaultNodeRenderer (JsonNode.class, jsonGraphRenderer); jgraph.setDefaultNodeRenderer (ObjectNode.class, jsonGraphRenderer); jgraph.setDefaultNodeRenderer (KeyedData.class, new KeyedDataGraphCellRenderer (weightedEdgeMaker)); jgraph.setDefaultEdgeRenderer (Integer.class, new EdgeCountFatEdgeRenderer ()); jgraph.setDefaultNodeToolTipRenderer (KeyedData.class, new TableTooltipGraphCellRenderer ()); final JTable pubTable = new JEditableVarColTable (listTableModel); //final JTable jtable3 = new JTable (dtm); pubTable.setSelectionMode (ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); pubTable.setRowSelectionAllowed (true); //jt2.setColumnSelectionAllowed (true); pubTable.setRowSorter (new TableRowSorter<DefaultTableModel> ((DefaultTableModel)listTableModel)); final StackedRowTableUI tlui = new StackedRowTableUI (); pubTable.setUI (tlui); tlui.setRelativeLayout (true); final Color[] columnColours = new Color [pubTable.getColumnCount() - 1]; for (int n = 0; n < columnColours.length; n++) { double perc = (double)n / columnColours.length; columnColours[n] = ColorUtilities.mixColours (Color.orange, new Color (0, 128, 255), (float)perc); } pubTable.getTableHeader().setReorderingAllowed(true); pubTable.getTableHeader().setResizingAllowed(false); System.err.println ("ptc: "+pubTable.getColumnModel().getColumnCount()); for (int col = 1; col < pubTable.getColumnCount(); col++) { System.err.println ("col: "+col+", ptyc: "+pubTable.getColumnModel().getColumn(col)); pubTable.getColumnModel().getColumn(col).setCellRenderer (new ColourBarCellRenderer (columnColours [(col - 1) % columnColours.length])); } final JColumnList jcl = new JColumnList (pubTable) { @Override public boolean isCellEditable (final int row, final int column) { return super.isCellEditable (row, column) && row > 0; } }; //jcl.addTable (pubTable); final JMatrix jmatrix = new JMatrix ((TableModel) matrixModel); //final JHeaderRenderer stringHeader = new JSONObjHeaderRenderer (); //final JHeaderRenderer stringHeader2 = new JSONObjHeaderRenderer (); final JHeaderRenderer stringHeader = new KeyedDataHeaderRenderer (); final JHeaderRenderer stringHeader2 = new KeyedDataHeaderRenderer (); jmatrix.getRowHeader().setDefaultRenderer (Object.class, stringHeader); jmatrix.getRowHeader().setDefaultRenderer (String.class, stringHeader); jmatrix.getColumnHeader().setDefaultRenderer (Object.class, stringHeader2); jmatrix.getColumnHeader().setDefaultRenderer (String.class, stringHeader2); ((JLabel)stringHeader2).setUI (new VerticalLabelUI (false)); stringHeader.setSelectionBackground (jmatrix.getRowHeader()); stringHeader2.setSelectionBackground (jmatrix.getColumnHeader()); //jmatrix.setDefaultRenderer (HashSet.class, stringHeader); jmatrix.setDefaultRenderer (String.class, stringHeader); jmatrix.setDefaultRenderer (Integer.class, new NumberShadeRenderer ()); final JTable table = new JParCoord (tableModel); table.setSelectionMode (ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); table.setRowSelectionAllowed (true); table.setAutoCreateRowSorter (true); table.setColumnSelectionAllowed (true); table.setForeground (Color.lightGray); table.setSelectionForeground (Color.orange); if (table instanceof JParCoord) { ((JParCoord)table).setBrushForegroundColour (Color.gray); ((JParCoord)table).setBrushSelectionColour (Color.red); ((JParCoord)table).setSelectedStroke (new BasicStroke (2.0f)); //((JParCoord)table).setBrushing (true); } table.setGridColor (Color.gray); table.setShowVerticalLines (false); table.setBorder (BorderFactory.createEmptyBorder (24, 2, 24, 2)); if (table.getRowSorter() instanceof TableRowSorter) { final TableRowSorter<? extends TableModel> trs = (TableRowSorter<? extends TableModel>)table.getRowSorter(); } table.setAutoResizeMode (JTable.AUTO_RESIZE_OFF); /* jgraph.setPreferredSize (new Dimension (768, 640)); table.setPreferredSize (new Dimension (768, 384)); table.setMinimumSize (new Dimension (256, 128)); final LinkedGraphMatrixSelectionModelBridge selectionBridge = new LinkedGraphMatrixSelectionModelBridge (); selectionBridge.addJGraph (jgraph); selectionBridge.addJTable (table); selectionBridge.addJTable (jmatrix); */ SwingUtilities.invokeLater ( new Runnable () { @Override public void run() { final JFrame jf2 = new MyFrame ("JGraph Demo"); jf2.setSize (1024, 768); final JPanel optionPanel = new JPanel (); optionPanel.setLayout (new BoxLayout (optionPanel, BoxLayout.Y_AXIS)); final JSlider llengthSlider = new JSlider (20, 1000, (int)edgeWeighter.getLinkLength()); llengthSlider.addChangeListener( new ChangeListener () { @Override public void stateChanged (final ChangeEvent cEvent) { edgeWeighter.setLinkLength (llengthSlider.getValue()); } } ); final JSlider lstiffSlider = new JSlider (20, 1000, edgeWeighter.getStiffness()); lstiffSlider.addChangeListener( new ChangeListener () { @Override public void stateChanged (final ChangeEvent cEvent) { edgeWeighter.setStiffness (lstiffSlider.getValue()); } } ); final JSlider repulseSlider = new JSlider (1, 50, 10); repulseSlider.addChangeListener( new ChangeListener () { @Override public void stateChanged (final ChangeEvent cEvent) { ((BarnesHut2DForceCalculator)jgraph.getRepulsiveForceCalculator()).setAttenuator (3.0 / repulseSlider.getValue()); } } ); final JCheckBox showSingletons = new JCheckBox ("Show singletons", true); showSingletons.addActionListener ( new ActionListener () { @Override public void actionPerformed (final ActionEvent e) { final Object source = e.getSource(); if (source instanceof JCheckBox) { final boolean selected = ((JCheckBox)source).isSelected(); final GraphFilter singletonFilter = new GraphFilter () { @Override public boolean includeNode (final Object obj) { return jgraph.getModel().getEdges(obj).size() > 0 || selected; } @Override public boolean includeEdge (final Edge edge) { return true; } }; jgraph.setGraphFilter (singletonFilter); } } } ); final JButton clearSelections = new JButton ("Clear Selections"); clearSelections.addActionListener ( new ActionListener () { @Override public void actionPerformed (ActionEvent e) { jgraph.getSelectionModel().clearSelection (); } } ); final JButton graphFreezer = new JButton ("Freeze Graph"); graphFreezer.addActionListener ( new ActionListener () { @Override public void actionPerformed (ActionEvent e) { jgraph.pauseWorker(); } } ); optionPanel.add (new JLabel ("Link Length:")); optionPanel.add (llengthSlider); optionPanel.add (new JLabel ("Link Stiffness:")); optionPanel.add (lstiffSlider); optionPanel.add (new JLabel ("Repulse Strength:")); optionPanel.add (repulseSlider); optionPanel.add (showSingletons); optionPanel.add (clearSelections); optionPanel.add (graphFreezer); JPanel listTablePanel = new JPanel (new BorderLayout ()); listTablePanel.add (new JScrollPane (pubTable), BorderLayout.CENTER); final Box pubControlPanel = Box.createVerticalBox(); final JScrollPane pubTableScrollPane = new JScrollPane (pubControlPanel); pubTableScrollPane.setPreferredSize (new Dimension (168, 400)); jcl.getColumnModel().getColumn(1).setWidth (30); listTablePanel.add (pubTableScrollPane, BorderLayout.WEST); JTable columnSorter = new ColumnSortControl (pubTable); pubControlPanel.add (jcl.getTableHeader()); pubControlPanel.add (jcl); pubControlPanel.add (columnSorter.getTableHeader()); pubControlPanel.add (columnSorter); JScrollPane parCoordsScrollPane = new JScrollPane (table); JScrollPane matrixScrollPane = new JScrollPane (jmatrix); JTabbedPane jtp = new JTabbedPane (); JPanel graphPanel = new JPanel (new BorderLayout ()); graphPanel.add (jgraph, BorderLayout.CENTER); graphPanel.add (optionPanel, BorderLayout.WEST); jtp.addTab ("Node-Link", graphPanel); jtp.addTab ("Matrix", matrixScrollPane); jtp.addTab ("Pubs", listTablePanel); jtp.addTab ("||-Coords", parCoordsScrollPane); jtp.setPreferredSize(new Dimension (800, 480)); //jf2.getContentPane().add (optionPanel, BorderLayout.EAST); jf2.getContentPane().add (jtp, BorderLayout.CENTER); //jf2.getContentPane().add (tableScrollPane, BorderLayout.SOUTH); jf2.setVisible (true); } } ); } public GraphModel makeGraph (final ResultSet nodeSet, final ResultSet edgeSet) throws SQLException { edgeSet.beforeFirst(); final GraphModel graph = new SymmetricGraphInstance (); // Look through the rootnode for fields named 'nodeType' // Add that nodeTypes' subfields as nodes to a graph while (edgeSet.next()) { Object author1 = edgeSet.getObject(1); Object author2 = edgeSet.getObject(2); graph.addNode (author1); graph.addNode (author2); final Set<Edge> edges = graph.getEdges (author1, author2); if (edges.isEmpty()) { graph.addEdge (author1, author2, Integer.valueOf (1)); } else { final Iterator<Edge> edgeIter = edges.iterator(); final Edge firstEdge = edgeIter.next(); final Integer val = (Integer)firstEdge.getEdgeObject(); firstEdge.setEdgeObject (Integer.valueOf (val.intValue() + 1)); //graph.removeEdge (firstEdge); //graph.addEdge (node1, node2, Integer.valueOf (val.intValue() + 1)); } } return graph; } public GraphModel makeGraph (final TableModel nodes, final String primaryKeyColumn, final TableModel edges) throws SQLException { final GraphModel graph = new SymmetricGraphInstance (); final Map<Object, Integer> primaryKeyRowMap = new HashMap<Object, Integer> (); for (int row = 0; row < nodes.getRowCount(); row++) { primaryKeyRowMap.put (nodes.getValueAt (row, 0), Integer.valueOf (row)); } // Look through the rootnode for fields named 'nodeType' // Add that nodeTypes' subfields as nodes to a graph for (int row = 0; row < edges.getRowCount(); row++) { Object authorKey1 = edges.getValueAt (row, 0); Object authorKey2 = edges.getValueAt (row, 1); int authorIndex1 = (primaryKeyRowMap.get(authorKey1) == null ? -1 : primaryKeyRowMap.get(authorKey1).intValue()); int authorIndex2 = (primaryKeyRowMap.get(authorKey2) == null ? -1 : primaryKeyRowMap.get(authorKey2).intValue()); if (authorIndex1 >= 0 && authorIndex2 >= 0) { Object graphNode1 = nodes.getValueAt (authorIndex1, 1); Object graphNode2 = nodes.getValueAt (authorIndex2, 1); graph.addNode (graphNode1); graph.addNode (graphNode2); final Set<Edge> gedges = graph.getEdges (graphNode1, graphNode2); if (gedges.isEmpty()) { graph.addEdge (graphNode1, graphNode2, Integer.valueOf (1)); } else { final Iterator<Edge> edgeIter = gedges.iterator(); final Edge firstEdge = edgeIter.next(); final Integer val = (Integer)firstEdge.getEdgeObject(); firstEdge.setEdgeObject (Integer.valueOf (val.intValue() + 1)); } } } return graph; } public GraphModel makeGraph (final Map<Object, KeyedData> keyDataMap, final String primaryKeyColumn, final TableModel edges) throws SQLException { final GraphModel graph = new SymmetricGraphInstance (); // Look through the rootnode for fields named 'nodeType' // Add that nodeTypes' subfields as nodes to a graph for (int row = 0; row < edges.getRowCount(); row++) { Object authorKey1 = edges.getValueAt (row, 0); Object authorKey2 = edges.getValueAt (row, 1); if (authorKey1 != null && authorKey2 != null) { Object graphNode1 = keyDataMap.get (authorKey1); Object graphNode2 = keyDataMap.get (authorKey2); if (graphNode1 != null && graphNode2 != null) { graph.addNode (graphNode1); graph.addNode (graphNode2); final Set<Edge> gedges = graph.getEdges (graphNode1, graphNode2); if (gedges.isEmpty()) { graph.addEdge (graphNode1, graphNode2, Integer.valueOf (1)); } else { final Iterator<Edge> edgeIter = gedges.iterator(); final Edge firstEdge = edgeIter.next(); final Integer val = (Integer)firstEdge.getEdgeObject(); firstEdge.setEdgeObject (Integer.valueOf (val.intValue() + 1)); } } } } return graph; } public Map<Object, Integer> makeKeyRowMap (final TableModel tableModel, final int columnPKIndex) { final Map<Object, Integer> primaryKeyRowMap = new HashMap<Object, Integer> (); for (int row = 0; row < tableModel.getRowCount(); row++) { primaryKeyRowMap.put (tableModel.getValueAt (row, 0), Integer.valueOf (row)); } return primaryKeyRowMap; } public Map<Object, KeyedData> makeKeyedDataMap (final TableModel tableModel, final int columnPKIndex, final int columnLabelIndex) { final Map<Object, KeyedData> primaryKeyDataMap = new HashMap<Object, KeyedData> (); for (int row = 0; row < tableModel.getRowCount(); row++) { primaryKeyDataMap.put (tableModel.getValueAt (row, columnPKIndex), makeKeyedData (tableModel, columnPKIndex, columnLabelIndex, row)); } return primaryKeyDataMap; } public KeyedData makeKeyedData (final TableModel tableModel, final int columnPKIndex, final int columnLabelIndex, final int rowIndex) { List<Object> data = new ArrayList<Object> (); for (int n = 0; n < tableModel.getColumnCount(); n++) { data.add (tableModel.getValueAt (rowIndex, n)); } KeyedData kd = new KeyedData (tableModel.getValueAt (rowIndex, columnPKIndex), data, columnLabelIndex); return kd; } /** * can't do pivot queries in ANSI SQL * @param sqlresult * @return */ public TableModel makePubByYearTable (final TableModel sqlresult) { DefaultTableModel tm = new DefaultTableModel () { public Class<?> getColumnClass(int columnIndex) { if (columnIndex > 0) { return Long.class; } return Integer.class; } public boolean isCellEditable (final int row, final int column) { return false; } }; Map<Object, List<Long>> yearsToTypes = new HashMap<Object, List<Long>> (); Map<Object, Integer> columnTypes = new HashMap<Object, Integer> (); tm.addColumn ("Year"); int col = 1; for (int sqlrow = 0; sqlrow < sqlresult.getRowCount(); sqlrow++) { Object type = sqlresult.getValueAt (sqlrow, 1); if (columnTypes.get(type) == null) { columnTypes.put(type, Integer.valueOf(col)); tm.addColumn (type); col++; } } System.err.println ("cols: "+columnTypes+", "+columnTypes.size()); for (int sqlrow = 0; sqlrow < sqlresult.getRowCount(); sqlrow++) { Object year = sqlresult.getValueAt (sqlrow, 0); if (year != null) { Object type = sqlresult.getValueAt (sqlrow, 1); Object val = sqlresult.getValueAt (sqlrow, 2); int colIndex = columnTypes.get(type).intValue(); List<Long> store = yearsToTypes.get (year); if (store == null) { Long[] storep = new Long [col - 1]; Arrays.fill (storep, Long.valueOf(0)); List<Long> longs = Arrays.asList (storep); store = new ArrayList (longs); //Collections.fill (store, Long.valueOf (0)); yearsToTypes.put (year, store); } store.set (colIndex - 1, (Long)val); } } for (Entry<Object, List<Long>> yearEntry : yearsToTypes.entrySet()) { Object[] rowData = new Object [col]; rowData[0] = yearEntry.getKey(); for (int n = 1; n < col; n++) { rowData[n] = yearEntry.getValue().get(n-1); } tm.addRow(rowData); } return tm; } }
Java
# Minio B2 Gateway [![Slack](https://slack.minio.io/slack?type=svg)](https://slack.minio.io) Minio Gateway adds Amazon S3 compatibility to Backblaze B2 Cloud Storage. ## Run Minio Gateway for Backblaze B2 Cloud Storage Please follow this [guide](https://www.backblaze.com/b2/docs/quick_account.html) to create an account on backblaze.com to obtain your access credentisals for B2 Cloud storage. ### Using Docker ``` docker run -p 9000:9000 --name b2-s3 \ -e "MINIO_ACCESS_KEY=b2_accound_id" \ -e "MINIO_SECRET_KEY=b2_application_key" \ minio/minio:edge gateway b2 ``` ## Test using Minio Browser Minio Gateway comes with an embedded web based object browser. Point your web browser to http://127.0.0.1:9000 to ensure that your server has started successfully. ![Screenshot](https://raw.githubusercontent.com/minio/minio/master/docs/screenshots/minio-browser-gateway.png) ## Test using Minio Client `mc` `mc` provides a modern alternative to UNIX commands such as ls, cat, cp, mirror, diff etc. It supports filesystems and Amazon S3 compatible cloud storage services. ### Configure `mc` ``` mc config host add myb2 http://gateway-ip:9000 b2_account_id b2_application_key ``` ### List buckets on Backblaze B2 ``` mc ls myb2 [2017-02-22 01:50:43 PST] 0B ferenginar/ [2017-02-26 21:43:51 PST] 0B my-bucket/ [2017-02-26 22:10:11 PST] 0B test-bucket1/ ``` ### Known limitations Gateway inherits the following B2 limitations: - No support for CopyObject S3 API (There are no equivalent APIs available on Backblaze B2). - No support for CopyObjectPart S3 API (There are no equivalent APIs available on Backblaze B2). - Only read-only bucket policy supported at bucket level, all other variations will return API Notimplemented error. - DeleteObject() might not delete the object right away on Backblaze B2, so you might see the object immediately after a Delete request. Other limitations: - Bucket notification APIs are not supported. ## Explore Further - [`mc` command-line interface](https://docs.minio.io/docs/minio-client-quickstart-guide) - [`aws` command-line interface](https://docs.minio.io/docs/aws-cli-with-minio) - [`minio-go` Go SDK](https://docs.minio.io/docs/golang-client-quickstart-guide)
Java
import props from './props'; import './view.html'; class NoteClab { beforeRegister() { this.is = 'note-clab'; this.properties = props; } computeClasses(type) { var arr = ['input-note']; if (type != undefined) arr.push(type); return arr.join(' '); } } Polymer(NoteClab);
Java
package com.umeng.soexample.run.step; /** * 步数更新回调 * Created by dylan on 16/9/27. */ public interface UpdateUiCallBack { /** * 更新UI步数 * * @param stepCount 步数 */ void updateUi(int stepCount); }
Java
package org.template.similarproduct import io.prediction.controller.LServing import breeze.stats.mean import breeze.stats.meanAndVariance import breeze.stats.MeanAndVariance class Serving extends LServing[Query, PredictedResult] { override def serve(query: Query, predictedResults: Seq[PredictedResult]): PredictedResult = { // MODFIED val standard: Seq[Array[ItemScore]] = if (query.num == 1) { // if query 1 item, don't standardize predictedResults.map(_.itemScores) } else { // Standardize the score before combine val mvList: Seq[MeanAndVariance] = predictedResults.map { pr => meanAndVariance(pr.itemScores.map(_.score)) } predictedResults.zipWithIndex .map { case (pr, i) => pr.itemScores.map { is => // standardize score (z-score) // if standard deviation is 0 (when all items have the same score, // meaning all items are ranked equally), return 0. val score = if (mvList(i).stdDev == 0) { 0 } else { (is.score - mvList(i).mean) / mvList(i).stdDev } ItemScore(is.item, score) } } } // sum the standardized score if same item val combined = standard.flatten // Array of ItemScore .groupBy(_.item) // groupBy item id .mapValues(itemScores => itemScores.map(_.score).reduce(_ + _)) .toArray // array of (item id, score) .sortBy(_._2)(Ordering.Double.reverse) .take(query.num) .map { case (k,v) => ItemScore(k, v) } new PredictedResult(combined) } }
Java
<layout name="layout" /> <div class="row"> <div class="panel panel-info"> <div class="panel-heading"> <h3 class="panel-title"> <{$arr.cate|getCatname=###}>-<b><{$arr.name}></b> <a href="__APP__/<{$JC}>/Servicelist/index/cate/<{$arr.cate}>" class="pull-right">返回分类</a> </h3> </div> <div class="panel-body"> <div class="col-md-3 "> <img src="__UPLOAD__<{$arr.path}><{$arr.img}>" alt="<{$arr.img}>" height="180px"> </div> <div class="col-md-7 "> <h5>编号:<{$arr.mark}></h5> <h4>名称:<{$arr.name}></h4> <h4>价格:<b>¥<{$arr.money}></b>(市场价:<s><em>¥<{$arr.smoney}></em></s>)</h4> <!--<h4>运费:¥<{$arr.wlmoney}></h4>--> <h5>规格:<{$arr.weight}></h5> <a href="#" class="btn btn-info btn-xs">咨询预约</a> <a href="http://wpa.qq.com/msgrd?v=3&amp;uin=<{$_SESSION[$JC]['qq']}>&amp;site=qq&amp;menu=yes" class="btn-xs" target="_blank"> <img border="0" title="在线客服" alt="在线客服" style="margin-top:0px;" src="http://wpa.qq.com/pa?p=2:<{$_SESSION[$JC]['qq']}>:41"> </a> </div> </div> </div> <div class="panel panel-info"> <div class="panel-heading"><h3 class="panel-title">详情介绍:</h3></div> <div class="panel-body"><p><{$arr.content}></p></div> </div> </div>
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_91) on Mon Jun 06 14:51:11 EDT 2016 --> <title>Lists.Value (apache-cassandra API)</title> <meta name="date" content="2016-06-06"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Lists.Value (apache-cassandra API)"; } } catch(err) { } //--> var methods = {"i0":10,"i1":9,"i2":10,"i3":10}; var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Lists.Value.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/apache/cassandra/cql3/Lists.SetterByIndex.html" title="class in org.apache.cassandra.cql3"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../org/apache/cassandra/cql3/Maps.html" title="class in org.apache.cassandra.cql3"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/cassandra/cql3/Lists.Value.html" target="_top">Frames</a></li> <li><a href="Lists.Value.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.apache.cassandra.cql3</div> <h2 title="Class Lists.Value" class="title">Class Lists.Value</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../../../org/apache/cassandra/cql3/Term.Terminal.html" title="class in org.apache.cassandra.cql3">org.apache.cassandra.cql3.Term.Terminal</a></li> <li> <ul class="inheritance"> <li><a href="../../../../org/apache/cassandra/cql3/Term.MultiItemTerminal.html" title="class in org.apache.cassandra.cql3">org.apache.cassandra.cql3.Term.MultiItemTerminal</a></li> <li> <ul class="inheritance"> <li>org.apache.cassandra.cql3.Lists.Value</li> </ul> </li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd><a href="../../../../org/apache/cassandra/cql3/Term.html" title="interface in org.apache.cassandra.cql3">Term</a></dd> </dl> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../org/apache/cassandra/cql3/Lists.html" title="class in org.apache.cassandra.cql3">Lists</a></dd> </dl> <hr> <br> <pre>public static class <span class="typeNameLabel">Lists.Value</span> extends <a href="../../../../org/apache/cassandra/cql3/Term.MultiItemTerminal.html" title="class in org.apache.cassandra.cql3">Term.MultiItemTerminal</a></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested.class.summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <ul class="blockList"> <li class="blockList"><a name="nested.classes.inherited.from.class.org.apache.cassandra.cql3.Term"> <!-- --> </a> <h3>Nested classes/interfaces inherited from interface&nbsp;org.apache.cassandra.cql3.<a href="../../../../org/apache/cassandra/cql3/Term.html" title="interface in org.apache.cassandra.cql3">Term</a></h3> <code><a href="../../../../org/apache/cassandra/cql3/Term.MultiColumnRaw.html" title="class in org.apache.cassandra.cql3">Term.MultiColumnRaw</a>, <a href="../../../../org/apache/cassandra/cql3/Term.MultiItemTerminal.html" title="class in org.apache.cassandra.cql3">Term.MultiItemTerminal</a>, <a href="../../../../org/apache/cassandra/cql3/Term.NonTerminal.html" title="class in org.apache.cassandra.cql3">Term.NonTerminal</a>, <a href="../../../../org/apache/cassandra/cql3/Term.Raw.html" title="class in org.apache.cassandra.cql3">Term.Raw</a>, <a href="../../../../org/apache/cassandra/cql3/Term.Terminal.html" title="class in org.apache.cassandra.cql3">Term.Terminal</a></code></li> </ul> </li> </ul> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>java.util.List&lt;java.nio.ByteBuffer&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/cql3/Lists.Value.html#elements">elements</a></span></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/cql3/Lists.Value.html#Value-java.util.List-">Value</a></span>(java.util.List&lt;java.nio.ByteBuffer&gt;&nbsp;elements)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/cql3/Lists.Value.html#equals-org.apache.cassandra.db.marshal.ListType-org.apache.cassandra.cql3.Lists.Value-">equals</a></span>(<a href="../../../../org/apache/cassandra/db/marshal/ListType.html" title="class in org.apache.cassandra.db.marshal">ListType</a>&nbsp;lt, <a href="../../../../org/apache/cassandra/cql3/Lists.Value.html" title="class in org.apache.cassandra.cql3">Lists.Value</a>&nbsp;v)</code>&nbsp;</td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/cql3/Lists.Value.html" title="class in org.apache.cassandra.cql3">Lists.Value</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/cql3/Lists.Value.html#fromSerialized-java.nio.ByteBuffer-org.apache.cassandra.db.marshal.ListType-int-">fromSerialized</a></span>(java.nio.ByteBuffer&nbsp;value, <a href="../../../../org/apache/cassandra/db/marshal/ListType.html" title="class in org.apache.cassandra.db.marshal">ListType</a>&nbsp;type, int&nbsp;version)</code>&nbsp;</td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>java.nio.ByteBuffer</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/cql3/Lists.Value.html#get-int-">get</a></span>(int&nbsp;protocolVersion)</code>&nbsp;</td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>java.util.List&lt;java.nio.ByteBuffer&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/cql3/Lists.Value.html#getElements--">getElements</a></span>()</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.org.apache.cassandra.cql3.Term.Terminal"> <!-- --> </a> <h3>Methods inherited from class&nbsp;org.apache.cassandra.cql3.<a href="../../../../org/apache/cassandra/cql3/Term.Terminal.html" title="class in org.apache.cassandra.cql3">Term.Terminal</a></h3> <code><a href="../../../../org/apache/cassandra/cql3/Term.Terminal.html#addFunctionsTo-java.util.List-">addFunctionsTo</a>, <a href="../../../../org/apache/cassandra/cql3/Term.Terminal.html#bind-org.apache.cassandra.cql3.QueryOptions-">bind</a>, <a href="../../../../org/apache/cassandra/cql3/Term.Terminal.html#bindAndGet-org.apache.cassandra.cql3.QueryOptions-">bindAndGet</a>, <a href="../../../../org/apache/cassandra/cql3/Term.Terminal.html#collectMarkerSpecification-org.apache.cassandra.cql3.VariableSpecifications-">collectMarkerSpecification</a>, <a href="../../../../org/apache/cassandra/cql3/Term.Terminal.html#containsBindMarker--">containsBindMarker</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="elements"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>elements</h4> <pre>public final&nbsp;java.util.List&lt;java.nio.ByteBuffer&gt; elements</pre> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="Value-java.util.List-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>Value</h4> <pre>public&nbsp;Value(java.util.List&lt;java.nio.ByteBuffer&gt;&nbsp;elements)</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="fromSerialized-java.nio.ByteBuffer-org.apache.cassandra.db.marshal.ListType-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>fromSerialized</h4> <pre>public static&nbsp;<a href="../../../../org/apache/cassandra/cql3/Lists.Value.html" title="class in org.apache.cassandra.cql3">Lists.Value</a>&nbsp;fromSerialized(java.nio.ByteBuffer&nbsp;value, <a href="../../../../org/apache/cassandra/db/marshal/ListType.html" title="class in org.apache.cassandra.db.marshal">ListType</a>&nbsp;type, int&nbsp;version) throws <a href="../../../../org/apache/cassandra/exceptions/InvalidRequestException.html" title="class in org.apache.cassandra.exceptions">InvalidRequestException</a></pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../../../../org/apache/cassandra/exceptions/InvalidRequestException.html" title="class in org.apache.cassandra.exceptions">InvalidRequestException</a></code></dd> </dl> </li> </ul> <a name="get-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>get</h4> <pre>public&nbsp;java.nio.ByteBuffer&nbsp;get(int&nbsp;protocolVersion)</pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../../../org/apache/cassandra/cql3/Term.Terminal.html#get-int-">get</a></code>&nbsp;in class&nbsp;<code><a href="../../../../org/apache/cassandra/cql3/Term.Terminal.html" title="class in org.apache.cassandra.cql3">Term.Terminal</a></code></dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the serialized value of this terminal.</dd> </dl> </li> </ul> <a name="equals-org.apache.cassandra.db.marshal.ListType-org.apache.cassandra.cql3.Lists.Value-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>equals</h4> <pre>public&nbsp;boolean&nbsp;equals(<a href="../../../../org/apache/cassandra/db/marshal/ListType.html" title="class in org.apache.cassandra.db.marshal">ListType</a>&nbsp;lt, <a href="../../../../org/apache/cassandra/cql3/Lists.Value.html" title="class in org.apache.cassandra.cql3">Lists.Value</a>&nbsp;v)</pre> </li> </ul> <a name="getElements--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getElements</h4> <pre>public&nbsp;java.util.List&lt;java.nio.ByteBuffer&gt;&nbsp;getElements()</pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../../../org/apache/cassandra/cql3/Term.MultiItemTerminal.html#getElements--">getElements</a></code>&nbsp;in class&nbsp;<code><a href="../../../../org/apache/cassandra/cql3/Term.MultiItemTerminal.html" title="class in org.apache.cassandra.cql3">Term.MultiItemTerminal</a></code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Lists.Value.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/apache/cassandra/cql3/Lists.SetterByIndex.html" title="class in org.apache.cassandra.cql3"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../org/apache/cassandra/cql3/Maps.html" title="class in org.apache.cassandra.cql3"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/cassandra/cql3/Lists.Value.html" target="_top">Frames</a></li> <li><a href="Lists.Value.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &copy; 2016 The Apache Software Foundation</small></p> </body> </html>
Java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/unittest_preserve_unknown_enum2.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include <google/protobuf/unittest_preserve_unknown_enum2.pb.h> #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace proto2_preserve_unknown_enum_unittest { class MyMessageDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<MyMessage> { public: int oneof_e_1_; int oneof_e_2_; } _MyMessage_default_instance_; namespace protobuf_google_2fprotobuf_2funittest_5fpreserve_5funknown_5fenum2_2eproto { namespace { ::google::protobuf::Metadata file_level_metadata[1]; const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[1]; } // namespace PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField const TableStruct::entries[] = { {0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0}, }; PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField const TableStruct::aux[] = { ::google::protobuf::internal::AuxillaryParseTableField(), }; PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const TableStruct::schema[] = { { NULL, NULL, 0, -1, -1, false }, }; const ::google::protobuf::uint32 TableStruct::offsets[] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MyMessage, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MyMessage, _internal_metadata_), ~0u, // no _extensions_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MyMessage, _oneof_case_[0]), ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MyMessage, e_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MyMessage, repeated_e_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MyMessage, repeated_packed_e_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MyMessage, repeated_packed_unexpected_e_), GOOGLE_PROTOBUF_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET((&_MyMessage_default_instance_), oneof_e_1_), GOOGLE_PROTOBUF_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET((&_MyMessage_default_instance_), oneof_e_2_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MyMessage, o_), 0, ~0u, ~0u, ~0u, ~0u, ~0u, }; static const ::google::protobuf::internal::MigrationSchema schemas[] = { { 0, 12, sizeof(MyMessage)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&_MyMessage_default_instance_), }; namespace { void protobuf_AssignDescriptors() { AddDescriptors(); ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( "google/protobuf/unittest_preserve_unknown_enum2.proto", schemas, file_default_instances, TableStruct::offsets, factory, file_level_metadata, file_level_enum_descriptors, NULL); } void protobuf_AssignDescriptorsOnce() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); } } // namespace void TableStruct::Shutdown() { _MyMessage_default_instance_.Shutdown(); delete file_level_metadata[0].reflection; } void TableStruct::InitDefaultsImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; ::google::protobuf::internal::InitProtobufDefaults(); _MyMessage_default_instance_.DefaultConstruct(); _MyMessage_default_instance_.oneof_e_1_ = 0; _MyMessage_default_instance_.oneof_e_2_ = 0; } void InitDefaults() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] = { "\n5google/protobuf/unittest_preserve_unkn" "own_enum2.proto\022%proto2_preserve_unknown" "_enum_unittest\"\270\003\n\tMyMessage\0228\n\001e\030\001 \001(\0162" "-.proto2_preserve_unknown_enum_unittest." "MyEnum\022A\n\nrepeated_e\030\002 \003(\0162-.proto2_pres" "erve_unknown_enum_unittest.MyEnum\022L\n\021rep" "eated_packed_e\030\003 \003(\0162-.proto2_preserve_u" "nknown_enum_unittest.MyEnumB\002\020\001\022S\n\034repea" "ted_packed_unexpected_e\030\004 \003(\0162-.proto2_p" "reserve_unknown_enum_unittest.MyEnum\022B\n\t" "oneof_e_1\030\005 \001(\0162-.proto2_preserve_unknow" "n_enum_unittest.MyEnumH\000\022B\n\toneof_e_2\030\006 " "\001(\0162-.proto2_preserve_unknown_enum_unitt" "est.MyEnumH\000B\003\n\001o*#\n\006MyEnum\022\007\n\003FOO\020\000\022\007\n\003" "BAR\020\001\022\007\n\003BAZ\020\002" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 574); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "google/protobuf/unittest_preserve_unknown_enum2.proto", &protobuf_RegisterTypes); ::google::protobuf::internal::OnShutdown(&TableStruct::Shutdown); } void AddDescriptors() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_google_2fprotobuf_2funittest_5fpreserve_5funknown_5fenum2_2eproto const ::google::protobuf::EnumDescriptor* MyEnum_descriptor() { protobuf_google_2fprotobuf_2funittest_5fpreserve_5funknown_5fenum2_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_google_2fprotobuf_2funittest_5fpreserve_5funknown_5fenum2_2eproto::file_level_enum_descriptors[0]; } bool MyEnum_IsValid(int value) { switch (value) { case 0: case 1: case 2: return true; default: return false; } } // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int MyMessage::kEFieldNumber; const int MyMessage::kRepeatedEFieldNumber; const int MyMessage::kRepeatedPackedEFieldNumber; const int MyMessage::kRepeatedPackedUnexpectedEFieldNumber; const int MyMessage::kOneofE1FieldNumber; const int MyMessage::kOneofE2FieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 MyMessage::MyMessage() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_google_2fprotobuf_2funittest_5fpreserve_5funknown_5fenum2_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:proto2_preserve_unknown_enum_unittest.MyMessage) } MyMessage::MyMessage(const MyMessage& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0), repeated_e_(from.repeated_e_), repeated_packed_e_(from.repeated_packed_e_), repeated_packed_unexpected_e_(from.repeated_packed_unexpected_e_) { _internal_metadata_.MergeFrom(from._internal_metadata_); e_ = from.e_; clear_has_o(); switch (from.o_case()) { case kOneofE1: { set_oneof_e_1(from.oneof_e_1()); break; } case kOneofE2: { set_oneof_e_2(from.oneof_e_2()); break; } case O_NOT_SET: { break; } } // @@protoc_insertion_point(copy_constructor:proto2_preserve_unknown_enum_unittest.MyMessage) } void MyMessage::SharedCtor() { _cached_size_ = 0; e_ = 0; clear_has_o(); } MyMessage::~MyMessage() { // @@protoc_insertion_point(destructor:proto2_preserve_unknown_enum_unittest.MyMessage) SharedDtor(); } void MyMessage::SharedDtor() { if (has_o()) { clear_o(); } } void MyMessage::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* MyMessage::descriptor() { protobuf_google_2fprotobuf_2funittest_5fpreserve_5funknown_5fenum2_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_google_2fprotobuf_2funittest_5fpreserve_5funknown_5fenum2_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const MyMessage& MyMessage::default_instance() { protobuf_google_2fprotobuf_2funittest_5fpreserve_5funknown_5fenum2_2eproto::InitDefaults(); return *internal_default_instance(); } MyMessage* MyMessage::New(::google::protobuf::Arena* arena) const { MyMessage* n = new MyMessage; if (arena != NULL) { arena->Own(n); } return n; } void MyMessage::clear_o() { // @@protoc_insertion_point(one_of_clear_start:proto2_preserve_unknown_enum_unittest.MyMessage) switch (o_case()) { case kOneofE1: { // No need to clear break; } case kOneofE2: { // No need to clear break; } case O_NOT_SET: { break; } } _oneof_case_[0] = O_NOT_SET; } void MyMessage::Clear() { // @@protoc_insertion_point(message_clear_start:proto2_preserve_unknown_enum_unittest.MyMessage) repeated_e_.Clear(); repeated_packed_e_.Clear(); repeated_packed_unexpected_e_.Clear(); e_ = 0; clear_o(); _has_bits_.Clear(); _internal_metadata_.Clear(); } bool MyMessage::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:proto2_preserve_unknown_enum_unittest.MyMessage) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .proto2_preserve_unknown_enum_unittest.MyEnum e = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid(value)) { set_e(static_cast< ::proto2_preserve_unknown_enum_unittest::MyEnum >(value)); } else { mutable_unknown_fields()->AddVarint(1, value); } } else { goto handle_unusual; } break; } // repeated .proto2_preserve_unknown_enum_unittest.MyEnum repeated_e = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid(value)) { add_repeated_e(static_cast< ::proto2_preserve_unknown_enum_unittest::MyEnum >(value)); } else { mutable_unknown_fields()->AddVarint(2, value); } } else if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u)) { DO_((::google::protobuf::internal::WireFormat::ReadPackedEnumPreserveUnknowns( input, 2, ::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid, mutable_unknown_fields(), this->mutable_repeated_e()))); } else { goto handle_unusual; } break; } // repeated .proto2_preserve_unknown_enum_unittest.MyEnum repeated_packed_e = 3 [packed = true]; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u)) { ::google::protobuf::uint32 length; DO_(input->ReadVarint32(&length)); ::google::protobuf::io::CodedInputStream::Limit limit = input->PushLimit(length); while (input->BytesUntilLimit() > 0) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid(value)) { add_repeated_packed_e(static_cast< ::proto2_preserve_unknown_enum_unittest::MyEnum >(value)); } else { mutable_unknown_fields()->AddVarint(3, value); } } input->PopLimit(limit); } else if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid(value)) { add_repeated_packed_e(static_cast< ::proto2_preserve_unknown_enum_unittest::MyEnum >(value)); } else { mutable_unknown_fields()->AddVarint(3, value); } } else { goto handle_unusual; } break; } // repeated .proto2_preserve_unknown_enum_unittest.MyEnum repeated_packed_unexpected_e = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(32u)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid(value)) { add_repeated_packed_unexpected_e(static_cast< ::proto2_preserve_unknown_enum_unittest::MyEnum >(value)); } else { mutable_unknown_fields()->AddVarint(4, value); } } else if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u)) { DO_((::google::protobuf::internal::WireFormat::ReadPackedEnumPreserveUnknowns( input, 4, ::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid, mutable_unknown_fields(), this->mutable_repeated_packed_unexpected_e()))); } else { goto handle_unusual; } break; } // optional .proto2_preserve_unknown_enum_unittest.MyEnum oneof_e_1 = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(40u)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid(value)) { set_oneof_e_1(static_cast< ::proto2_preserve_unknown_enum_unittest::MyEnum >(value)); } else { mutable_unknown_fields()->AddVarint(5, value); } } else { goto handle_unusual; } break; } // optional .proto2_preserve_unknown_enum_unittest.MyEnum oneof_e_2 = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(48u)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid(value)) { set_oneof_e_2(static_cast< ::proto2_preserve_unknown_enum_unittest::MyEnum >(value)); } else { mutable_unknown_fields()->AddVarint(6, value); } } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:proto2_preserve_unknown_enum_unittest.MyMessage) return true; failure: // @@protoc_insertion_point(parse_failure:proto2_preserve_unknown_enum_unittest.MyMessage) return false; #undef DO_ } void MyMessage::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:proto2_preserve_unknown_enum_unittest.MyMessage) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .proto2_preserve_unknown_enum_unittest.MyEnum e = 1; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 1, this->e(), output); } // repeated .proto2_preserve_unknown_enum_unittest.MyEnum repeated_e = 2; for (int i = 0, n = this->repeated_e_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 2, this->repeated_e(i), output); } // repeated .proto2_preserve_unknown_enum_unittest.MyEnum repeated_packed_e = 3 [packed = true]; if (this->repeated_packed_e_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag( 3, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(_repeated_packed_e_cached_byte_size_); } for (int i = 0, n = this->repeated_packed_e_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteEnumNoTag( this->repeated_packed_e(i), output); } // repeated .proto2_preserve_unknown_enum_unittest.MyEnum repeated_packed_unexpected_e = 4; for (int i = 0, n = this->repeated_packed_unexpected_e_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 4, this->repeated_packed_unexpected_e(i), output); } switch (o_case()) { case kOneofE1: ::google::protobuf::internal::WireFormatLite::WriteEnum( 5, this->oneof_e_1(), output); break; case kOneofE2: ::google::protobuf::internal::WireFormatLite::WriteEnum( 6, this->oneof_e_2(), output); break; default: ; } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:proto2_preserve_unknown_enum_unittest.MyMessage) } ::google::protobuf::uint8* MyMessage::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:proto2_preserve_unknown_enum_unittest.MyMessage) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .proto2_preserve_unknown_enum_unittest.MyEnum e = 1; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 1, this->e(), target); } // repeated .proto2_preserve_unknown_enum_unittest.MyEnum repeated_e = 2; target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 2, this->repeated_e_, target); // repeated .proto2_preserve_unknown_enum_unittest.MyEnum repeated_packed_e = 3 [packed = true]; if (this->repeated_packed_e_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 3, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( _repeated_packed_e_cached_byte_size_, target); target = ::google::protobuf::internal::WireFormatLite::WriteEnumNoTagToArray( this->repeated_packed_e_, target); } // repeated .proto2_preserve_unknown_enum_unittest.MyEnum repeated_packed_unexpected_e = 4; target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 4, this->repeated_packed_unexpected_e_, target); switch (o_case()) { case kOneofE1: target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 5, this->oneof_e_1(), target); break; case kOneofE2: target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 6, this->oneof_e_2(), target); break; default: ; } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:proto2_preserve_unknown_enum_unittest.MyMessage) return target; } size_t MyMessage::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:proto2_preserve_unknown_enum_unittest.MyMessage) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } // repeated .proto2_preserve_unknown_enum_unittest.MyEnum repeated_e = 2; { size_t data_size = 0; unsigned int count = this->repeated_e_size();for (unsigned int i = 0; i < count; i++) { data_size += ::google::protobuf::internal::WireFormatLite::EnumSize( this->repeated_e(i)); } total_size += (1UL * count) + data_size; } // repeated .proto2_preserve_unknown_enum_unittest.MyEnum repeated_packed_e = 3 [packed = true]; { size_t data_size = 0; unsigned int count = this->repeated_packed_e_size();for (unsigned int i = 0; i < count; i++) { data_size += ::google::protobuf::internal::WireFormatLite::EnumSize( this->repeated_packed_e(i)); } if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size(data_size); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _repeated_packed_e_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // repeated .proto2_preserve_unknown_enum_unittest.MyEnum repeated_packed_unexpected_e = 4; { size_t data_size = 0; unsigned int count = this->repeated_packed_unexpected_e_size();for (unsigned int i = 0; i < count; i++) { data_size += ::google::protobuf::internal::WireFormatLite::EnumSize( this->repeated_packed_unexpected_e(i)); } total_size += (1UL * count) + data_size; } // optional .proto2_preserve_unknown_enum_unittest.MyEnum e = 1; if (has_e()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->e()); } switch (o_case()) { // optional .proto2_preserve_unknown_enum_unittest.MyEnum oneof_e_1 = 5; case kOneofE1: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->oneof_e_1()); break; } // optional .proto2_preserve_unknown_enum_unittest.MyEnum oneof_e_2 = 6; case kOneofE2: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->oneof_e_2()); break; } case O_NOT_SET: { break; } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void MyMessage::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:proto2_preserve_unknown_enum_unittest.MyMessage) GOOGLE_DCHECK_NE(&from, this); const MyMessage* source = ::google::protobuf::internal::DynamicCastToGenerated<const MyMessage>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:proto2_preserve_unknown_enum_unittest.MyMessage) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:proto2_preserve_unknown_enum_unittest.MyMessage) MergeFrom(*source); } } void MyMessage::MergeFrom(const MyMessage& from) { // @@protoc_insertion_point(class_specific_merge_from_start:proto2_preserve_unknown_enum_unittest.MyMessage) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; repeated_e_.MergeFrom(from.repeated_e_); repeated_packed_e_.MergeFrom(from.repeated_packed_e_); repeated_packed_unexpected_e_.MergeFrom(from.repeated_packed_unexpected_e_); if (from.has_e()) { set_e(from.e()); } switch (from.o_case()) { case kOneofE1: { set_oneof_e_1(from.oneof_e_1()); break; } case kOneofE2: { set_oneof_e_2(from.oneof_e_2()); break; } case O_NOT_SET: { break; } } } void MyMessage::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:proto2_preserve_unknown_enum_unittest.MyMessage) if (&from == this) return; Clear(); MergeFrom(from); } void MyMessage::CopyFrom(const MyMessage& from) { // @@protoc_insertion_point(class_specific_copy_from_start:proto2_preserve_unknown_enum_unittest.MyMessage) if (&from == this) return; Clear(); MergeFrom(from); } bool MyMessage::IsInitialized() const { return true; } void MyMessage::Swap(MyMessage* other) { if (other == this) return; InternalSwap(other); } void MyMessage::InternalSwap(MyMessage* other) { repeated_e_.InternalSwap(&other->repeated_e_); repeated_packed_e_.InternalSwap(&other->repeated_packed_e_); repeated_packed_unexpected_e_.InternalSwap(&other->repeated_packed_unexpected_e_); std::swap(e_, other->e_); std::swap(o_, other->o_); std::swap(_oneof_case_[0], other->_oneof_case_[0]); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata MyMessage::GetMetadata() const { protobuf_google_2fprotobuf_2funittest_5fpreserve_5funknown_5fenum2_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_google_2fprotobuf_2funittest_5fpreserve_5funknown_5fenum2_2eproto::file_level_metadata[kIndexInFileMessages]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // MyMessage // optional .proto2_preserve_unknown_enum_unittest.MyEnum e = 1; bool MyMessage::has_e() const { return (_has_bits_[0] & 0x00000001u) != 0; } void MyMessage::set_has_e() { _has_bits_[0] |= 0x00000001u; } void MyMessage::clear_has_e() { _has_bits_[0] &= ~0x00000001u; } void MyMessage::clear_e() { e_ = 0; clear_has_e(); } ::proto2_preserve_unknown_enum_unittest::MyEnum MyMessage::e() const { // @@protoc_insertion_point(field_get:proto2_preserve_unknown_enum_unittest.MyMessage.e) return static_cast< ::proto2_preserve_unknown_enum_unittest::MyEnum >(e_); } void MyMessage::set_e(::proto2_preserve_unknown_enum_unittest::MyEnum value) { assert(::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid(value)); set_has_e(); e_ = value; // @@protoc_insertion_point(field_set:proto2_preserve_unknown_enum_unittest.MyMessage.e) } // repeated .proto2_preserve_unknown_enum_unittest.MyEnum repeated_e = 2; int MyMessage::repeated_e_size() const { return repeated_e_.size(); } void MyMessage::clear_repeated_e() { repeated_e_.Clear(); } ::proto2_preserve_unknown_enum_unittest::MyEnum MyMessage::repeated_e(int index) const { // @@protoc_insertion_point(field_get:proto2_preserve_unknown_enum_unittest.MyMessage.repeated_e) return static_cast< ::proto2_preserve_unknown_enum_unittest::MyEnum >(repeated_e_.Get(index)); } void MyMessage::set_repeated_e(int index, ::proto2_preserve_unknown_enum_unittest::MyEnum value) { assert(::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid(value)); repeated_e_.Set(index, value); // @@protoc_insertion_point(field_set:proto2_preserve_unknown_enum_unittest.MyMessage.repeated_e) } void MyMessage::add_repeated_e(::proto2_preserve_unknown_enum_unittest::MyEnum value) { assert(::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid(value)); repeated_e_.Add(value); // @@protoc_insertion_point(field_add:proto2_preserve_unknown_enum_unittest.MyMessage.repeated_e) } const ::google::protobuf::RepeatedField<int>& MyMessage::repeated_e() const { // @@protoc_insertion_point(field_list:proto2_preserve_unknown_enum_unittest.MyMessage.repeated_e) return repeated_e_; } ::google::protobuf::RepeatedField<int>* MyMessage::mutable_repeated_e() { // @@protoc_insertion_point(field_mutable_list:proto2_preserve_unknown_enum_unittest.MyMessage.repeated_e) return &repeated_e_; } // repeated .proto2_preserve_unknown_enum_unittest.MyEnum repeated_packed_e = 3 [packed = true]; int MyMessage::repeated_packed_e_size() const { return repeated_packed_e_.size(); } void MyMessage::clear_repeated_packed_e() { repeated_packed_e_.Clear(); } ::proto2_preserve_unknown_enum_unittest::MyEnum MyMessage::repeated_packed_e(int index) const { // @@protoc_insertion_point(field_get:proto2_preserve_unknown_enum_unittest.MyMessage.repeated_packed_e) return static_cast< ::proto2_preserve_unknown_enum_unittest::MyEnum >(repeated_packed_e_.Get(index)); } void MyMessage::set_repeated_packed_e(int index, ::proto2_preserve_unknown_enum_unittest::MyEnum value) { assert(::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid(value)); repeated_packed_e_.Set(index, value); // @@protoc_insertion_point(field_set:proto2_preserve_unknown_enum_unittest.MyMessage.repeated_packed_e) } void MyMessage::add_repeated_packed_e(::proto2_preserve_unknown_enum_unittest::MyEnum value) { assert(::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid(value)); repeated_packed_e_.Add(value); // @@protoc_insertion_point(field_add:proto2_preserve_unknown_enum_unittest.MyMessage.repeated_packed_e) } const ::google::protobuf::RepeatedField<int>& MyMessage::repeated_packed_e() const { // @@protoc_insertion_point(field_list:proto2_preserve_unknown_enum_unittest.MyMessage.repeated_packed_e) return repeated_packed_e_; } ::google::protobuf::RepeatedField<int>* MyMessage::mutable_repeated_packed_e() { // @@protoc_insertion_point(field_mutable_list:proto2_preserve_unknown_enum_unittest.MyMessage.repeated_packed_e) return &repeated_packed_e_; } // repeated .proto2_preserve_unknown_enum_unittest.MyEnum repeated_packed_unexpected_e = 4; int MyMessage::repeated_packed_unexpected_e_size() const { return repeated_packed_unexpected_e_.size(); } void MyMessage::clear_repeated_packed_unexpected_e() { repeated_packed_unexpected_e_.Clear(); } ::proto2_preserve_unknown_enum_unittest::MyEnum MyMessage::repeated_packed_unexpected_e(int index) const { // @@protoc_insertion_point(field_get:proto2_preserve_unknown_enum_unittest.MyMessage.repeated_packed_unexpected_e) return static_cast< ::proto2_preserve_unknown_enum_unittest::MyEnum >(repeated_packed_unexpected_e_.Get(index)); } void MyMessage::set_repeated_packed_unexpected_e(int index, ::proto2_preserve_unknown_enum_unittest::MyEnum value) { assert(::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid(value)); repeated_packed_unexpected_e_.Set(index, value); // @@protoc_insertion_point(field_set:proto2_preserve_unknown_enum_unittest.MyMessage.repeated_packed_unexpected_e) } void MyMessage::add_repeated_packed_unexpected_e(::proto2_preserve_unknown_enum_unittest::MyEnum value) { assert(::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid(value)); repeated_packed_unexpected_e_.Add(value); // @@protoc_insertion_point(field_add:proto2_preserve_unknown_enum_unittest.MyMessage.repeated_packed_unexpected_e) } const ::google::protobuf::RepeatedField<int>& MyMessage::repeated_packed_unexpected_e() const { // @@protoc_insertion_point(field_list:proto2_preserve_unknown_enum_unittest.MyMessage.repeated_packed_unexpected_e) return repeated_packed_unexpected_e_; } ::google::protobuf::RepeatedField<int>* MyMessage::mutable_repeated_packed_unexpected_e() { // @@protoc_insertion_point(field_mutable_list:proto2_preserve_unknown_enum_unittest.MyMessage.repeated_packed_unexpected_e) return &repeated_packed_unexpected_e_; } // optional .proto2_preserve_unknown_enum_unittest.MyEnum oneof_e_1 = 5; bool MyMessage::has_oneof_e_1() const { return o_case() == kOneofE1; } void MyMessage::set_has_oneof_e_1() { _oneof_case_[0] = kOneofE1; } void MyMessage::clear_oneof_e_1() { if (has_oneof_e_1()) { o_.oneof_e_1_ = 0; clear_has_o(); } } ::proto2_preserve_unknown_enum_unittest::MyEnum MyMessage::oneof_e_1() const { // @@protoc_insertion_point(field_get:proto2_preserve_unknown_enum_unittest.MyMessage.oneof_e_1) if (has_oneof_e_1()) { return static_cast< ::proto2_preserve_unknown_enum_unittest::MyEnum >(o_.oneof_e_1_); } return static_cast< ::proto2_preserve_unknown_enum_unittest::MyEnum >(0); } void MyMessage::set_oneof_e_1(::proto2_preserve_unknown_enum_unittest::MyEnum value) { assert(::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid(value)); if (!has_oneof_e_1()) { clear_o(); set_has_oneof_e_1(); } o_.oneof_e_1_ = value; // @@protoc_insertion_point(field_set:proto2_preserve_unknown_enum_unittest.MyMessage.oneof_e_1) } // optional .proto2_preserve_unknown_enum_unittest.MyEnum oneof_e_2 = 6; bool MyMessage::has_oneof_e_2() const { return o_case() == kOneofE2; } void MyMessage::set_has_oneof_e_2() { _oneof_case_[0] = kOneofE2; } void MyMessage::clear_oneof_e_2() { if (has_oneof_e_2()) { o_.oneof_e_2_ = 0; clear_has_o(); } } ::proto2_preserve_unknown_enum_unittest::MyEnum MyMessage::oneof_e_2() const { // @@protoc_insertion_point(field_get:proto2_preserve_unknown_enum_unittest.MyMessage.oneof_e_2) if (has_oneof_e_2()) { return static_cast< ::proto2_preserve_unknown_enum_unittest::MyEnum >(o_.oneof_e_2_); } return static_cast< ::proto2_preserve_unknown_enum_unittest::MyEnum >(0); } void MyMessage::set_oneof_e_2(::proto2_preserve_unknown_enum_unittest::MyEnum value) { assert(::proto2_preserve_unknown_enum_unittest::MyEnum_IsValid(value)); if (!has_oneof_e_2()) { clear_o(); set_has_oneof_e_2(); } o_.oneof_e_2_ = value; // @@protoc_insertion_point(field_set:proto2_preserve_unknown_enum_unittest.MyMessage.oneof_e_2) } bool MyMessage::has_o() const { return o_case() != O_NOT_SET; } void MyMessage::clear_has_o() { _oneof_case_[0] = O_NOT_SET; } MyMessage::OCase MyMessage::o_case() const { return MyMessage::OCase(_oneof_case_[0]); } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace proto2_preserve_unknown_enum_unittest // @@protoc_insertion_point(global_scope)
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2016 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * Contributor(s): * * Portions Copyrighted 2016 Sun Microsystems, Inc. */ package beans; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author marc.gareta */ @Entity @Table(name = "TIPO_SERVICIO", catalog = "", schema = "APP") @XmlRootElement @NamedQueries({ @NamedQuery(name = "TIPO_SERVICIO.findAll", query = "SELECT t FROM TipoServicio t"), @NamedQuery(name = "TIPO_SERVICIO.findAllNombre", query = "SELECT t.nombre FROM TipoServicio t"), @NamedQuery(name = "TIPO_SERVICIO.findById", query = "SELECT t FROM TipoServicio t WHERE t.id = :id"), @NamedQuery(name = "TIPO_SERVICIO.findByNombre", query = "SELECT t FROM TipoServicio t WHERE t.nombre = :nombre"), @NamedQuery(name = "TIPO_SERVICIO.deleteAll", query = "DELETE FROM TipoServicio t")}) public class TipoServicio implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(nullable = false) private Integer id; @Column(length = 100) private String nombre; @OneToMany(mappedBy = "tipoServicio") private Collection<ParteIncidencia> parteIncidenciaCollection; public TipoServicio() { } public TipoServicio(Integer id) { this.id = id; } public TipoServicio(String nombre) { this.nombre = nombre; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } @XmlTransient public Collection<ParteIncidencia> getParteIncidenciaCollection() { return parteIncidenciaCollection; } public void setParteIncidenciaCollection(Collection<ParteIncidencia> parteIncidenciaCollection) { this.parteIncidenciaCollection = parteIncidenciaCollection; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof TipoServicio)) { return false; } TipoServicio other = (TipoServicio) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "beans.TipoServicio[ id=" + id + " ]"; } }
Java
--- title: Announcing Istio 1.11.6 linktitle: 1.11.6 subtitle: Patch Release description: Istio 1.11.6 patch release. publishdate: 2022-02-03 release: 1.11.6 aliases: - /news/announcing-1.11.6 --- This release contains bug fixes to improve robustness. This release note describes what’s different between Istio 1.11.5 and Istio 1.11.6 {{< relnote >}} ## Changes - **Added** privileged flag to Istio-CNI Helm charts to set `securityContext` flag. ([Issue #34211](https://github.com/istio/istio/issues/34211)) - **Added** an option to disable a number of nonstandard kubeconfig authentication methods when using multicluster secret by configuring the `PILOT_INSECURE_MULTICLUSTER_KUBECONFIG_OPTIONS` environment variable in Istiod. By default, this option is configured to allow all methods; future versions will restrict this by default. - **Fixed** an issue where enabling tracing with telemetry API would cause a malformed host header being used at the trace report request. ([Issue #35750](https://github.com/istio/istio/issues/35750)),([Issue #36166](https://github.com/istio/istio/issues/36166)),([Issue #36521](https://github.com/istio/istio/issues/36521)) - **Fixed** error format after json marshal in virtual machine config. ([Issue #36358](https://github.com/istio/istio/issues/36358)) - **Fixed** endpoint slice cache memory leak. - **Fixed** an issue where `EnvoyFilter` patches on `virtualOutbound-blackhole` could cause memory leaks. - **Fixed** an issue where using `ISTIO_MUTUAL` TLS mode in Gateways while also setting `credentialName` causes mutual TLS to not be configured. For backwards compatibility, this only introduces a warning. To enable the new behavior, set the `PILOT_ENABLE_LEGACY_ISTIO_MUTUAL_CREDENTIAL_NAME=false` environment variable in Istiod. This will cause invalid configurations to be rejected, and will be the default behavior in future releases.
Java
namespace Snippets3.Serialization { using NServiceBus; public class BinarySerializerUsage { public void Simple() { #region BinarySerialization Configure configure = Configure.With(); configure.BinarySerializer(); #endregion } } }
Java
Ext.define('TaxRate', { extend: 'Ext.data.Model', fields: [{name: "id"}, {name: "date",type: 'date',dateFormat: 'Y-m-d'}, {name: "rate"}, {name: "remark"}, {name: "create_time",type: 'date',dateFormat: 'timestamp'}, {name: "update_time",type: 'date',dateFormat: 'timestamp'}, {name: "creater"}, {name: "updater"}] }); var taxRateStore = Ext.create('Ext.data.Store', { model: 'TaxRate', proxy: { type: 'ajax', reader: 'json', url: homePath+'/public/erp/setting_tax/gettaxrate/option/data' } }); var taxRateRowEditing = Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 1 }); // 税率管理窗口 var taxRateWin = Ext.create('Ext.window.Window', { title: '税率管理', border: 0, height: 300, width: 600, modal: true, constrain: true, closeAction: 'hide', layout: 'fit', tools: [{ type: 'refresh', tooltip: 'Refresh', scope: this, handler: function(){taxRateStore.reload();} }], items: [{ xtype: 'gridpanel', id: 'taxRateGrid', columnLines: true, store: taxRateStore, selType: 'checkboxmodel', tbar: [{ xtype: 'hiddenfield', id: 'tax_id_to_rate' }, { text: '添加税率', iconCls: 'icon-add', scope: this, handler: function(){ taxRateRowEditing.cancelEdit(); var r = Ext.create('TaxRate', { date: Ext.util.Format.date(new Date(), 'Y-m-d'), rate: 1 }); taxRateStore.insert(0, r); taxRateRowEditing.startEdit(0, 0); } }, { text: '删除税率', iconCls: 'icon-delete', scope: this, handler: function(){ var selection = Ext.getCmp('taxRateGrid').getView().getSelectionModel().getSelection(); if(selection.length > 0){ taxRateStore.remove(selection); }else{ Ext.MessageBox.alert('错误', '没有选择删除对象!'); } } }, { text: '保存修改', iconCls: 'icon-save', scope: this, handler: function(){ var updateRecords = taxRateStore.getUpdatedRecords(); var insertRecords = taxRateStore.getNewRecords(); var deleteRecords = taxRateStore.getRemovedRecords(); // 判断是否有修改数据 if(updateRecords.length + insertRecords.length + deleteRecords.length > 0){ var changeRows = { updated: [], inserted: [], deleted: [] } for(var i = 0; i < updateRecords.length; i++){ var data = updateRecords[i].data; changeRows.updated.push(data) } for(var i = 0; i < insertRecords.length; i++){ var data = insertRecords[i].data; changeRows.inserted.push(data) } for(var i = 0; i < deleteRecords.length; i++){ changeRows.deleted.push(deleteRecords[i].data) } Ext.MessageBox.confirm('确认', '确定保存修改内容?', function(button, text){ if(button == 'yes'){ var json = Ext.JSON.encode(changeRows); var selection = Ext.getCmp('taxGrid').getView().getSelectionModel().getSelection(); Ext.Msg.wait('提交中,请稍后...', '提示'); Ext.Ajax.request({ url: homePath+'/public/erp/setting_tax/edittaxrate', params: {json: json, tax_id: Ext.getCmp('tax_id_to_rate').value}, method: 'POST', success: function(response, options) { var data = Ext.JSON.decode(response.responseText); if(data.success){ Ext.MessageBox.alert('提示', data.info); taxRateStore.reload(); taxStore.reload(); }else{ Ext.MessageBox.alert('错误', data.info); } }, failure: function(response){ Ext.MessageBox.alert('错误', '保存提交失败'); } }); } }); }else{ Ext.MessageBox.alert('提示', '没有修改任何数据!'); } } }, '->', { text: '刷新', iconCls: 'icon-refresh', handler: function(){ taxRateStore.reload(); } }], plugins: taxRateRowEditing, columns: [{ xtype: 'rownumberer' }, { text: 'ID', dataIndex: 'id', hidden: true, flex: 1 }, { text: '生效日期', dataIndex: 'date', renderer: Ext.util.Format.dateRenderer('Y-m-d'), editor: { xtype: 'datefield', editable: false, format: 'Y-m-d' }, flex: 3 }, { text: '税率', dataIndex: 'rate', editor: 'numberfield', flex: 2 }, { text: '备注', dataIndex: 'remark', editor: 'textfield', flex: 5 }, { text: '创建人', hidden: true, dataIndex: 'creater', flex: 2 }, { text: '创建时间', hidden: true, dataIndex: 'create_time', renderer : Ext.util.Format.dateRenderer('Y-m-d H:i:s'), flex: 3 }, { text: '更新人', hidden: true, dataIndex: 'updater', flex: 2 }, { text: '更新时间', hidden: true, dataIndex: 'update_time', renderer : Ext.util.Format.dateRenderer('Y-m-d H:i:s'), flex: 3 }] }] });
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_55) on Thu Jan 22 11:30:09 CST 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>ICreate</title> <meta name="date" content="2015-01-22"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ICreate"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/ICreate.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../com/share/mod/pay/ali/wap/inter/ICallback.html" title="interface in com.share.mod.pay.ali.wap.inter"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../../com/share/mod/pay/ali/wap/inter/IInterrupt.html" title="interface in com.share.mod.pay.ali.wap.inter"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/share/mod/pay/ali/wap/inter/ICreate.html" target="_top">Frames</a></li> <li><a href="ICreate.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.share.mod.pay.ali.wap.inter</div> <h2 title="Interface ICreate" class="title">Interface ICreate</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public interface <span class="strong">ICreate</span></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../com/share/mod/pay/ali/wap/inter/ICreate.html#createOutTradeNo()">createOutTradeNo</a></strong>()</code> <div class="block">创建商户订单号</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../../../com/share/mod/pay/ali/wap/inter/ICreate.html#handleException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Exception)">handleException</a></strong>(javax.servlet.http.HttpServletRequest&nbsp;request, javax.servlet.http.HttpServletResponse&nbsp;response, java.lang.Exception&nbsp;e)</code> <div class="block">处理异常</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../../../com/share/mod/pay/ali/wap/inter/ICreate.html#handleNumberFormatException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)">handleNumberFormatException</a></strong>(javax.servlet.http.HttpServletRequest&nbsp;request, javax.servlet.http.HttpServletResponse&nbsp;response)</code> <div class="block">处理金额异常</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../../../com/share/mod/pay/ali/wap/inter/ICreate.html#save(javax.servlet.http.HttpServletRequest)">save</a></strong>(javax.servlet.http.HttpServletRequest&nbsp;request)</code> <div class="block">根据请求记录创建订单记录</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="createOutTradeNo()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>createOutTradeNo</h4> <pre>java.lang.String&nbsp;createOutTradeNo()</pre> <div class="block">创建商户订单号</div> <dl><dt><span class="strong">Returns:</span></dt><dd></dd></dl> </li> </ul> <a name="handleNumberFormatException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>handleNumberFormatException</h4> <pre>void&nbsp;handleNumberFormatException(javax.servlet.http.HttpServletRequest&nbsp;request, javax.servlet.http.HttpServletResponse&nbsp;response) throws javax.servlet.ServletException, java.io.IOException</pre> <div class="block">处理金额异常</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>request</code> - </dd><dd><code>response</code> - </dd> <dt><span class="strong">Throws:</span></dt> <dd><code>javax.servlet.ServletException</code></dd> <dd><code>java.io.IOException</code></dd></dl> </li> </ul> <a name="handleException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Exception)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>handleException</h4> <pre>void&nbsp;handleException(javax.servlet.http.HttpServletRequest&nbsp;request, javax.servlet.http.HttpServletResponse&nbsp;response, java.lang.Exception&nbsp;e) throws javax.servlet.ServletException, java.io.IOException</pre> <div class="block">处理异常</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>request</code> - </dd><dd><code>response</code> - </dd> <dt><span class="strong">Throws:</span></dt> <dd><code>javax.servlet.ServletException</code></dd> <dd><code>java.io.IOException</code></dd></dl> </li> </ul> <a name="save(javax.servlet.http.HttpServletRequest)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>save</h4> <pre>void&nbsp;save(javax.servlet.http.HttpServletRequest&nbsp;request) throws javax.servlet.ServletException, java.io.IOException</pre> <div class="block">根据请求记录创建订单记录</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>request</code> - </dd><dd><code>response</code> - </dd> <dt><span class="strong">Throws:</span></dt> <dd><code>javax.servlet.ServletException</code></dd> <dd><code>java.io.IOException</code></dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/ICreate.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../com/share/mod/pay/ali/wap/inter/ICallback.html" title="interface in com.share.mod.pay.ali.wap.inter"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../../com/share/mod/pay/ali/wap/inter/IInterrupt.html" title="interface in com.share.mod.pay.ali.wap.inter"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/share/mod/pay/ali/wap/inter/ICreate.html" target="_top">Frames</a></li> <li><a href="ICreate.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Java
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Aula2505.Views.Categorias { public partial class Excluir { } }
Java
--- layout: post title: "2017年终总结" subtitle: "我这一年到底干了什么~" date: 2018-01-01 author: "Franary" tags: - Blog - 废话 - 2018 --- # 2017 ## 年终总结 ## Code - Github: 218次提交 - 学习 - 阿里云 云服务器工程师 认证 - PHP CURL库 Laravel框架 - Mysql基础语法 - 项目 - 图片爬虫[Image-spider](https://github.com/Chenjinyi/Image-spider) - 四套官方网站(团队内部) - 个人网站API [MyWebApi](https://github.com/Chenjinyi/MyWebApi) - 个人在线交易平台 [Art_Online](https://github.com/Chenjinyi/Art_Online) - 项目进度表[Project_progress](https://github.com/Chenjinyi/Project_progress) - Shell Web管理 (未完成) ## Hardware - Wacom CTH-490 ## Game - 单机游戏 - 完美通关《地平线 零之曙光》 - 完美通关《尼尔:机械纪元》 - 完美通关《巫师3》 - 完美通关 《美好世界(WILL)》 - 《Watch_Dogs2》2017全DLC - 《HackNet》8小时游戏时间 - 《命运石之门》3小时游戏时间\ - 《辐射4》1小时游戏时间 - 联机游戏 - 通关《BattleBlock Theater》 - 《彩虹六号》121小时游戏时间 - 《剑侠情缘三:重置版(三测)》14小时游戏时间 - 《剑侠情缘三》42小时游戏时间 - 《天涯明月刀》152小时游戏时间 - 《CSGO》154小时游戏时间 - 《暗黑破坏神3》97小时游玩时间 - 《绝地求生》10小时游戏时间 - 《守望先锋》40小时游戏时间 - 《Stick Fight The Game》2小时游戏时间 ## Coffee - 咖啡豆 - 阿拉比卡(多个产地) - 曼特宁(多种产地) - 西达摩 - 苏门答腊 - 耶加雪菲 - 歌伦比亚 - 器材 - 法压壶 - 家用意式机 - 家用磨豆机
Java
package ch.bfh.swos.bookapp.jpa.model; import javax.persistence.*; import java.io.Serializable; import java.util.Date; import static javax.persistence.GenerationType.IDENTITY; import static javax.persistence.TemporalType.DATE; /** * Entity implementation class for Entity: Book * */ @Entity public class Book implements Serializable { @Id @GeneratedValue(strategy = IDENTITY) private Long id; private String bookId; private String title; @Temporal(DATE) private Date releaseDate; private static final long serialVersionUID = 1L; @ManyToOne private Author author; public Book() { super(); } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getBookId() { return bookId; } public void setBookId(String bookId) { this.bookId = bookId; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public Date getReleaseDate() { return this.releaseDate; } public void setReleaseDate(Date releaseDate) { this.releaseDate = releaseDate; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } }
Java
<?php namespace App\Util; use Illuminate\Support\Facades\DB; class Access { // list all perm // if the returned array is empty then user dont have permission to list the perms public static function listPerm($userid, $appcode) { if (self::can_editPerm($userid, $appcode) == false) return []; $app = DB::table('apps')->where('code', $appcode)->first(); if ($app == null) return -3; return DB::table('user_app') ->join('users', 'user_app.userid', '=', 'users.id') ->where('user_app.appid', $app->id)->get(); } // used to delete user from app // return // -1 acess deny // -3 appid doesn't exist // -4 cannot delte owner // public static function deletePerm($userid, $otherid, $appcode) { // get owner $app = DB::table('apps')->where('code', $appcode)->first(); if ($app == null) return -3; if ($otherid == $app->ownerid) return -4; if (self::can_editPerm($userid, $app->id)) { DB::table('user_app')->where('appid', $app->id)->where('userid', $otherid)->delete(); return 0; } return -1; } // used to add new user to app // or $userid set perm for $otheruserid, // if $can_perm is differ than null, then its value is valid // if $can_struct is differ than null, then its value is valid // if $can_reportis differ than null, then its value is valid // 0 means unset, 1 means set // return 0 if sucecss // -1: access deny // -2 other user not exist in app, must add first // -3 appid doesn't exist // -4 cannot set perm for owner // -5 if user doesn't exist public static function setPerm($userid, $otheruser, $appcode, $can_perm, $can_struct, $can_report) { //check if user existed if (DB::table('users')->where('id', $otheruser)->count() + DB::table('users')->where('id', $userid)->count() != 2) return -5; // get owner $app = DB::table('apps')->where('code', $appcode)->first(); if ($app == null) return -3; if (self::can_editPerm($userid, $appcode)) { $perm = DB::table('user_app')->where('appid', $app->id)->where('userid', $otheruser)->first(); if ($perm == null) { if ($app->ownerid == $otheruser) DB::table('user_app')->insert( ['appid' => $app->id, 'userid' => $otheruser, 'can_perm' => 1, 'can_struct' => 1, 'can_report' => 1] ); else DB::table('user_app')->insert( ['appid' => $app->id, 'userid' => $otheruser, 'can_perm' => 0, 'can_struct' => 0, 'can_report' => 1] ); } else { if ($app->ownerid == $otheruser) { return -4; } } $permrecord = []; if ($can_perm != null) $permrecord['can_perm'] = $can_perm; if ($can_struct != null) $permrecord['can_struct'] = $can_struct; if ($can_report != null) $permrecord['can_report'] = $can_report; if (count($permrecord) != 0) { DB::table('user_app')->where('appid', $app->id)->where('userid', $otheruser)->update($permrecord); } return 0; } abort(500, "sdfdf"); return -1; } public static function isBanned($id){ $user = DB::table('users')->where('id',$id)->first(); if($user == null) return true; if(!$user->banned) return false; return true; } public static function can_editPerm($userid, $appcode) { // full access for app owner $app = DB::table('apps')->where('code', $appcode)->first(); if ($app == null) return -3; if(self::isBanned($app->ownerid)) return false; if ($app->ownerid == $userid) return true; $perm = DB::table('user_app')->where('appid', $app->id)->where('userid', $userid)->first(); if ($perm == null) return false; if ($perm->can_perm == 1) return true; return false; } public static function can_editStruct($userid, $appcode) { // full access for app owner $app = DB::table('apps')->where('code', $appcode)->first(); if ($app == null) return -3; if(self::isBanned($app->ownerid)) return false; if ($app->ownerid == $userid) return true; $perm = DB::table('user_app')->where('appid', $app->id)->where('userid', $userid)->first(); if ($perm == null) return false; if ($perm->can_struct == 1) return true; return false; } public static function can_view($userid, $appcode) { // full access for app owner $app = DB::table('apps')->where('code', $appcode)->first(); if ($app == null) return -3; if(self::isBanned($app->ownerid)) return false; if ($app->ownerid == $userid) return true; $perm = DB::table('user_app')->where('appid', $app->id)->where('userid', $userid)->first(); if ($perm == null) return false; return true; } public static function can_editReport($userid, $appcode) { // full access for app owner $app = DB::table('apps')->where('code', $appcode)->first(); if ($app == null) return -3; if(self::isBanned($app->ownerid)) return false; if ($app->ownerid == $userid) return true; $perm = DB::table('user_app')->where('appid', $app->id)->where('userid', $userid)->first(); if ($perm == null) return false; if ($perm->can_report == 1) return true; return false; } }
Java
/* * * Copyright (c) 2013-2017 Nest Labs, 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. */ /** * @file * This header file defines the <tt>nl::Inet::TCPEndPoint</tt> * class, where the Nest Inet Layer encapsulates methods for * interacting with TCP transport endpoints (SOCK_DGRAM sockets * on Linux and BSD-derived systems) or LwIP TCP protocol * control blocks, as the system is configured accordingly. */ #ifndef TCPENDPOINT_H #define TCPENDPOINT_H #include <InetLayer/EndPointBasis.h> #include <InetLayer/IPAddress.h> #include <SystemLayer/SystemPacketBuffer.h> #if WEAVE_SYSTEM_CONFIG_USE_SOCKETS #include <netinet/tcp.h> #endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS namespace nl { namespace Inet { class InetLayer; #if INET_CONFIG_TCP_CONN_REPAIR_SUPPORTED #if (!defined(TCP_REPAIR) || !defined(TCP_REPAIR_QUEUE) || !defined(TCP_REPAIR_OPTIONS) || \ !defined(TCPI_OPT_SACK) || !defined(TCPI_OPT_WSCALE) || !defined(TCPI_OPT_TIMESTAMPS) || \ !defined(TCPOPT_MAXSEG) || !defined(TCP_REPAIR_WINDOW)) #error "INET_CONFIG_TCP_CONN_REPAIR_SUPPORTED set but platform does not support TCP REPAIR" #endif typedef struct TCPConnRepairInfo { IPAddress srcIP; // Source IP address IPAddress dstIP; // Destination IP address IPAddressType addrType; // Address family type uint16_t srcPort; // Source port uint16_t dstPort; // Destination port uint32_t txSeq; // Transmit sequence uint32_t rxSeq; // Receive sequence uint32_t sndWl1; // Segment seq number for last window update uint32_t sndWnd; // Send window uint32_t maxWindow; // Max window uint32_t rcvWnd; // Receive window uint32_t rcvWup; // Last ack number that was sent/ uint32_t tsVal; // TCP Timestamp uint32_t tsecr; uint16_t mss; // Max segment size uint8_t sndWscale; // Send window scale uint8_t rcvWscale; // Receive window scale uint8_t tcpOptions; // TCP options bool IsValid (void) const; void Dump (void) const; } TCPConnRepairInfo; #endif // INET_CONFIG_TCP_CONN_REPAIR_SUPPORTED /** * @brief Objects of this class represent TCP transport endpoints. * * @details * Nest Inet Layer encapsulates methods for interacting with TCP transport * endpoints (SOCK_STREAM sockets on Linux and BSD-derived systems) or LwIP * TCP protocol control blocks, as the system is configured accordingly. */ class NL_DLL_EXPORT TCPEndPoint : public EndPointBasis { friend class InetLayer; public: /** Control switch indicating whether the application is receiving data. */ bool ReceiveEnabled; /** * @brief Basic dynamic state of the underlying endpoint. * * @details * Objects are initialized in the "ready" state, proceed to subsequent * states corresponding to a simplification of the states of the TCP * transport state machine. * * @note * The \c kBasisState_Closed state enumeration is mapped to \c kState_Ready for historical binary-compatibility reasons. The * existing \c kState_Closed exists to identify separately the distinction between "not opened yet" and "previously opened now * closed" that existed previously in the \c kState_Ready and \c kState_Closed states. */ enum { kState_Ready = kBasisState_Closed, /**< Endpoint initialized, but not bound. */ kState_Bound = 1, /**< Endpoint bound, but not listening. */ kState_Listening = 2, /**< Endpoint receiving connections. */ kState_Connecting = 3, /**< Endpoint attempting to connect. */ kState_Connected = 4, /**< Endpoint connected, ready for tx/rx. */ kState_SendShutdown = 5, /**< Endpoint initiated its half-close. */ kState_ReceiveShutdown = 6, /**< Endpoint responded to half-close. */ kState_Closing = 7, /**< Endpoint closing bidirectionally. */ kState_Closed = 8 /**< Endpoint closed, ready for release. */ } State; /** * @brief Bind the endpoint to an interface IP address. * * @param[in] addrType the protocol version of the IP address * @param[in] addr the IP address (must be an interface address) * @param[in] port the TCP port * @param[in] reuseAddr option to share binding with other endpoints * * @retval INET_NO_ERROR success: endpoint bound to address * @retval INET_ERROR_INCORRECT_STATE endpoint has been bound previously * @retval INET_NO_MEMORY insufficient memory for endpoint * * @retval INET_ERROR_WRONG_PROTOCOL_TYPE * \c addrType does not match \c IPVer. * * @retval INET_ERROR_WRONG_ADDRESS_TYPE * \c addrType is \c kIPAddressType_Any, or the type of \c addr is not * equal to \c addrType. * * @retval other another system or platform error * * @details * Binds the endpoint to the specified network interface IP address. * * On LwIP, this method must not be called with the LwIP stack lock * already acquired. */ INET_ERROR Bind(IPAddressType addrType, IPAddress addr, uint16_t port, bool reuseAddr = false); /** * @brief Prepare the endpoint to receive TCP messages. * * @param[in] backlog maximum depth of connection acceptance queue * * @retval INET_NO_ERROR success: endpoint ready to receive messages. * @retval INET_ERROR_INCORRECT_STATE endpoint is already listening. * * @details * If \c State is already \c kState_Listening, then no operation is * performed, otherwise the \c State is set to \c kState_Listening and * the endpoint is prepared to received TCP messages, according to the * semantics of the platform. * * On some platforms, the \c backlog argument is not used (the depth of * the queue is fixed; only one connection may be accepted at a time). * * On LwIP systems, this method must not be called with the LwIP stack * lock already acquired */ INET_ERROR Listen(uint16_t backlog); /** * @brief Initiate a TCP connection. * * @param[in] addr the destination IP address * @param[in] port the destination TCP port * @param[in] intf an optional network interface indicator * * @retval INET_NO_ERROR success: \c msg is queued for transmit. * @retval INET_ERROR_NOT_IMPLEMENTED system implementation not complete. * * @retval INET_ERROR_WRONG_ADDRESS_TYPE * the destination address and the bound interface address do not * have matching protocol versions or address type, or the destination * address is an IPv6 link-local address and \c intf is not specified. * * @retval other another system or platform error * * @details * If possible, then this method initiates a TCP connection to the * destination \c addr (with \c intf used as the scope * identifier for IPv6 link-local destinations) and \c port. */ INET_ERROR Connect(IPAddress addr, uint16_t port, InterfaceId intf = INET_NULL_INTERFACEID); /** * @brief Extract IP address and TCP port of remote endpoint. * * @param[out] retAddr IP address of remote endpoint. * @param[out] retPort TCP port of remote endpoint. * * @retval INET_NO_ERROR success: address and port extracted. * @retval INET_ERROR_INCORRECT_STATE TCP connection not established. * @retval INET_ERROR_CONNECTION_ABORTED TCP connection no longer open. * * @details * Do not use \c NULL pointer values for either argument. */ INET_ERROR GetPeerInfo(IPAddress *retAddr, uint16_t *retPort) const; /** * @brief Extract IP address and TCP port of local endpoint. * * @param[out] retAddr IP address of local endpoint. * @param[out] retPort TCP port of local endpoint. * * @retval INET_NO_ERROR success: address and port extracted. * @retval INET_ERROR_INCORRECT_STATE TCP connection not established. * @retval INET_ERROR_CONNECTION_ABORTED TCP connection no longer open. * * @details * Do not use \c NULL pointer values for either argument. */ INET_ERROR GetLocalInfo(IPAddress *retAddr, uint16_t *retPort); /** * @brief Send message text on TCP connection. * * @param[out] data Message text to send. * @param[out] push If \c true, then send immediately, otherwise queue. * * @retval INET_NO_ERROR success: address and port extracted. * @retval INET_ERROR_INCORRECT_STATE TCP connection not established. * * @details * The <tt>Weave::System::PacketBuffer::Free</tt> method is called on the \c data argument * regardless of whether the transmission is successful or failed. */ INET_ERROR Send(Weave::System::PacketBuffer *data, bool push = true); /** * @brief Disable reception. * * @details * Disable all event handlers. Data sent to an endpoint that disables * reception will be acknowledged until the receive window is exhausted. */ void DisableReceive(void); /** * @brief Enable reception. * * @details * Enable all event handlers. Data sent to an endpoint that disables * reception will be acknowledged until the receive window is exhausted. */ void EnableReceive(void); /** * @brief EnableNoDelay */ INET_ERROR EnableNoDelay(void); /** * @brief Enable the TCP "keep-alive" option. * * @param[in] interval time in seconds between probe requests. * @param[in] timeoutCount number of probes to send before timeout. * * @retval INET_NO_ERROR success: address and port extracted. * @retval INET_ERROR_INCORRECT_STATE TCP connection not established. * @retval INET_ERROR_CONNECTION_ABORTED TCP connection no longer open. * @retval INET_ERROR_NOT_IMPLEMENTED system implementation not complete. * * @retval other another system or platform error * * @details * Start automatically transmitting TCP "keep-alive" probe segments every * \c interval seconds. The connection will abort automatically after * receiving a negative response, or after sending \c timeoutCount * probe segments without receiving a positive response. * * See RFC 1122, section 4.2.3.6 for specification details. */ INET_ERROR EnableKeepAlive(uint16_t interval, uint16_t timeoutCount); /** * @brief Disable the TCP "keep-alive" option. * * @retval INET_NO_ERROR success: address and port extracted. * @retval INET_ERROR_INCORRECT_STATE TCP connection not established. * @retval INET_ERROR_CONNECTION_ABORTED TCP connection no longer open. * @retval INET_ERROR_NOT_IMPLEMENTED system implementation not complete. * * @retval other another system or platform error */ INET_ERROR DisableKeepAlive(void); /** * @brief Set the TCP TCP_USER_TIMEOUT socket option. * * @param[in] userTimeoutMillis Tcp user timeout value in milliseconds. * * @retval INET_NO_ERROR success: address and port extracted. * @retval INET_ERROR_NOT_IMPLEMENTED system implementation not complete. * * @retval other another system or platform error * * @details * When the value is greater than 0, it specifies the maximum amount of * time in milliseconds that transmitted data may remain * unacknowledged before TCP will forcibly close the * corresponding connection. If the option value is specified as 0, * TCP will to use the system default. * See RFC 5482, for further details. */ INET_ERROR SetUserTimeout(uint32_t userTimeoutMillis); /** * @brief Acknowledge receipt of message text. * * @param[in] len number of bytes to acknowledge. * * @retval INET_NO_ERROR success: reception acknowledged. * @retval INET_ERROR_INCORRECT_STATE TCP connection not established. * @retval INET_ERROR_CONNECTION_ABORTED TCP connection no longer open. * * @details * Use this method to acknowledge reception of all or part of the data * received. The operational semantics are undefined if \c len is larger * than the total outstanding unacknowledged received data. */ INET_ERROR AckReceive(uint16_t len); /** * @brief Push message text back to the head of the receive queue. * * @param[out] data Message text to push. * * @retval INET_NO_ERROR success: reception acknowledged. * @retval INET_ERROR_INCORRECT_STATE TCP connection not established. * * @details * This method may only be called by data reception event handlers to * put an unacknowledged portion of data back on the receive queue. The * operational semantics are undefined if the caller is outside the scope * of a data reception event handler, \c data is not the \c Weave::System::PacketBuffer * provided to the handler, or \c data does not contain the unacknowledged * portion remaining after the bytes acknowledged by a prior call to the * <tt>AckReceive(uint16_t len)</tt> method. */ INET_ERROR PutBackReceivedData(Weave::System::PacketBuffer *data); /** * @brief Extract the length of the data awaiting first transmit. * * @return Number of untransmitted bytes in the transmit queue. */ uint32_t PendingSendLength(void); /** * @brief Extract the length of the unacknowledged receive data. * * @return Number of bytes in the receive queue that have not yet been * acknowledged with <tt>AckReceive(uint16_t len)</tt>. */ uint32_t PendingReceiveLength(void); /** * @brief Initiate TCP half close, in other words, finished with sending. * * @retval INET_NO_ERROR success: address and port extracted. * @retval INET_ERROR_INCORRECT_STATE TCP connection not established. * * @retval other another system or platform error */ INET_ERROR Shutdown(void); /** * @brief Initiate TCP full close, in other words, finished with both send and * receive. * * @retval INET_NO_ERROR success: address and port extracted. * @retval INET_ERROR_INCORRECT_STATE TCP connection not established. * * @retval other another system or platform error */ INET_ERROR Close(void); /** * @brief Abortively close the endpoint, in other words, send RST packets. */ void Abort(void); /** * @brief Initiate (or continue) TCP full close, ignoring errors. * * @details * The object is returned to the free pool, and all remaining user * references are subsequently invalid. */ void Free(void); /** * @brief Extract whether TCP connection is established. */ bool IsConnected(void) const; void SetConnectTimeout(const uint32_t connTimeoutMsecs); #if INET_TCP_IDLE_CHECK_INTERVAL > 0 /** * @brief Set timer event for idle activity. * * @param[in] timeoutMS * * @details * Set the idle timer interval to \c timeoutMS milliseconds. A zero * time interval implies the idle timer is disabled. */ void SetIdleTimeout(uint32_t timeoutMS); #endif // INET_TCP_IDLE_CHECK_INTERVAL > 0 /** * @brief Note activity, in other words, reset the idle timer. * * @details * Reset the idle timer to zero. */ void MarkActive(void); /** * @brief Obtain an identifier for the endpoint. * * @return Returns an opaque unique identifier for use logs. */ uint16_t LogId(void); #if INET_CONFIG_TCP_CONN_REPAIR_SUPPORTED INET_ERROR RepairConnection(const TCPConnRepairInfo &connRepairInfo, InterfaceId intf); #endif // INET_CONFIG_TCP_CONN_REPAIR_SUPPORTED /** * @brief Type of connection establishment event handling function. * * @param[in] endPoint The TCP endpoint associated with the event. * @param[in] err \c INET_NO_ERROR if success, else another code. * * @details * Provide a function of this type to the \c OnConnectComplete delegate * member to process connection establishment events on \c endPoint. The * \c err argument distinguishes successful connections from failures. */ typedef void (*OnConnectCompleteFunct)(TCPEndPoint *endPoint, INET_ERROR err); /** * The endpoint's connection establishment event handling function * delegate. */ OnConnectCompleteFunct OnConnectComplete; /** * @brief Type of data reception event handling function. * * @param[in] endPoint The TCP endpoint associated with the event. * @param[in] data The data received. * * @details * Provide a function of this type to the \c OnDataReceived delegate * member to process data reception events on \c endPoint where \c data * is the message text received. * * A data reception event handler must acknowledge data processed using * the \c AckReceive method. The \c Free method on the data buffer must * also be invoked unless the \c PutBackReceivedData is used instead. */ typedef void (*OnDataReceivedFunct)(TCPEndPoint *endPoint, Weave::System::PacketBuffer *data); /** * The endpoint's message text reception event handling function delegate. */ OnDataReceivedFunct OnDataReceived; /** * @brief Type of data transmission event handling function. * * @param[in] endPoint The TCP endpoint associated with the event. * @param[in] len Number of bytes added to the transmit window. * * @details * Provide a function of this type to the \c OnDataSent delegate * member to process data transmission events on \c endPoint where \c len * is the length of the message text added to the TCP transmit window, * which are eligible for sending by the underlying network stack. */ typedef void (*OnDataSentFunct)(TCPEndPoint *endPoint, uint16_t len); /** * The endpoint's message text transmission event handling function * delegate. */ OnDataSentFunct OnDataSent; /** * @brief Type of connection establishment event handling function. * * @param[in] endPoint The TCP endpoint associated with the event. * @param[in] err \c INET_NO_ERROR if success, else another code. * * @details * Provide a function of this type to the \c OnConnectionClosed delegate * member to process connection termination events on \c endPoint. The * \c err argument distinguishes successful terminations from failures. */ typedef void (*OnConnectionClosedFunct)(TCPEndPoint *endPoint, INET_ERROR err); /** The endpoint's close event handling function delegate. */ OnConnectionClosedFunct OnConnectionClosed; /** * @brief Type of half-close reception event handling function. * * @param[in] endPoint The TCP endpoint associated with the event. * * @details * Provide a function of this type to the \c OnPeerClose delegate member * to process connection termination events on \c endPoint. */ typedef void (*OnPeerCloseFunct)(TCPEndPoint *endPoint); /** The endpoint's half-close receive event handling function delegate. */ OnPeerCloseFunct OnPeerClose; /** * @brief Type of connection received event handling function. * * @param[in] listeningEndPoint The listening TCP endpoint. * @param[in] conEndPoint The newly received TCP endpoint. * @param[in] peerAddr The IP address of the remote peer. * @param[in] peerPort The TCP port of the remote peer. * * @details * Provide a function of this type to the \c OnConnectionReceived delegate * member to process connection reception events on \c listeningEndPoint. * The newly received endpoint \c conEndPoint is located at IP address * \c peerAddr and TCP port \c peerPort. */ typedef void (*OnConnectionReceivedFunct)(TCPEndPoint *listeningEndPoint, TCPEndPoint *conEndPoint, const IPAddress &peerAddr, uint16_t peerPort); /** The endpoint's connection receive event handling function delegate. */ OnConnectionReceivedFunct OnConnectionReceived; /** * @brief Type of connection acceptance error event handling function. * * @param[in] endPoint The TCP endpoint associated with the event. * @param[in] err The reason for the error. * * @details * Provide a function of this type to the \c OnAcceptError delegate * member to process connection acceptance error events on \c endPoint. The * \c err argument provides specific detail about the type of the error. */ typedef void (*OnAcceptErrorFunct)(TCPEndPoint *endPoint, INET_ERROR err); /** * The endpoint's connection acceptance event handling function delegate. */ OnAcceptErrorFunct OnAcceptError; #if INET_CONFIG_ENABLE_TCP_SEND_IDLE_CALLBACKS /** * @brief Type of TCP SendIdle changed signal handling function. * * @param[in] endPoint The TCP endpoint associated with the event. * * @param[in] isIdle True if the send channel of the TCP endpoint * is Idle, otherwise false. * @details * Provide a function of this type to the \c OnTCPSendIdleChanged delegate * member to process the event of the send channel of the TCPEndPoint * changing state between being idle and not idle. */ typedef void (*OnTCPSendIdleChangedFunct)(TCPEndPoint *endPoint, bool isIdle); /** The event handling function delegate of the endpoint signaling when the * idleness of the TCP connection's send channel changes. This is utilized * by upper layers to take appropriate actions based on whether sent data * has been reliably delivered to the peer. */ OnTCPSendIdleChangedFunct OnTCPSendIdleChanged; #endif // INET_CONFIG_ENABLE_TCP_SEND_IDLE_CALLBACKS private: static Weave::System::ObjectPool<TCPEndPoint, INET_CONFIG_NUM_TCP_ENDPOINTS> sPool; Weave::System::PacketBuffer *mRcvQueue; Weave::System::PacketBuffer *mSendQueue; #if INET_TCP_IDLE_CHECK_INTERVAL > 0 uint16_t mIdleTimeout; // in units of INET_TCP_IDLE_CHECK_INTERVAL; zero means no timeout uint16_t mRemainingIdleTime; // in units of INET_TCP_IDLE_CHECK_INTERVAL #endif // INET_TCP_IDLE_CHECK_INTERVAL > 0 uint32_t mConnectTimeoutMsecs; // This is the timeout to wait for a Connect call to succeed or // return an error; zero means use system defaults. #if INET_CONFIG_OVERRIDE_SYSTEM_TCP_USER_TIMEOUT uint32_t mUserTimeoutMillis; // The configured TCP user timeout value in milliseconds. // If 0, assume not set. #if INET_CONFIG_ENABLE_TCP_SEND_IDLE_CALLBACKS bool mIsTCPSendIdle; // Indicates whether the send channel of the TCPEndPoint is Idle. uint16_t mTCPSendQueueRemainingPollCount; // The current remaining number of TCP SendQueue polls before // the TCP User timeout period is reached. uint32_t mTCPSendQueuePollPeriodMillis; // The configured period of active polling of the TCP // SendQueue. If 0, assume not set. void SetTCPSendIdleAndNotifyChange(bool aIsSendIdle); #endif // INET_CONFIG_ENABLE_TCP_SEND_IDLE_CALLBACKS bool mUserTimeoutTimerRunning; // Indicates whether the TCP UserTimeout timer has been started. static void TCPUserTimeoutHandler(Weave::System::Layer* aSystemLayer, void* aAppState, Weave::System::Error aError); void StartTCPUserTimeoutTimer(void); void StopTCPUserTimeoutTimer(void); void RestartTCPUserTimeoutTimer(void); void ScheduleNextTCPUserTimeoutPoll(uint32_t aTimeOut); #if INET_CONFIG_ENABLE_TCP_SEND_IDLE_CALLBACKS uint16_t MaxTCPSendQueuePolls(void); #endif // INET_CONFIG_ENABLE_TCP_SEND_IDLE_CALLBACKS #if WEAVE_SYSTEM_CONFIG_USE_SOCKETS uint32_t mBytesWrittenSinceLastProbe; // This counts the number of bytes written on the TCP socket since the // last probe into the TCP outqueue was made. uint32_t mLastTCPKernelSendQueueLen; // This is the measured size(in bytes) of the kernel TCP send queue // at the end of the last user timeout window. INET_ERROR CheckConnectionProgress(bool &IsProgressing); #endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS #endif // INET_CONFIG_OVERRIDE_SYSTEM_TCP_USER_TIMEOUT TCPEndPoint(void); // not defined TCPEndPoint(const TCPEndPoint&); // not defined ~TCPEndPoint(void); // not defined void Init(InetLayer *inetLayer); INET_ERROR DriveSending(void); void DriveReceiving(void); void HandleConnectComplete(INET_ERROR err); void HandleAcceptError(INET_ERROR err); INET_ERROR DoClose(INET_ERROR err, bool suppressCallback); static bool IsConnected(int state); static void TCPConnectTimeoutHandler(Weave::System::Layer* aSystemLayer, void* aAppState, Weave::System::Error aError); void StartConnectTimerIfSet(void); void StopConnectTimer(void); #if WEAVE_SYSTEM_CONFIG_USE_LWIP struct BufferOffset { const Weave::System::PacketBuffer *buffer; uint32_t offset; }; uint32_t mUnackedLength; // Amount sent but awaiting ACK. Used as a form of reference count // to hang-on to backing packet buffers until they are no longer needed. uint32_t RemainingToSend(); BufferOffset FindStartOfUnsent(); INET_ERROR GetPCB(IPAddressType addrType); void HandleDataSent(uint16_t len); void HandleDataReceived(Weave::System::PacketBuffer *buf); void HandleIncomingConnection(TCPEndPoint *pcb); void HandleError(INET_ERROR err); static err_t LwIPHandleConnectComplete(void *arg, struct tcp_pcb *tpcb, err_t lwipErr); static err_t LwIPHandleIncomingConnection(void *arg, struct tcp_pcb *tcpConPCB, err_t lwipErr); static err_t LwIPHandleDataReceived(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err); static err_t LwIPHandleDataSent(void *arg, struct tcp_pcb *tpcb, u16_t len); static void LwIPHandleError(void *arg, err_t err); #endif // WEAVE_SYSTEM_CONFIG_USE_LWIP #if WEAVE_SYSTEM_CONFIG_USE_SOCKETS INET_ERROR GetSocket(IPAddressType addrType); SocketEvents PrepareIO(void); void HandlePendingIO(void); void ReceiveData(void); void HandleIncomingConnection(void); INET_ERROR BindSrcAddrFromIntf(IPAddressType addrType, InterfaceId intf); #endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS }; #if INET_CONFIG_ENABLE_TCP_SEND_IDLE_CALLBACKS && INET_CONFIG_OVERRIDE_SYSTEM_TCP_USER_TIMEOUT inline uint16_t TCPEndPoint::MaxTCPSendQueuePolls(void) { // If the UserTimeout is configured less than or equal to the poll interval, // return 1 to poll at least once instead of returning zero and timing out // immediately. return (mUserTimeoutMillis > mTCPSendQueuePollPeriodMillis) ? (mUserTimeoutMillis / mTCPSendQueuePollPeriodMillis) : 1; } #endif // INET_CONFIG_ENABLE_TCP_SEND_IDLE_CALLBACKS && INET_CONFIG_OVERRIDE_SYSTEM_TCP_USER_TIMEOUT inline bool TCPEndPoint::IsConnected(void) const { return IsConnected(State); } inline uint16_t TCPEndPoint::LogId(void) { return static_cast<uint16_t>(reinterpret_cast<intptr_t>(this)); } inline void TCPEndPoint::MarkActive(void) { #if INET_TCP_IDLE_CHECK_INTERVAL > 0 mRemainingIdleTime = mIdleTimeout; #endif // INET_TCP_IDLE_CHECK_INTERVAL > 0 } } // namespace Inet } // namespace nl #endif // !defined(TCPENDPOINT_H)
Java
/* * Copyright 2010-2011 Nabeel Mukhtar * * 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.code.linkedinapi.schema.impl; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import com.google.code.linkedinapi.schema.Adapter1; import com.google.code.linkedinapi.schema.DateOfBirth; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "year", "month", "day" }) @XmlRootElement(name = "date-of-birth") public class DateOfBirthImpl implements Serializable, DateOfBirth { private final static long serialVersionUID = 2461660169443089969L; @XmlElement(required = true, type = String.class) @XmlJavaTypeAdapter(Adapter1 .class) protected Long year; @XmlElement(required = true, type = String.class) @XmlJavaTypeAdapter(Adapter1 .class) protected Long month; @XmlElement(required = true, type = String.class) @XmlJavaTypeAdapter(Adapter1 .class) protected Long day; public Long getYear() { return year; } public void setYear(Long value) { this.year = value; } public Long getMonth() { return month; } public void setMonth(Long value) { this.month = value; } public Long getDay() { return day; } public void setDay(Long value) { this.day = value; } }
Java
package excelcom.api; import com.sun.jna.platform.win32.COM.COMException; import com.sun.jna.platform.win32.COM.COMLateBindingObject; import com.sun.jna.platform.win32.COM.IDispatch; import com.sun.jna.platform.win32.OaIdl; import com.sun.jna.platform.win32.OleAuto; import com.sun.jna.platform.win32.Variant; import static com.sun.jna.platform.win32.Variant.VT_NULL; /** * Represents a Range */ class Range extends COMLateBindingObject { Range(IDispatch iDispatch) throws COMException { super(iDispatch); } Variant.VARIANT getValue() { return this.invoke("Value"); } int getRow() { return this.invoke("Row").intValue(); } int getColumn() { return this.invoke("Column").intValue(); } void setInteriorColor(ExcelColor color) { new CellPane(this.getAutomationProperty("Interior", this)).setColorIndex(color); } ExcelColor getInteriorColor() { return ExcelColor.getColor(new CellPane(this.getAutomationProperty("Interior", this)).getColorIndex()); } void setFontColor(ExcelColor color) { new CellPane(this.getAutomationProperty("Font", this)).setColorIndex(color); } ExcelColor getFontColor() { return ExcelColor.getColor(new CellPane(this.getAutomationProperty("Font", this)).getColorIndex()); } void setBorderColor(ExcelColor color) { new CellPane(this.getAutomationProperty("Borders", this)).setColorIndex(color); } ExcelColor getBorderColor() { return ExcelColor.getColor(new CellPane(this.getAutomationProperty("Borders", this)).getColorIndex()); } void setComment(String comment) { this.invokeNoReply("ClearComments"); this.invoke("AddComment", new Variant.VARIANT(comment)); } String getComment() { return new COMLateBindingObject(this.getAutomationProperty("Comment")) { private String getText() { return this.invoke("Text").stringValue(); } }.getText(); } FindResult find(Variant.VARIANT[] options) { IDispatch find = (IDispatch) this.invoke("Find", options).getValue(); if (find == null) { return null; } return new FindResult(find, this); } FindResult findNext(FindResult previous) { return new FindResult(this.getAutomationProperty("FindNext", this, previous.toVariant()), this); } /** * Can be Interior, Border or Font. Has methods for setting e.g. Color. */ private class CellPane extends COMLateBindingObject { CellPane(IDispatch iDispatch) { super(iDispatch); } void setColorIndex(ExcelColor color) { this.setProperty("ColorIndex", color.getIndex()); } int getColorIndex() { Variant.VARIANT colorIndex = this.invoke("ColorIndex"); if(colorIndex.getVarType().intValue() == VT_NULL) { throw new NullPointerException("return type of colorindex is null. Maybe multiple colors in range?"); } return this.invoke("ColorIndex").intValue(); } } }
Java
$packageName = 'kvrt' $url = 'http://devbuilds.kaspersky-labs.com/devbuilds/KVRT/latest/full/KVRT.exe' $checksum = '71ea93798110a5e6551208d4dccee5dc84204615' $checksumType = 'sha1' $toolsPath = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" $installFile = Join-Path $toolsPath "kvrt.exe" try { Get-ChocolateyWebFile -PackageName "$packageName" ` -FileFullPath "$installFile" ` -Url "$url" ` -Checksum "$checksum" ` -ChecksumType "$checksumType" # create empty sidecars so shimgen only creates one shim Set-Content -Path ("$installFile.ignore") ` -Value $null # create batch to start executable $batchStart = Join-Path $toolsPath "kvrt.bat" 'start %~dp0\kvrt.exe -accepteula' | Out-File -FilePath $batchStart -Encoding ASCII Install-BinFile "kvrt" "$batchStart" } catch { throw $_.Exception }
Java
/* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigtable.hbase; import static com.google.cloud.bigtable.hbase.test_env.SharedTestEnvRule.COLUMN_FAMILY; import java.io.IOException; import java.util.List; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HRegionLocation; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.RegionInfo; import org.junit.Assert; import org.junit.Test; @SuppressWarnings("deprecation") public class TestCreateTable extends AbstractTestCreateTable { @Override protected void createTable(TableName tableName) throws IOException { getConnection().getAdmin().createTable(createDescriptor(tableName)); } @Override protected void createTable(TableName tableName, byte[] start, byte[] end, int splitCount) throws IOException { getConnection().getAdmin().createTable(createDescriptor(tableName), start, end, splitCount); } @Override protected void createTable(TableName tableName, byte[][] ranges) throws IOException { getConnection().getAdmin().createTable(createDescriptor(tableName), ranges); } private HTableDescriptor createDescriptor(TableName tableName) { return new HTableDescriptor(tableName).addFamily(new HColumnDescriptor(COLUMN_FAMILY)); } @Override protected List<HRegionLocation> getRegions(TableName tableName) throws Exception { return getConnection().getRegionLocator(tableName).getAllRegionLocations(); } @Test public void testGetRegions() throws Exception { TableName tableName = sharedTestEnv.newTestTableName(); getConnection().getAdmin().createTable(createDescriptor(tableName)); List<RegionInfo> regions = getConnection().getAdmin().getRegions(tableName); Assert.assertEquals(1, regions.size()); } @Override protected boolean asyncGetRegions(TableName tableName) throws Exception { return getConnection().getAdmin().getRegions(tableName).size() == 1 ? true : false; } @Override protected boolean isTableEnabled(TableName tableName) throws Exception { return getConnection().getAdmin().isTableEnabled(tableName); } @Override protected void disableTable(TableName tableName) throws Exception { getConnection().getAdmin().disableTable(tableName); } @Override protected void adminDeleteTable(TableName tableName) throws Exception { getConnection().getAdmin().deleteTable(tableName); } @Override protected boolean tableExists(TableName tableName) throws Exception { return getConnection().getAdmin().tableExists(tableName); } }
Java
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="aui-page-header-main" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="test-Test_AbaRouteValidator_16.html">Class Test_AbaRouteValidator_16</a></li> </ol></div> <h1 class="aui-h2-clover"> Test testAbaNumberCheck_36904_bad </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_16.html?line=45760#src-45760" >testAbaNumberCheck_36904_bad</a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:45:47 </td> <td> 0.0 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_36904_bad</th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/exceptions/AbaRouteValidationException.html?id=23167#AbaRouteValidationException" title="AbaRouteValidationException" name="sl-43">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</a> </td> <td> <span class="sortValue">0.5714286</span>57.1% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td> </tr> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/ErrorCodes.html?id=23167#ErrorCodes" title="ErrorCodes" name="sl-42">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</a> </td> <td> <span class="sortValue">0.5714286</span>57.1% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td> </tr> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=23167#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.29411766</span>29.4% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="29.4% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:29.4%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
Java
Administrator Guide {#admin_guide} ==================== # Installation See the [Installation guide](installation.md). # Server Configuration See the [Server Configuration guide](server_configuration.md). # General %Service Configuration Various aspects of how a service is presented to a user such as the display name of the parameters, default values, *etc.* can be adjusted by changing the service's configuration details on the Grassroots server. These are explained in the [Service Configuration guide](service_configuration.md) # Services As well as these general configuration options, each service can have a number of service-specific configuration details that can be set by a server administrator. The services with extra configuration options are listed [below](#specific_services_configuration) # Linking %Services [Linked Services](linked_services.md) are when the output of running a %Service can be used to either fully or partially fill in the parameters of one or more other Services ready to be run by a user. The service-specific details for the linking of Services are listed below. # Specific Services Configuration {#specific_services_configuration} Links for the configuration for the following services are listed below: * [BLAST services](blast_service.md) * [SamTools service](samtools_service.md)
Java
// Copyright 2004, 2005 The Apache Software 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.apache.tapestry.binding; import org.apache.hivemind.Location; import org.apache.tapestry.BindingException; import org.apache.tapestry.IActionListener; import org.apache.tapestry.IComponent; import org.apache.tapestry.IRequestCycle; import org.apache.tapestry.PageRedirectException; import org.apache.tapestry.RedirectException; import org.apache.tapestry.coerce.ValueConverter; import org.apache.tapestry.listener.ListenerMap; /** * Test for {@link org.apache.tapestry.binding.ListenerMethodBinding}. * * @author Howard M. Lewis Ship * @since 4.0 */ public class TestListenerMethodBinding extends BindingTestCase { public void testInvokeListener() { IComponent component = newComponent(); ListenerMap map = newListenerMap(); IActionListener listener = newListener(); Location l = newLocation(); IComponent sourceComponent = newComponent(); IRequestCycle cycle = newCycle(); ValueConverter vc = newValueConverter(); trainGetListener(component, map, listener); listener.actionTriggered(sourceComponent, cycle); replayControls(); ListenerMethodBinding b = new ListenerMethodBinding("param", vc, l, component, "foo"); assertSame(b, b.getObject()); assertSame(component, b.getComponent()); b.actionTriggered(sourceComponent, cycle); verifyControls(); } public void testToString() { IComponent component = newComponent(); Location l = newLocation(); ValueConverter vc = newValueConverter(); trainGetExtendedId(component, "Fred/barney"); replayControls(); ListenerMethodBinding b = new ListenerMethodBinding("param", vc, l, component, "foo"); String toString = b.toString(); String description = toString.substring(toString.indexOf('[') + 1, toString.length() - 1); assertEquals( "param, component=Fred/barney, methodName=foo, location=classpath:/org/apache/tapestry/binding/TestListenerMethodBinding, line 1", description); verifyControls(); } public void testInvokeAndPageRedirect() { IComponent component = newComponent(); ListenerMap map = newListenerMap(); IActionListener listener = newListener(); Location l = newLocation(); ValueConverter vc = newValueConverter(); IComponent sourceComponent = newComponent(); IRequestCycle cycle = newCycle(); trainGetListener(component, map, listener); listener.actionTriggered(sourceComponent, cycle); Throwable t = new PageRedirectException("TargetPage"); setThrowable(listener, t); replayControls(); ListenerMethodBinding b = new ListenerMethodBinding("param", vc, l, component, "foo"); try { b.actionTriggered(sourceComponent, cycle); unreachable(); } catch (PageRedirectException ex) { assertSame(t, ex); } verifyControls(); } public void testInvokeAndRedirect() { IComponent component = newComponent(); ListenerMap map = newListenerMap(); IActionListener listener = newListener(); Location l = newLocation(); ValueConverter vc = newValueConverter(); IComponent sourceComponent = newComponent(); IRequestCycle cycle = newCycle(); trainGetListener(component, map, listener); listener.actionTriggered(sourceComponent, cycle); Throwable t = new RedirectException("http://foo.bar"); setThrowable(listener, t); replayControls(); ListenerMethodBinding b = new ListenerMethodBinding("param", vc, l, component, "foo"); try { b.actionTriggered(sourceComponent, cycle); unreachable(); } catch (RedirectException ex) { assertSame(t, ex); } verifyControls(); } public void testInvokeListenerFailure() { IComponent component = newComponent(); ListenerMap map = newListenerMap(); IActionListener listener = newListener(); Location l = newLocation(); ValueConverter vc = newValueConverter(); IComponent sourceComponent = newComponent(); IRequestCycle cycle = newCycle(); trainGetListener(component, map, listener); listener.actionTriggered(sourceComponent, cycle); Throwable t = new RuntimeException("Failure."); setThrowable(listener, t); trainGetExtendedId(component, "Fred/barney"); replayControls(); ListenerMethodBinding b = new ListenerMethodBinding("param", vc, l, component, "foo"); try { b.actionTriggered(sourceComponent, cycle); unreachable(); } catch (BindingException ex) { assertEquals( "Exception invoking listener method foo of component Fred/barney: Failure.", ex.getMessage()); assertSame(component, ex.getComponent()); assertSame(l, ex.getLocation()); assertSame(b, ex.getBinding()); } verifyControls(); } private void trainGetListener(IComponent component, ListenerMap lm, IActionListener listener) { trainGetListeners(component, lm); trainGetListener(lm, "foo", listener); } protected IRequestCycle newCycle() { return (IRequestCycle) newMock(IRequestCycle.class); } private void trainGetListener(ListenerMap map, String methodName, IActionListener listener) { map.getListener(methodName); setReturnValue(map, listener); } private void trainGetListeners(IComponent component, ListenerMap lm) { component.getListeners(); setReturnValue(component,lm); } private ListenerMap newListenerMap() { return (ListenerMap) newMock(ListenerMap.class); } private IActionListener newListener() { return (IActionListener) newMock(IActionListener.class); } }
Java
/* * 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.lops.compile; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapred.SequenceFileInputFormat; import org.apache.sysml.api.DMLScript; import org.apache.sysml.api.DMLScript.RUNTIME_PLATFORM; import org.apache.sysml.conf.ConfigurationManager; import org.apache.sysml.conf.DMLConfig; import org.apache.sysml.hops.AggBinaryOp; import org.apache.sysml.hops.BinaryOp; import org.apache.sysml.hops.Hop.FileFormatTypes; import org.apache.sysml.hops.HopsException; import org.apache.sysml.hops.OptimizerUtils; import org.apache.sysml.lops.AppendM; import org.apache.sysml.lops.BinaryM; import org.apache.sysml.lops.CombineBinary; import org.apache.sysml.lops.Data; import org.apache.sysml.lops.Data.OperationTypes; import org.apache.sysml.lops.FunctionCallCP; import org.apache.sysml.lops.Lop; import org.apache.sysml.lops.Lop.Type; import org.apache.sysml.lops.LopProperties.ExecLocation; import org.apache.sysml.lops.LopProperties.ExecType; import org.apache.sysml.lops.LopsException; import org.apache.sysml.lops.MapMult; import org.apache.sysml.lops.OutputParameters; import org.apache.sysml.lops.OutputParameters.Format; import org.apache.sysml.lops.PMMJ; import org.apache.sysml.lops.ParameterizedBuiltin; import org.apache.sysml.lops.PickByCount; import org.apache.sysml.lops.SortKeys; import org.apache.sysml.lops.Unary; import org.apache.sysml.parser.DataExpression; import org.apache.sysml.parser.Expression; import org.apache.sysml.parser.Expression.DataType; import org.apache.sysml.parser.ParameterizedBuiltinFunctionExpression; import org.apache.sysml.parser.StatementBlock; import org.apache.sysml.runtime.DMLRuntimeException; import org.apache.sysml.runtime.controlprogram.parfor.ProgramConverter; import org.apache.sysml.runtime.controlprogram.parfor.util.IDSequence; import org.apache.sysml.runtime.instructions.CPInstructionParser; import org.apache.sysml.runtime.instructions.Instruction; import org.apache.sysml.runtime.instructions.Instruction.INSTRUCTION_TYPE; import org.apache.sysml.runtime.instructions.InstructionParser; import org.apache.sysml.runtime.instructions.MRJobInstruction; import org.apache.sysml.runtime.instructions.SPInstructionParser; import org.apache.sysml.runtime.instructions.cp.CPInstruction; import org.apache.sysml.runtime.instructions.cp.CPInstruction.CPINSTRUCTION_TYPE; import org.apache.sysml.runtime.instructions.cp.VariableCPInstruction; import org.apache.sysml.runtime.matrix.MatrixCharacteristics; import org.apache.sysml.runtime.matrix.data.InputInfo; import org.apache.sysml.runtime.matrix.data.OutputInfo; import org.apache.sysml.runtime.matrix.sort.PickFromCompactInputFormat; /** * * Class to maintain a DAG of lops and compile it into * runtime instructions, incl piggybacking into jobs. * * @param <N> the class parameter has no affect and is * only kept for documentation purposes. */ public class Dag<N extends Lop> { private static final Log LOG = LogFactory.getLog(Dag.class.getName()); private static final int CHILD_BREAKS_ALIGNMENT = 2; private static final int CHILD_DOES_NOT_BREAK_ALIGNMENT = 1; private static final int MRCHILD_NOT_FOUND = 0; private static final int MR_CHILD_FOUND_BREAKS_ALIGNMENT = 4; private static final int MR_CHILD_FOUND_DOES_NOT_BREAK_ALIGNMENT = 5; private static IDSequence job_id = null; private static IDSequence var_index = null; private int total_reducers = -1; private String scratch = ""; private String scratchFilePath = null; private double gmrMapperFootprint = 0; static { job_id = new IDSequence(); var_index = new IDSequence(); } // hash set for all nodes in dag private ArrayList<Lop> nodes = null; /* * Hashmap to translates the nodes in the DAG to a sequence of numbers * key: Lop ID * value: Sequence Number (0 ... |DAG|) * * This map is primarily used in performing DFS on the DAG, and subsequently in performing ancestor-descendant checks. */ private HashMap<Long, Integer> IDMap = null; private static class NodeOutput { String fileName; String varName; OutputInfo outInfo; ArrayList<Instruction> preInstructions; // instructions added before a MR instruction ArrayList<Instruction> postInstructions; // instructions added after a MR instruction ArrayList<Instruction> lastInstructions; NodeOutput() { fileName = null; varName = null; outInfo = null; preInstructions = new ArrayList<Instruction>(); postInstructions = new ArrayList<Instruction>(); lastInstructions = new ArrayList<Instruction>(); } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getVarName() { return varName; } public void setVarName(String varName) { this.varName = varName; } public OutputInfo getOutInfo() { return outInfo; } public void setOutInfo(OutputInfo outInfo) { this.outInfo = outInfo; } public ArrayList<Instruction> getPreInstructions() { return preInstructions; } public void addPreInstruction(Instruction inst) { preInstructions.add(inst); } public ArrayList<Instruction> getPostInstructions() { return postInstructions; } public void addPostInstruction(Instruction inst) { postInstructions.add(inst); } public ArrayList<Instruction> getLastInstructions() { return lastInstructions; } public void addLastInstruction(Instruction inst) { lastInstructions.add(inst); } } public Dag() { //allocate internal data structures nodes = new ArrayList<Lop>(); IDMap = new HashMap<Long, Integer>(); // get number of reducers from dml config total_reducers = ConfigurationManager.getNumReducers(); } /////// // filename handling private String getFilePath() { if ( scratchFilePath == null ) { scratchFilePath = scratch + Lop.FILE_SEPARATOR + Lop.PROCESS_PREFIX + DMLScript.getUUID() + Lop.FILE_SEPARATOR + Lop.FILE_SEPARATOR + ProgramConverter.CP_ROOT_THREAD_ID + Lop.FILE_SEPARATOR; } return scratchFilePath; } public static String getNextUniqueFilenameSuffix() { return "temp" + job_id.getNextID(); } public String getNextUniqueFilename() { return getFilePath() + getNextUniqueFilenameSuffix(); } public static String getNextUniqueVarname(DataType dt) { return (dt==DataType.MATRIX ? Lop.MATRIX_VAR_NAME_PREFIX : Lop.FRAME_VAR_NAME_PREFIX) + var_index.getNextID(); } /////// // Dag modifications /** * Method to add a node to the DAG. * * @param node low-level operator * @return true if node was not already present, false if not. */ public boolean addNode(Lop node) { if (nodes.contains(node)) return false; nodes.add(node); return true; } /** * Method to compile a dag generically * * @param sb statement block * @param config dml configuration * @return list of instructions * @throws LopsException if LopsException occurs * @throws IOException if IOException occurs * @throws DMLRuntimeException if DMLRuntimeException occurs */ public ArrayList<Instruction> getJobs(StatementBlock sb, DMLConfig config) throws LopsException, IOException, DMLRuntimeException { if (config != null) { total_reducers = config.getIntValue(DMLConfig.NUM_REDUCERS); scratch = config.getTextValue(DMLConfig.SCRATCH_SPACE) + "/"; } // hold all nodes in a vector (needed for ordering) ArrayList<Lop> node_v = new ArrayList<Lop>(); node_v.addAll(nodes); /* * Sort the nodes by topological order. * * 1) All nodes with level i appear prior to the nodes in level i+1. * 2) All nodes within a level are ordered by their ID i.e., in the order * they are created */ doTopologicalSort_strict_order(node_v); // do greedy grouping of operations ArrayList<Instruction> inst = doGreedyGrouping(sb, node_v); return inst; } private static void deleteUpdatedTransientReadVariables(StatementBlock sb, ArrayList<Lop> nodeV, ArrayList<Instruction> inst) throws DMLRuntimeException { if ( sb == null ) return; if( LOG.isTraceEnabled() ) LOG.trace("In delete updated variables"); // CANDIDATE list of variables which could have been updated in this statement block HashMap<String, Lop> labelNodeMapping = new HashMap<String, Lop>(); // ACTUAL list of variables whose value is updated, AND the old value of the variable // is no longer accessible/used. HashSet<String> updatedLabels = new HashSet<String>(); HashMap<String, Lop> updatedLabelsLineNum = new HashMap<String, Lop>(); // first capture all transient read variables for ( Lop node : nodeV ) { if (node.getExecLocation() == ExecLocation.Data && ((Data) node).isTransient() && ((Data) node).getOperationType() == OperationTypes.READ && ((Data) node).getDataType() == DataType.MATRIX) { // "node" is considered as updated ONLY IF the old value is not used any more // So, make sure that this READ node does not feed into any (transient/persistent) WRITE boolean hasWriteParent=false; for(Lop p : node.getOutputs()) { if(p.getExecLocation() == ExecLocation.Data) { // if the "p" is of type Data, then it has to be a WRITE hasWriteParent = true; break; } } if ( !hasWriteParent ) { // node has no parent of type WRITE, so this is a CANDIDATE variable // add it to labelNodeMapping so that it is considered in further processing labelNodeMapping.put(node.getOutputParameters().getLabel(), node); } } } // capture updated transient write variables for ( Lop node : nodeV ) { if (node.getExecLocation() == ExecLocation.Data && ((Data) node).isTransient() && ((Data) node).getOperationType() == OperationTypes.WRITE && ((Data) node).getDataType() == DataType.MATRIX && labelNodeMapping.containsKey(node.getOutputParameters().getLabel()) // check to make sure corresponding (i.e., with the same label/name) transient read is present && !labelNodeMapping.containsValue(node.getInputs().get(0)) // check to avoid cases where transient read feeds into a transient write ) { updatedLabels.add(node.getOutputParameters().getLabel()); updatedLabelsLineNum.put(node.getOutputParameters().getLabel(), node); } } // generate RM instructions Instruction rm_inst = null; for ( String label : updatedLabels ) { rm_inst = VariableCPInstruction.prepareRemoveInstruction(label); rm_inst.setLocation(updatedLabelsLineNum.get(label)); if( LOG.isTraceEnabled() ) LOG.trace(rm_inst.toString()); inst.add(rm_inst); } } private static void generateRemoveInstructions(StatementBlock sb, ArrayList<Instruction> deleteInst) throws DMLRuntimeException { if ( sb == null ) return; if( LOG.isTraceEnabled() ) LOG.trace("In generateRemoveInstructions()"); Instruction inst = null; // RULE 1: if in IN and not in OUT, then there should be an rmvar or rmfilevar inst // (currently required for specific cases of external functions) for (String varName : sb.liveIn().getVariableNames()) { if (!sb.liveOut().containsVariable(varName)) { // DataType dt = in.getVariable(varName).getDataType(); // if( !(dt==DataType.MATRIX || dt==DataType.UNKNOWN) ) // continue; //skip rm instructions for non-matrix objects inst = VariableCPInstruction.prepareRemoveInstruction(varName); inst.setLocation(sb.getEndLine(), sb.getEndLine(), -1, -1); deleteInst.add(inst); if( LOG.isTraceEnabled() ) LOG.trace(" Adding " + inst.toString()); } } // RULE 2: if in KILL and not in IN and not in OUT, then there should be an rmvar or rmfilevar inst // (currently required for specific cases of nested loops) // i.e., local variables which are created within the block, and used entirely within the block /*for (String varName : sb.getKill().getVariableNames()) { if ((!sb.liveIn().containsVariable(varName)) && (!sb.liveOut().containsVariable(varName))) { // DataType dt = // sb.getKill().getVariable(varName).getDataType(); // if( !(dt==DataType.MATRIX || dt==DataType.UNKNOWN) ) // continue; //skip rm instructions for non-matrix objects inst = createCleanupInstruction(varName); deleteInst.add(inst); if (DMLScript.DEBUG) System.out.println("Adding instruction (r2) " + inst.toString()); } }*/ } private static ArrayList<ArrayList<Lop>> createNodeVectors(int size) { ArrayList<ArrayList<Lop>> arr = new ArrayList<ArrayList<Lop>>(); // for each job type, we need to create a vector. // additionally, create another vector for execNodes for (int i = 0; i < size; i++) { arr.add(new ArrayList<Lop>()); } return arr; } private static void clearNodeVectors(ArrayList<ArrayList<Lop>> arr) { for (ArrayList<Lop> tmp : arr) { tmp.clear(); } } private static boolean isCompatible(ArrayList<Lop> nodes, JobType jt, int from, int to) throws LopsException { int base = jt.getBase(); for ( Lop node : nodes ) { if ((node.getCompatibleJobs() & base) == 0) { if( LOG.isTraceEnabled() ) LOG.trace("Not compatible "+ node.toString()); return false; } } return true; } /** * Function that determines if the two input nodes can be executed together * in at least one job. * * @param node1 low-level operator 1 * @param node2 low-level operator 2 * @return true if nodes can be executed together */ private static boolean isCompatible(Lop node1, Lop node2) { return( (node1.getCompatibleJobs() & node2.getCompatibleJobs()) > 0); } /** * Function that checks if the given node executes in the job specified by jt. * * @param node low-level operator * @param jt job type * @return true if node executes in the specified job type */ private static boolean isCompatible(Lop node, JobType jt) { if ( jt == JobType.GMRCELL ) jt = JobType.GMR; return ((node.getCompatibleJobs() & jt.getBase()) > 0); } /* * Add node, and its relevant children to job-specific node vectors. */ private void addNodeByJobType(Lop node, ArrayList<ArrayList<Lop>> arr, ArrayList<Lop> execNodes, boolean eliminate) throws LopsException { if (!eliminate) { // Check if this lop defines a MR job. if ( node.definesMRJob() ) { // find the corresponding JobType JobType jt = JobType.findJobTypeFromLop(node); if ( jt == null ) { throw new LopsException(node.printErrorLocation() + "No matching JobType is found for a the lop type: " + node.getType() + " \n"); } // Add "node" to corresponding job vector if ( jt == JobType.GMR ) { if ( node.hasNonBlockedInputs() ) { int gmrcell_index = JobType.GMRCELL.getId(); arr.get(gmrcell_index).add(node); int from = arr.get(gmrcell_index).size(); addChildren(node, arr.get(gmrcell_index), execNodes); int to = arr.get(gmrcell_index).size(); if (!isCompatible(arr.get(gmrcell_index),JobType.GMR, from, to)) // check against GMR only, not against GMRCELL throw new LopsException(node.printErrorLocation() + "Error during compatibility check \n"); } else { // if "node" (in this case, a group lop) has any inputs from RAND // then add it to RAND job. Otherwise, create a GMR job if (hasChildNode(node, arr.get(JobType.DATAGEN.getId()) )) { arr.get(JobType.DATAGEN.getId()).add(node); // we should NOT call 'addChildren' because appropriate // child nodes would have got added to RAND job already } else { int gmr_index = JobType.GMR.getId(); arr.get(gmr_index).add(node); int from = arr.get(gmr_index).size(); addChildren(node, arr.get(gmr_index), execNodes); int to = arr.get(gmr_index).size(); if (!isCompatible(arr.get(gmr_index),JobType.GMR, from, to)) throw new LopsException(node.printErrorLocation() + "Error during compatibility check \n"); } } } else { int index = jt.getId(); arr.get(index).add(node); int from = arr.get(index).size(); addChildren(node, arr.get(index), execNodes); int to = arr.get(index).size(); // check if all added nodes are compatible with current job if (!isCompatible(arr.get(index), jt, from, to)) { throw new LopsException( "Unexpected error in addNodeByType."); } } return; } } if ( eliminate ) { // Eliminated lops are directly added to GMR queue. // Note that eliminate flag is set only for 'group' lops if ( node.hasNonBlockedInputs() ) arr.get(JobType.GMRCELL.getId()).add(node); else arr.get(JobType.GMR.getId()).add(node); return; } /* * If this lop does not define a job, check if it uses the output of any * specialized job. i.e., if this lop has a child node in any of the * job-specific vector, then add it to the vector. Note: This lop must * be added to ONLY ONE of the job-specific vectors. */ int numAdded = 0; for ( JobType j : JobType.values() ) { if ( j.getId() > 0 && hasDirectChildNode(node, arr.get(j.getId()))) { if (isCompatible(node, j)) { arr.get(j.getId()).add(node); numAdded += 1; } } } if (numAdded > 1) { throw new LopsException("Unexpected error in addNodeByJobType(): A given lop can ONLY be added to a single job vector (numAdded = " + numAdded + ")." ); } } /* * Remove the node from all job-specific node vectors. This method is * invoked from removeNodesForNextIteration(). */ private static void removeNodeByJobType(Lop node, ArrayList<ArrayList<Lop>> arr) { for ( JobType jt : JobType.values()) if ( jt.getId() > 0 ) arr.get(jt.getId()).remove(node); } /** * As some jobs only write one output, all operations in the mapper need to * be redone and cannot be marked as finished. * * @param execNodes list of exec low-level operators * @param jobNodes list of job low-level operators * @param finishedNodes list of finished low-level operators * @throws LopsException if LopsException occurs */ private void handleSingleOutputJobs(ArrayList<Lop> execNodes, ArrayList<ArrayList<Lop>> jobNodes, ArrayList<Lop> finishedNodes) throws LopsException { /* * If the input of a MMCJ/MMRJ job (must have executed in a Mapper) is used * by multiple lops then we should mark it as not-finished. */ ArrayList<Lop> nodesWithUnfinishedOutputs = new ArrayList<Lop>(); int[] jobIndices = {JobType.MMCJ.getId()}; Lop.Type[] lopTypes = { Lop.Type.MMCJ}; // TODO: SortByValue should be treated similar to MMCJ, since it can // only sort one file now for ( int jobi=0; jobi < jobIndices.length; jobi++ ) { int jindex = jobIndices[jobi]; if (!jobNodes.get(jindex).isEmpty()) { ArrayList<Lop> vec = jobNodes.get(jindex); // first find all nodes with more than one parent that is not finished. for (int i = 0; i < vec.size(); i++) { Lop node = vec.get(i); if (node.getExecLocation() == ExecLocation.MapOrReduce || node.getExecLocation() == ExecLocation.Map) { Lop MRparent = getParentNode(node, execNodes, ExecLocation.MapAndReduce); if ( MRparent != null && MRparent.getType() == lopTypes[jobi]) { int numParents = node.getOutputs().size(); if (numParents > 1) { for (int j = 0; j < numParents; j++) { if (!finishedNodes.contains(node.getOutputs() .get(j))) nodesWithUnfinishedOutputs.add(node); } } } } } // need to redo all nodes in nodesWithOutput as well as their children for ( Lop node : vec ) { if (node.getExecLocation() == ExecLocation.MapOrReduce || node.getExecLocation() == ExecLocation.Map) { if (nodesWithUnfinishedOutputs.contains(node)) finishedNodes.remove(node); if (hasParentNode(node, nodesWithUnfinishedOutputs)) finishedNodes.remove(node); } } } } } /** * Method to check if a lop can be eliminated from checking * * @param node low-level operator * @param execNodes list of exec nodes * @return true if lop can be eliminated */ private static boolean canEliminateLop(Lop node, ArrayList<Lop> execNodes) { // this function can only eliminate "aligner" lops such a group if (!node.isAligner()) return false; // find the child whose execLoc = 'MapAndReduce' int ret = getChildAlignment(node, execNodes, ExecLocation.MapAndReduce); if (ret == CHILD_BREAKS_ALIGNMENT) return false; else if (ret == CHILD_DOES_NOT_BREAK_ALIGNMENT) return true; else if (ret == MRCHILD_NOT_FOUND) return false; else if (ret == MR_CHILD_FOUND_BREAKS_ALIGNMENT) return false; else if (ret == MR_CHILD_FOUND_DOES_NOT_BREAK_ALIGNMENT) return true; else throw new RuntimeException("Should not happen. \n"); } /** * Method to generate createvar instructions, which creates a new entry * in the symbol table. One instruction is generated for every LOP that is * 1) type Data and * 2) persistent and * 3) matrix and * 4) read * * Transient reads needn't be considered here since the previous program * block would already create appropriate entries in the symbol table. * * @param nodes_v list of nodes * @param inst list of instructions * @throws LopsException if LopsException occurs * @throws IOException if IOException occurs */ private static void generateInstructionsForInputVariables(ArrayList<Lop> nodes_v, ArrayList<Instruction> inst) throws LopsException, IOException { for(Lop n : nodes_v) { if (n.getExecLocation() == ExecLocation.Data && !((Data) n).isTransient() && ((Data) n).getOperationType() == OperationTypes.READ && (n.getDataType() == DataType.MATRIX || n.getDataType() == DataType.FRAME) ) { if ( !((Data)n).isLiteral() ) { try { String inst_string = n.getInstructions(); CPInstruction currInstr = CPInstructionParser.parseSingleInstruction(inst_string); currInstr.setLocation(n); inst.add(currInstr); } catch (DMLRuntimeException e) { throw new LopsException(n.printErrorLocation() + "error generating instructions from input variables in Dag -- \n", e); } } } } } /** * Determine whether to send <code>node</code> to MR or to process it in the control program. * It is sent to MR in the following cases: * * 1) if input lop gets processed in MR then <code>node</code> can be piggybacked * * 2) if the exectype of write lop itself is marked MR i.e., memory estimate > memory budget. * * @param node low-level operator * @return true if lop should be sent to MR */ private static boolean sendWriteLopToMR(Lop node) { if ( DMLScript.rtplatform == RUNTIME_PLATFORM.SINGLE_NODE ) return false; Lop in = node.getInputs().get(0); Format nodeFormat = node.getOutputParameters().getFormat(); // Case of a transient read feeding into only one output persistent binaryblock write // Move the temporary file on HDFS to required persistent location, insteadof copying. if ( in.getExecLocation() == ExecLocation.Data && in.getOutputs().size() == 1 && !((Data)node).isTransient() && ((Data)in).isTransient() && ((Data)in).getOutputParameters().isBlocked() && node.getOutputParameters().isBlocked() ) { return false; } //send write lop to MR if (1) it is marked with exec type MR (based on its memory estimate), or //(2) if the input lop is in MR and the write format allows to pack it into the same job (this does //not apply to csv write because MR csvwrite is a separate MR job type) return (node.getExecType() == ExecType.MR || (in.getExecType() == ExecType.MR && nodeFormat != Format.CSV)); } /** * Computes the memory footprint required to execute <code>node</code> in the mapper. * It is used only for those nodes that use inputs from distributed cache. The returned * value is utilized in limiting the number of instructions piggybacked onto a single GMR mapper. * * @param node low-level operator * @return memory footprint */ private static double computeFootprintInMapper(Lop node) { // Memory limits must be checked only for nodes that use distributed cache if ( ! node.usesDistributedCache() ) // default behavior return 0.0; OutputParameters in1dims = node.getInputs().get(0).getOutputParameters(); OutputParameters in2dims = node.getInputs().get(1).getOutputParameters(); double footprint = 0; if ( node instanceof MapMult ) { int dcInputIndex = node.distributedCacheInputIndex()[0]; footprint = AggBinaryOp.getMapmmMemEstimate( in1dims.getNumRows(), in1dims.getNumCols(), in1dims.getRowsInBlock(), in1dims.getColsInBlock(), in1dims.getNnz(), in2dims.getNumRows(), in2dims.getNumCols(), in2dims.getRowsInBlock(), in2dims.getColsInBlock(), in2dims.getNnz(), dcInputIndex, false); } else if ( node instanceof PMMJ ) { int dcInputIndex = node.distributedCacheInputIndex()[0]; footprint = AggBinaryOp.getMapmmMemEstimate( in1dims.getNumRows(), 1, in1dims.getRowsInBlock(), in1dims.getColsInBlock(), in1dims.getNnz(), in2dims.getNumRows(), in2dims.getNumCols(), in2dims.getRowsInBlock(), in2dims.getColsInBlock(), in2dims.getNnz(), dcInputIndex, true); } else if ( node instanceof AppendM ) { footprint = BinaryOp.footprintInMapper( in1dims.getNumRows(), in1dims.getNumCols(), in2dims.getNumRows(), in2dims.getNumCols(), in1dims.getRowsInBlock(), in1dims.getColsInBlock()); } else if ( node instanceof BinaryM ) { footprint = BinaryOp.footprintInMapper( in1dims.getNumRows(), in1dims.getNumCols(), in2dims.getNumRows(), in2dims.getNumCols(), in1dims.getRowsInBlock(), in1dims.getColsInBlock()); } else { // default behavior return 0.0; } return footprint; } /** * Determines if <code>node</code> can be executed in current round of MR jobs or if it needs to be queued for later rounds. * If the total estimated footprint (<code>node</code> and previously added nodes in GMR) is less than available memory on * the mappers then <code>node</code> can be executed in current round, and <code>true</code> is returned. Otherwise, * <code>node</code> must be queued and <code>false</code> is returned. * * @param node low-level operator * @param footprintInMapper mapper footprint * @return true if node can be executed in current round of jobs */ private static boolean checkMemoryLimits(Lop node, double footprintInMapper) { boolean addNode = true; // Memory limits must be checked only for nodes that use distributed cache if ( ! node.usesDistributedCache() ) // default behavior return addNode; double memBudget = Math.min(AggBinaryOp.MAPMULT_MEM_MULTIPLIER, BinaryOp.APPEND_MEM_MULTIPLIER) * OptimizerUtils.getRemoteMemBudgetMap(true); if ( footprintInMapper <= memBudget ) return addNode; else return !addNode; } /** * Method to group a vector of sorted lops. * * @param sb statement block * @param node_v list of low-level operators * @return list of instructions * @throws LopsException if LopsException occurs * @throws IOException if IOException occurs * @throws DMLRuntimeException if DMLRuntimeException occurs */ private ArrayList<Instruction> doGreedyGrouping(StatementBlock sb, ArrayList<Lop> node_v) throws LopsException, IOException, DMLRuntimeException { if( LOG.isTraceEnabled() ) LOG.trace("Grouping DAG ============"); // nodes to be executed in current iteration ArrayList<Lop> execNodes = new ArrayList<Lop>(); // nodes that have already been processed ArrayList<Lop> finishedNodes = new ArrayList<Lop>(); // nodes that are queued for the following iteration ArrayList<Lop> queuedNodes = new ArrayList<Lop>(); ArrayList<ArrayList<Lop>> jobNodes = createNodeVectors(JobType.getNumJobTypes()); // list of instructions ArrayList<Instruction> inst = new ArrayList<Instruction>(); //ArrayList<Instruction> preWriteDeleteInst = new ArrayList<Instruction>(); ArrayList<Instruction> writeInst = new ArrayList<Instruction>(); ArrayList<Instruction> deleteInst = new ArrayList<Instruction>(); ArrayList<Instruction> endOfBlockInst = new ArrayList<Instruction>(); // remove files for transient reads that are updated. deleteUpdatedTransientReadVariables(sb, node_v, writeInst); generateRemoveInstructions(sb, endOfBlockInst); generateInstructionsForInputVariables(node_v, inst); boolean done = false; String indent = " "; while (!done) { if( LOG.isTraceEnabled() ) LOG.trace("Grouping nodes in DAG"); execNodes.clear(); queuedNodes.clear(); clearNodeVectors(jobNodes); gmrMapperFootprint=0; for ( Lop node : node_v ) { // finished nodes don't need to be processed if (finishedNodes.contains(node)) continue; if( LOG.isTraceEnabled() ) LOG.trace("Processing node (" + node.getID() + ") " + node.toString() + " exec nodes size is " + execNodes.size()); //if node defines MR job, make sure it is compatible with all //its children nodes in execNodes if(node.definesMRJob() && !compatibleWithChildrenInExecNodes(execNodes, node)) { if( LOG.isTraceEnabled() ) LOG.trace(indent + "Queueing node " + node.toString() + " (code 1)"); queuedNodes.add(node); removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); continue; } // if child is queued, this node will be processed in the later // iteration if (hasChildNode(node,queuedNodes)) { if( LOG.isTraceEnabled() ) LOG.trace(indent + "Queueing node " + node.toString() + " (code 2)"); queuedNodes.add(node); // if node has more than two inputs, // remove children that will be needed in a future // iterations // may also have to remove parent nodes of these children removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); continue; } // if inputs come from different jobs, then queue if ( node.getInputs().size() >= 2) { int jobid = Integer.MIN_VALUE; boolean queueit = false; for(int idx=0; idx < node.getInputs().size(); idx++) { int input_jobid = jobType(node.getInputs().get(idx), jobNodes); if (input_jobid != -1) { if ( jobid == Integer.MIN_VALUE ) jobid = input_jobid; else if ( jobid != input_jobid ) { queueit = true; break; } } } if ( queueit ) { if( LOG.isTraceEnabled() ) LOG.trace(indent + "Queueing node " + node.toString() + " (code 3)"); queuedNodes.add(node); removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); continue; } } // See if this lop can be eliminated // This check is for "aligner" lops (e.g., group) boolean eliminate = false; eliminate = canEliminateLop(node, execNodes); if (eliminate) { if( LOG.isTraceEnabled() ) LOG.trace(indent + "Adding -"+ node.toString()); execNodes.add(node); finishedNodes.add(node); addNodeByJobType(node, jobNodes, execNodes, eliminate); continue; } // If the node defines a MR Job then make sure none of its // children that defines a MR Job are present in execNodes if (node.definesMRJob()) { if (hasMRJobChildNode(node, execNodes)) { // "node" must NOT be queued when node=group and the child that defines job is Rand // this is because "group" can be pushed into the "Rand" job. if (! (node.getType() == Lop.Type.Grouping && checkDataGenAsChildNode(node,execNodes)) ) { if( LOG.isTraceEnabled() ) LOG.trace(indent + "Queueing node " + node.toString() + " (code 4)"); queuedNodes.add(node); removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); continue; } } } // if "node" has more than one input, and has a descendant lop // in execNodes that is of type RecordReader // then all its inputs must be ancestors of RecordReader. If // not, queue "node" if (node.getInputs().size() > 1 && hasChildNode(node, execNodes, ExecLocation.RecordReader)) { // get the actual RecordReader lop Lop rr_node = getChildNode(node, execNodes, ExecLocation.RecordReader); // all inputs of "node" must be ancestors of rr_node boolean queue_it = false; for (Lop n : node.getInputs()) { // each input should be ancestor of RecordReader lop if (!n.equals(rr_node) && !isChild(rr_node, n, IDMap)) { queue_it = true; // i.e., "node" must be queued break; } } if (queue_it) { // queue node if( LOG.isTraceEnabled() ) LOG.trace(indent + "Queueing -" + node.toString() + " (code 5)"); queuedNodes.add(node); // TODO: does this have to be modified to handle // recordreader lops? removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); continue; } else { // nothing here.. subsequent checks have to be performed // on "node" ; } } // data node, always add if child not queued // only write nodes are kept in execnodes if (node.getExecLocation() == ExecLocation.Data) { Data dnode = (Data) node; boolean dnode_queued = false; if ( dnode.getOperationType() == OperationTypes.READ ) { if( LOG.isTraceEnabled() ) LOG.trace(indent + "Adding Data -"+ node.toString()); // TODO: avoid readScalar instruction, and read it on-demand just like the way Matrices are read in control program if ( node.getDataType() == DataType.SCALAR //TODO: LEO check the following condition is still needed && node.getOutputParameters().getFile_name() != null ) { // this lop corresponds to reading a scalar from HDFS file // add it to execNodes so that "readScalar" instruction gets generated execNodes.add(node); // note: no need to add it to any job vector } } else if (dnode.getOperationType() == OperationTypes.WRITE) { // Skip the transient write <code>node</code> if the input is a // transient read with the same variable name. i.e., a dummy copy. // Hence, <code>node</code> can be avoided. // TODO: this case should ideally be handled in the language layer // prior to the construction of Hops Dag Lop input = dnode.getInputs().get(0); if ( dnode.isTransient() && input.getExecLocation() == ExecLocation.Data && ((Data)input).isTransient() && dnode.getOutputParameters().getLabel().equals(input.getOutputParameters().getLabel()) ) { // do nothing, <code>node</code> must not processed any further. ; } else if ( execNodes.contains(input) && !isCompatible(node, input) && sendWriteLopToMR(node)) { // input is in execNodes but it is not compatible with write lop. So, queue the write lop. if( LOG.isTraceEnabled() ) LOG.trace(indent + "Queueing -" + node.toString()); queuedNodes.add(node); dnode_queued = true; } else { if( LOG.isTraceEnabled() ) LOG.trace(indent + "Adding Data -"+ node.toString()); execNodes.add(node); if ( sendWriteLopToMR(node) ) { addNodeByJobType(node, jobNodes, execNodes, false); } } } if (!dnode_queued) finishedNodes.add(node); continue; } // map or reduce node, can always be piggybacked with parent if (node.getExecLocation() == ExecLocation.MapOrReduce) { if( LOG.isTraceEnabled() ) LOG.trace(indent + "Adding -"+ node.toString()); execNodes.add(node); finishedNodes.add(node); addNodeByJobType(node, jobNodes, execNodes, false); continue; } // RecordReader node, add, if no parent needs reduce, else queue if (node.getExecLocation() == ExecLocation.RecordReader) { // "node" should not have any children in // execNodes .. it has to be the first one in the job! if (!hasChildNode(node, execNodes, ExecLocation.Map) && !hasChildNode(node, execNodes, ExecLocation.MapAndReduce)) { if( LOG.isTraceEnabled() ) LOG.trace(indent + "Adding -"+ node.toString()); execNodes.add(node); finishedNodes.add(node); addNodeByJobType(node, jobNodes, execNodes, false); } else { if( LOG.isTraceEnabled() ) LOG.trace(indent + "Queueing -"+ node.toString() + " (code 6)"); queuedNodes.add(node); removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); } continue; } // map node, add, if no parent needs reduce, else queue if (node.getExecLocation() == ExecLocation.Map) { boolean queueThisNode = false; int subcode = -1; if ( node.usesDistributedCache() ) { // if an input to <code>node</code> comes from distributed cache // then that input must get executed in one of the previous jobs. int[] dcInputIndexes = node.distributedCacheInputIndex(); for( int dcInputIndex : dcInputIndexes ){ Lop dcInput = node.getInputs().get(dcInputIndex-1); if ( (dcInput.getType() != Lop.Type.Data && dcInput.getExecType()==ExecType.MR) && execNodes.contains(dcInput) ) { queueThisNode = true; subcode = 1; } } // Limit the number of distributed cache inputs based on the available memory in mappers double memsize = computeFootprintInMapper(node); //gmrMapperFootprint += computeFootprintInMapper(node); if ( gmrMapperFootprint>0 && !checkMemoryLimits(node, gmrMapperFootprint+memsize ) ) { queueThisNode = true; subcode = 2; } if(!queueThisNode) gmrMapperFootprint += memsize; } if (!queueThisNode && !hasChildNode(node, execNodes,ExecLocation.MapAndReduce)&& !hasMRJobChildNode(node, execNodes)) { if( LOG.isTraceEnabled() ) LOG.trace(indent + "Adding -"+ node.toString()); execNodes.add(node); finishedNodes.add(node); addNodeByJobType(node, jobNodes, execNodes, false); } else { if( LOG.isTraceEnabled() ) LOG.trace(indent + "Queueing -"+ node.toString() + " (code 7 - " + "subcode " + subcode + ")"); queuedNodes.add(node); removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); } continue; } // reduce node, make sure no parent needs reduce, else queue if (node.getExecLocation() == ExecLocation.MapAndReduce) { // TODO: statiko -- keep the middle condition // discuss about having a lop that is MapAndReduce but does // not define a job if( LOG.isTraceEnabled() ) LOG.trace(indent + "Adding -"+ node.toString()); execNodes.add(node); finishedNodes.add(node); addNodeByJobType(node, jobNodes, execNodes, eliminate); continue; } // aligned reduce, make sure a parent that is reduce exists if (node.getExecLocation() == ExecLocation.Reduce) { if ( compatibleWithChildrenInExecNodes(execNodes, node) && (hasChildNode(node, execNodes, ExecLocation.MapAndReduce) || hasChildNode(node, execNodes, ExecLocation.Map) ) ) { if( LOG.isTraceEnabled() ) LOG.trace(indent + "Adding -"+ node.toString()); execNodes.add(node); finishedNodes.add(node); addNodeByJobType(node, jobNodes, execNodes, false); } else { if( LOG.isTraceEnabled() ) LOG.trace(indent + "Queueing -"+ node.toString() + " (code 8)"); queuedNodes.add(node); removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); } continue; } // add Scalar to execNodes if it has no child in exec nodes // that will be executed in a MR job. if (node.getExecLocation() == ExecLocation.ControlProgram) { for ( Lop lop : node.getInputs() ) { if (execNodes.contains(lop) && !(lop.getExecLocation() == ExecLocation.Data) && !(lop.getExecLocation() == ExecLocation.ControlProgram)) { if( LOG.isTraceEnabled() ) LOG.trace(indent + "Queueing -"+ node.toString() + " (code 9)"); queuedNodes.add(node); removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); break; } } if (queuedNodes.contains(node)) continue; if( LOG.isTraceEnabled() ) LOG.trace(indent + "Adding - scalar"+ node.toString()); execNodes.add(node); addNodeByJobType(node, jobNodes, execNodes, false); finishedNodes.add(node); continue; } } // no work to do if ( execNodes.isEmpty() ) { if( !queuedNodes.isEmpty() ) { //System.err.println("Queued nodes should be 0"); throw new LopsException("Queued nodes should not be 0 at this point \n"); } if( LOG.isTraceEnabled() ) LOG.trace("All done! queuedNodes = "+ queuedNodes.size()); done = true; } else { // work to do if( LOG.isTraceEnabled() ) LOG.trace("Generating jobs for group -- Node count="+ execNodes.size()); // first process scalar instructions generateControlProgramJobs(execNodes, inst, writeInst, deleteInst); // copy unassigned lops in execnodes to gmrnodes for (int i = 0; i < execNodes.size(); i++) { Lop node = execNodes.get(i); if (jobType(node, jobNodes) == -1) { if ( isCompatible(node, JobType.GMR) ) { if ( node.hasNonBlockedInputs() ) { jobNodes.get(JobType.GMRCELL.getId()).add(node); addChildren(node, jobNodes.get(JobType.GMRCELL.getId()), execNodes); } else { jobNodes.get(JobType.GMR.getId()).add(node); addChildren(node, jobNodes.get(JobType.GMR.getId()), execNodes); } } else { if( LOG.isTraceEnabled() ) LOG.trace(indent + "Queueing -" + node.toString() + " (code 10)"); execNodes.remove(i); finishedNodes.remove(node); queuedNodes.add(node); removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); } } } // next generate MR instructions if (!execNodes.isEmpty()) generateMRJobs(execNodes, inst, writeInst, deleteInst, jobNodes); handleSingleOutputJobs(execNodes, jobNodes, finishedNodes); } } // add write and delete inst at the very end. //inst.addAll(preWriteDeleteInst); inst.addAll(writeInst); inst.addAll(deleteInst); inst.addAll(endOfBlockInst); return inst; } private boolean compatibleWithChildrenInExecNodes(ArrayList<Lop> execNodes, Lop node) { for( Lop tmpNode : execNodes ) { // for lops that execute in control program, compatibleJobs property is set to LopProperties.INVALID // we should not consider such lops in this check if (isChild(tmpNode, node, IDMap) && tmpNode.getExecLocation() != ExecLocation.ControlProgram //&& tmpNode.getCompatibleJobs() != LopProperties.INVALID && (tmpNode.getCompatibleJobs() & node.getCompatibleJobs()) == 0) return false; } return true; } /** * Exclude rmvar instruction for varname from deleteInst, if exists * * @param varName variable name * @param deleteInst list of instructions */ private static void excludeRemoveInstruction(String varName, ArrayList<Instruction> deleteInst) { //for(Instruction inst : deleteInst) { for(int i=0; i < deleteInst.size(); i++) { Instruction inst = deleteInst.get(i); if ((inst.getType() == INSTRUCTION_TYPE.CONTROL_PROGRAM || inst.getType() == INSTRUCTION_TYPE.SPARK) && ((CPInstruction)inst).getCPInstructionType() == CPINSTRUCTION_TYPE.Variable && ((VariableCPInstruction)inst).isRemoveVariable(varName) ) { deleteInst.remove(i); } } } /** * Generate rmvar instructions for the inputs, if their consumer count becomes zero. * * @param node low-level operator * @param inst list of instructions * @param delteInst list of instructions * @throws DMLRuntimeException if DMLRuntimeException occurs */ private void processConsumersForInputs(Lop node, ArrayList<Instruction> inst, ArrayList<Instruction> delteInst) throws DMLRuntimeException { // reduce the consumer count for all input lops // if the count becomes zero, then then variable associated w/ input can be removed for(Lop in : node.getInputs() ) { if(DMLScript.ENABLE_DEBUG_MODE) { processConsumers(in, inst, delteInst, node); } else { processConsumers(in, inst, delteInst, null); } } } private static void processConsumers(Lop node, ArrayList<Instruction> inst, ArrayList<Instruction> deleteInst, Lop locationInfo) throws DMLRuntimeException { // reduce the consumer count for all input lops // if the count becomes zero, then then variable associated w/ input can be removed if ( node.removeConsumer() == 0 ) { if ( node.getExecLocation() == ExecLocation.Data && ((Data)node).isLiteral() ) { return; } String label = node.getOutputParameters().getLabel(); Instruction currInstr = VariableCPInstruction.prepareRemoveInstruction(label); if (locationInfo != null) currInstr.setLocation(locationInfo); else currInstr.setLocation(node); inst.add(currInstr); excludeRemoveInstruction(label, deleteInst); } } /** * Method to generate instructions that are executed in Control Program. At * this point, this DAG has no dependencies on the MR dag. ie. none of the * inputs are outputs of MR jobs * * @param execNodes list of low-level operators * @param inst list of instructions * @param writeInst list of write instructions * @param deleteInst list of delete instructions * @throws LopsException if LopsException occurs * @throws DMLRuntimeException if DMLRuntimeException occurs */ private void generateControlProgramJobs(ArrayList<Lop> execNodes, ArrayList<Instruction> inst, ArrayList<Instruction> writeInst, ArrayList<Instruction> deleteInst) throws LopsException, DMLRuntimeException { // nodes to be deleted from execnodes ArrayList<Lop> markedNodes = new ArrayList<Lop>(); // variable names to be deleted ArrayList<String> var_deletions = new ArrayList<String>(); HashMap<String, Lop> var_deletionsLineNum = new HashMap<String, Lop>(); boolean doRmVar = false; for (int i = 0; i < execNodes.size(); i++) { Lop node = execNodes.get(i); doRmVar = false; // mark input scalar read nodes for deletion // TODO: statiko -- check if this condition ever evaluated to TRUE if (node.getExecLocation() == ExecLocation.Data && ((Data) node).getOperationType() == Data.OperationTypes.READ && ((Data) node).getDataType() == DataType.SCALAR && node.getOutputParameters().getFile_name() == null ) { markedNodes.add(node); continue; } // output scalar instructions and mark nodes for deletion if (node.getExecLocation() == ExecLocation.ControlProgram) { if (node.getDataType() == DataType.SCALAR) { // Output from lops with SCALAR data type must // go into Temporary Variables (Var0, Var1, etc.) NodeOutput out = setupNodeOutputs(node, ExecType.CP, false, false); inst.addAll(out.getPreInstructions()); // dummy deleteInst.addAll(out.getLastInstructions()); } else { // Output from lops with non-SCALAR data type must // go into Temporary Files (temp0, temp1, etc.) NodeOutput out = setupNodeOutputs(node, ExecType.CP, false, false); inst.addAll(out.getPreInstructions()); boolean hasTransientWriteParent = false; for ( Lop parent : node.getOutputs() ) { if ( parent.getExecLocation() == ExecLocation.Data && ((Data)parent).getOperationType() == Data.OperationTypes.WRITE && ((Data)parent).isTransient() ) { hasTransientWriteParent = true; break; } } if ( !hasTransientWriteParent ) { deleteInst.addAll(out.getLastInstructions()); } else { var_deletions.add(node.getOutputParameters().getLabel()); var_deletionsLineNum.put(node.getOutputParameters().getLabel(), node); } } String inst_string = ""; // Lops with arbitrary number of inputs (ParameterizedBuiltin, GroupedAggregate, DataGen) // are handled separately, by simply passing ONLY the output variable to getInstructions() if (node.getType() == Lop.Type.ParameterizedBuiltin || node.getType() == Lop.Type.GroupedAgg || node.getType() == Lop.Type.DataGen ){ inst_string = node.getInstructions(node.getOutputParameters().getLabel()); } // Lops with arbitrary number of inputs and outputs are handled // separately as well by passing arrays of inputs and outputs else if ( node.getType() == Lop.Type.FunctionCallCP ) { String[] inputs = new String[node.getInputs().size()]; String[] outputs = new String[node.getOutputs().size()]; int count = 0; for( Lop in : node.getInputs() ) inputs[count++] = in.getOutputParameters().getLabel(); count = 0; for( Lop out : node.getOutputs() ) { outputs[count++] = out.getOutputParameters().getLabel(); } inst_string = node.getInstructions(inputs, outputs); } else if (node.getType() == Lop.Type.MULTIPLE_CP) { // ie, MultipleCP class inst_string = node.getInstructions(node.getOutputParameters().getLabel()); } else { if ( node.getInputs().isEmpty() ) { // currently, such a case exists only for Rand lop inst_string = node.getInstructions(node.getOutputParameters().getLabel()); } else if (node.getInputs().size() == 1) { inst_string = node.getInstructions(node.getInputs() .get(0).getOutputParameters().getLabel(), node.getOutputParameters().getLabel()); } else if (node.getInputs().size() == 2) { inst_string = node.getInstructions( node.getInputs().get(0).getOutputParameters().getLabel(), node.getInputs().get(1).getOutputParameters().getLabel(), node.getOutputParameters().getLabel()); } else if (node.getInputs().size() == 3 || node.getType() == Type.Ternary) { inst_string = node.getInstructions( node.getInputs().get(0).getOutputParameters().getLabel(), node.getInputs().get(1).getOutputParameters().getLabel(), node.getInputs().get(2).getOutputParameters().getLabel(), node.getOutputParameters().getLabel()); } else if (node.getInputs().size() == 4) { inst_string = node.getInstructions( node.getInputs().get(0).getOutputParameters().getLabel(), node.getInputs().get(1).getOutputParameters().getLabel(), node.getInputs().get(2).getOutputParameters().getLabel(), node.getInputs().get(3).getOutputParameters().getLabel(), node.getOutputParameters().getLabel()); } else if (node.getInputs().size() == 5) { inst_string = node.getInstructions( node.getInputs().get(0).getOutputParameters().getLabel(), node.getInputs().get(1).getOutputParameters().getLabel(), node.getInputs().get(2).getOutputParameters().getLabel(), node.getInputs().get(3).getOutputParameters().getLabel(), node.getInputs().get(4).getOutputParameters().getLabel(), node.getOutputParameters().getLabel()); } else if (node.getInputs().size() == 6) { inst_string = node.getInstructions( node.getInputs().get(0).getOutputParameters().getLabel(), node.getInputs().get(1).getOutputParameters().getLabel(), node.getInputs().get(2).getOutputParameters().getLabel(), node.getInputs().get(3).getOutputParameters().getLabel(), node.getInputs().get(4).getOutputParameters().getLabel(), node.getInputs().get(5).getOutputParameters().getLabel(), node.getOutputParameters().getLabel()); } else if (node.getInputs().size() == 7) { inst_string = node.getInstructions( node.getInputs().get(0).getOutputParameters().getLabel(), node.getInputs().get(1).getOutputParameters().getLabel(), node.getInputs().get(2).getOutputParameters().getLabel(), node.getInputs().get(3).getOutputParameters().getLabel(), node.getInputs().get(4).getOutputParameters().getLabel(), node.getInputs().get(5).getOutputParameters().getLabel(), node.getInputs().get(6).getOutputParameters().getLabel(), node.getOutputParameters().getLabel()); } else { String[] inputs = new String[node.getInputs().size()]; for( int j=0; j<node.getInputs().size(); j++ ) inputs[j] = node.getInputs().get(j).getOutputParameters().getLabel(); inst_string = node.getInstructions(inputs, node.getOutputParameters().getLabel()); } } try { if( LOG.isTraceEnabled() ) LOG.trace("Generating instruction - "+ inst_string); Instruction currInstr = InstructionParser.parseSingleInstruction(inst_string); if(currInstr == null) { throw new LopsException("Error parsing the instruction:" + inst_string); } if (node._beginLine != 0) currInstr.setLocation(node); else if ( !node.getOutputs().isEmpty() ) currInstr.setLocation(node.getOutputs().get(0)); else if ( !node.getInputs().isEmpty() ) currInstr.setLocation(node.getInputs().get(0)); inst.add(currInstr); } catch (Exception e) { throw new LopsException(node.printErrorLocation() + "Problem generating simple inst - " + inst_string, e); } markedNodes.add(node); doRmVar = true; //continue; } else if (node.getExecLocation() == ExecLocation.Data ) { Data dnode = (Data)node; Data.OperationTypes op = dnode.getOperationType(); if ( op == Data.OperationTypes.WRITE ) { NodeOutput out = null; if ( sendWriteLopToMR(node) ) { // In this case, Data WRITE lop goes into MR, and // we don't have to do anything here doRmVar = false; } else { out = setupNodeOutputs(node, ExecType.CP, false, false); if ( dnode.getDataType() == DataType.SCALAR ) { // processing is same for both transient and persistent scalar writes writeInst.addAll(out.getLastInstructions()); //inst.addAll(out.getLastInstructions()); doRmVar = false; } else { // setupNodeOutputs() handles both transient and persistent matrix writes if ( dnode.isTransient() ) { //inst.addAll(out.getPreInstructions()); // dummy ? deleteInst.addAll(out.getLastInstructions()); doRmVar = false; } else { // In case of persistent write lop, write instruction will be generated // and that instruction must be added to <code>inst</code> so that it gets // executed immediately. If it is added to <code>deleteInst</code> then it // gets executed at the end of program block's execution inst.addAll(out.getLastInstructions()); doRmVar = true; } } markedNodes.add(node); //continue; } } else { // generate a temp label to hold the value that is read from HDFS if ( node.getDataType() == DataType.SCALAR ) { node.getOutputParameters().setLabel(Lop.SCALAR_VAR_NAME_PREFIX + var_index.getNextID()); String io_inst = node.getInstructions(node.getOutputParameters().getLabel(), node.getOutputParameters().getFile_name()); CPInstruction currInstr = CPInstructionParser.parseSingleInstruction(io_inst); currInstr.setLocation(node); inst.add(currInstr); Instruction tempInstr = VariableCPInstruction.prepareRemoveInstruction(node.getOutputParameters().getLabel()); tempInstr.setLocation(node); deleteInst.add(tempInstr); } else { throw new LopsException("Matrix READs are not handled in CP yet!"); } markedNodes.add(node); doRmVar = true; //continue; } } // see if rmvar instructions can be generated for node's inputs if(doRmVar) processConsumersForInputs(node, inst, deleteInst); doRmVar = false; } for ( String var : var_deletions ) { Instruction rmInst = VariableCPInstruction.prepareRemoveInstruction(var); if( LOG.isTraceEnabled() ) LOG.trace(" Adding var_deletions: " + rmInst.toString()); rmInst.setLocation(var_deletionsLineNum.get(var)); deleteInst.add(rmInst); } // delete all marked nodes for ( Lop node : markedNodes ) { execNodes.remove(node); } } /** * Method to remove all child nodes of a queued node that should be executed * in a following iteration. * * @param node low-level operator * @param finishedNodes list of finished nodes * @param execNodes list of exec nodes * @param queuedNodes list of queued nodes * @param jobvec list of lists of low-level operators * @throws LopsException if LopsException occurs */ private void removeNodesForNextIteration(Lop node, ArrayList<Lop> finishedNodes, ArrayList<Lop> execNodes, ArrayList<Lop> queuedNodes, ArrayList<ArrayList<Lop>> jobvec) throws LopsException { // only queued nodes with multiple inputs need to be handled. if (node.getInputs().size() == 1) return; //if all children are queued, then there is nothing to do. boolean allQueued = true; for( Lop input : node.getInputs() ) { if( !queuedNodes.contains(input) ) { allQueued = false; break; } } if ( allQueued ) return; if( LOG.isTraceEnabled() ) LOG.trace(" Before remove nodes for next iteration -- size of execNodes " + execNodes.size()); // Determine if <code>node</code> has inputs from the same job or multiple jobs int jobid = Integer.MIN_VALUE; boolean inputs_in_same_job = true; for( Lop input : node.getInputs() ) { int input_jobid = jobType(input, jobvec); if ( jobid == Integer.MIN_VALUE ) jobid = input_jobid; else if ( jobid != input_jobid ) { inputs_in_same_job = false; break; } } // Determine if there exist any unassigned inputs to <code>node</code> // Evaluate only those lops that execute in MR. boolean unassigned_inputs = false; for( Lop input : node.getInputs() ) { //if ( input.getExecLocation() != ExecLocation.ControlProgram && jobType(input, jobvec) == -1 ) { if ( input.getExecType() == ExecType.MR && !execNodes.contains(input)) { //jobType(input, jobvec) == -1 ) { unassigned_inputs = true; break; } } // Determine if any node's children are queued boolean child_queued = false; for( Lop input : node.getInputs() ) { if (queuedNodes.contains(input) ) { child_queued = true; break; } } if (LOG.isTraceEnabled()) { LOG.trace(" Property Flags:"); LOG.trace(" Inputs in same job: " + inputs_in_same_job); LOG.trace(" Unassigned inputs: " + unassigned_inputs); LOG.trace(" Child queued: " + child_queued); } // Evaluate each lop in <code>execNodes</code> for removal. // Add lops to be removed to <code>markedNodes</code>. ArrayList<Lop> markedNodes = new ArrayList<Lop>(); for (Lop tmpNode : execNodes ) { if (LOG.isTraceEnabled()) { LOG.trace(" Checking for removal (" + tmpNode.getID() + ") " + tmpNode.toString()); } // if tmpNode is not a descendant of 'node', then there is no advantage in removing tmpNode for later iterations. if(!isChild(tmpNode, node, IDMap)) continue; // handle group input lops if(node.getInputs().contains(tmpNode) && tmpNode.isAligner()) { markedNodes.add(tmpNode); if( LOG.isTraceEnabled() ) LOG.trace(" Removing for next iteration (code 1): (" + tmpNode.getID() + ") " + tmpNode.toString()); } //if (child_queued) { // if one of the children are queued, // remove some child nodes on other leg that may be needed later on. // For e.g. Group lop. if (!hasOtherQueuedParentNode(tmpNode, queuedNodes, node) && branchHasNoOtherUnExecutedParents(tmpNode, node, execNodes, finishedNodes)) { boolean queueit = false; int code = -1; switch(node.getExecLocation()) { case Map: if(branchCanBePiggyBackedMap(tmpNode, node, execNodes, queuedNodes, markedNodes)) queueit = true; code=2; break; case MapAndReduce: if(branchCanBePiggyBackedMapAndReduce(tmpNode, node, execNodes, queuedNodes)&& !tmpNode.definesMRJob()) queueit = true; code=3; break; case Reduce: if(branchCanBePiggyBackedReduce(tmpNode, node, execNodes, queuedNodes)) queueit = true; code=4; break; default: //do nothing } if(queueit) { if( LOG.isTraceEnabled() ) LOG.trace(" Removing for next iteration (code " + code + "): (" + tmpNode.getID() + ") " + tmpNode.toString()); markedNodes.add(tmpNode); } } /* * "node" has no other queued children. * * If inputs are in the same job and "node" is of type * MapAndReduce, then remove nodes of all types other than * Reduce, MapAndReduce, and the ones that define a MR job as * they can be piggybacked later. * * e.g: A=Rand, B=Rand, C=A%*%B Here, both inputs of MMCJ lop * come from Rand job, and they should not be removed. * * Other examples: -- MMCJ whose children are of type * MapAndReduce (say GMR) -- Inputs coming from two different * jobs .. GMR & REBLOCK */ //boolean himr = hasOtherMapAndReduceParentNode(tmpNode, execNodes,node); //boolean bcbp = branchCanBePiggyBackedMapAndReduce(tmpNode, node, execNodes, finishedNodes); //System.out.println(" .. " + inputs_in_same_job + "," + himr + "," + bcbp); if ((inputs_in_same_job || unassigned_inputs) && node.getExecLocation() == ExecLocation.MapAndReduce && !hasOtherMapAndReduceParentNode(tmpNode, execNodes,node) // don't remove since it already piggybacked with a MapReduce node && branchCanBePiggyBackedMapAndReduce(tmpNode, node, execNodes, queuedNodes) && !tmpNode.definesMRJob()) { if( LOG.isTraceEnabled() ) LOG.trace(" Removing for next iteration (code 5): ("+ tmpNode.getID() + ") " + tmpNode.toString()); markedNodes.add(tmpNode); } } // for i // we also need to delete all parent nodes of marked nodes for ( Lop enode : execNodes ) { if( LOG.isTraceEnabled() ) { LOG.trace(" Checking for removal - (" + enode.getID() + ") " + enode.toString()); } if (hasChildNode(enode, markedNodes) && !markedNodes.contains(enode)) { markedNodes.add(enode); if( LOG.isTraceEnabled() ) LOG.trace(" Removing for next iteration (code 6) (" + enode.getID() + ") " + enode.toString()); } } if ( execNodes.size() != markedNodes.size() ) { // delete marked nodes from finishedNodes and execNodes // add to queued nodes for(Lop n : markedNodes) { if ( n.usesDistributedCache() ) gmrMapperFootprint -= computeFootprintInMapper(n); finishedNodes.remove(n); execNodes.remove(n); removeNodeByJobType(n, jobvec); queuedNodes.add(n); } } } private boolean branchCanBePiggyBackedReduce(Lop tmpNode, Lop node, ArrayList<Lop> execNodes, ArrayList<Lop> queuedNodes) { if(node.getExecLocation() != ExecLocation.Reduce) return false; // if tmpNode is descendant of any queued child of node, then branch can not be piggybacked for(Lop ni : node.getInputs()) { if(queuedNodes.contains(ni) && isChild(tmpNode, ni, IDMap)) return false; } for( Lop n : execNodes ) { if(n.equals(node)) continue; if(n.equals(tmpNode) && n.getExecLocation() != ExecLocation.Map && n.getExecLocation() != ExecLocation.MapOrReduce) return false; // check if n is on the branch tmpNode->*->node if(isChild(n, node, IDMap) && isChild(tmpNode, n, IDMap)) { if(!node.getInputs().contains(tmpNode) // redundant && n.getExecLocation() != ExecLocation.Map && n.getExecLocation() != ExecLocation.MapOrReduce) return false; } } return true; } private boolean branchCanBePiggyBackedMap(Lop tmpNode, Lop node, ArrayList<Lop> execNodes, ArrayList<Lop> queuedNodes, ArrayList<Lop> markedNodes) { if(node.getExecLocation() != ExecLocation.Map) return false; // if tmpNode is descendant of any queued child of node, then branch can not be piggybacked for(Lop ni : node.getInputs()) { if(queuedNodes != null && queuedNodes.contains(ni) && isChild(tmpNode, ni, IDMap)) return false; } // since node.location=Map: only Map & MapOrReduce lops must be considered if( tmpNode.definesMRJob() || (tmpNode.getExecLocation() != ExecLocation.Map && tmpNode.getExecLocation() != ExecLocation.MapOrReduce)) return false; // if there exist a node "dcInput" that is // -- a) parent of tmpNode, and b) feeds into "node" via distributed cache // then, tmpNode should not be removed. // "dcInput" must be executed prior to "node", and removal of tmpNode does not make that happen. if(node.usesDistributedCache() ) { for(int dcInputIndex : node.distributedCacheInputIndex()) { Lop dcInput = node.getInputs().get(dcInputIndex-1); if(isChild(tmpNode, dcInput, IDMap)) return false; } } // if tmpNode requires an input from distributed cache, // remove tmpNode only if that input can fit into mappers' memory. If not, if ( tmpNode.usesDistributedCache() ) { double memsize = computeFootprintInMapper(tmpNode); if (node.usesDistributedCache() ) memsize += computeFootprintInMapper(node); if ( markedNodes != null ) { for(Lop n : markedNodes) { if ( n.usesDistributedCache() ) memsize += computeFootprintInMapper(n); } } if ( !checkMemoryLimits(node, memsize ) ) { return false; } } return ( (tmpNode.getCompatibleJobs() & node.getCompatibleJobs()) > 0); } /** * Function that checks if <code>tmpNode</code> can be piggybacked with MapAndReduce * lop <code>node</code>. * * Decision depends on the exec location of <code>tmpNode</code>. If the exec location is: * MapAndReduce: CAN NOT be piggybacked since it defines its own MR job * Reduce: CAN NOT be piggybacked since it must execute before <code>node</code> * Map or MapOrReduce: CAN be piggybacked ONLY IF it is comatible w/ <code>tmpNode</code> * * @param tmpNode temporary low-level operator * @param node low-level operator * @param execNodes list of exec nodes * @param queuedNodes list of queued nodes * @return true if tmpNode can be piggbacked on node */ private boolean branchCanBePiggyBackedMapAndReduce(Lop tmpNode, Lop node, ArrayList<Lop> execNodes, ArrayList<Lop> queuedNodes) { if (node.getExecLocation() != ExecLocation.MapAndReduce) return false; JobType jt = JobType.findJobTypeFromLop(node); for ( Lop n : execNodes ) { if (n.equals(node)) continue; // Evaluate only nodes on the branch between tmpNode->..->node if (n.equals(tmpNode) || (isChild(n, node, IDMap) && isChild(tmpNode, n, IDMap))) { if ( hasOtherMapAndReduceParentNode(tmpNode, queuedNodes,node) ) return false; ExecLocation el = n.getExecLocation(); if (el != ExecLocation.Map && el != ExecLocation.MapOrReduce) return false; else if (!isCompatible(n, jt)) return false; } } return true; } private boolean branchHasNoOtherUnExecutedParents(Lop tmpNode, Lop node, ArrayList<Lop> execNodes, ArrayList<Lop> finishedNodes) { //if tmpNode has more than one unfinished output, return false if(tmpNode.getOutputs().size() > 1) { int cnt = 0; for (Lop output : tmpNode.getOutputs() ) if (!finishedNodes.contains(output)) cnt++; if(cnt != 1) return false; } //check to see if any node between node and tmpNode has more than one unfinished output for( Lop n : execNodes ) { if(n.equals(node) || n.equals(tmpNode)) continue; if(isChild(n, node, IDMap) && isChild(tmpNode, n, IDMap)) { int cnt = 0; for (Lop output : n.getOutputs() ) { if (!finishedNodes.contains(output)) cnt++; } if(cnt != 1) return false; } } return true; } /** * Method to return the job index for a lop. * * @param lops low-level operator * @param jobvec list of lists of low-level operators * @return job index for a low-level operator * @throws LopsException if LopsException occurs */ private static int jobType(Lop lops, ArrayList<ArrayList<Lop>> jobvec) throws LopsException { for ( JobType jt : JobType.values()) { int i = jt.getId(); if (i > 0 && jobvec.get(i) != null && jobvec.get(i).contains(lops)) { return i; } } return -1; } /** * Method to see if there is a node of type MapAndReduce between tmpNode and node * in given node collection * * @param tmpNode temporary low-level operator * @param nodeList list of low-level operators * @param node low-level operator * @return true if MapAndReduce node between tmpNode and node in nodeList */ private boolean hasOtherMapAndReduceParentNode(Lop tmpNode, ArrayList<Lop> nodeList, Lop node) { if ( tmpNode.getExecLocation() == ExecLocation.MapAndReduce) return true; for ( Lop n : tmpNode.getOutputs() ) { if ( nodeList.contains(n) && isChild(n,node,IDMap)) { if(!n.equals(node) && n.getExecLocation() == ExecLocation.MapAndReduce) return true; else return hasOtherMapAndReduceParentNode(n, nodeList, node); } } return false; } /** * Method to check if there is a queued node that is a parent of both tmpNode and node * * @param tmpNode temporary low-level operator * @param queuedNodes list of queued nodes * @param node low-level operator * @return true if there is a queued node that is a parent of tmpNode and node */ private boolean hasOtherQueuedParentNode(Lop tmpNode, ArrayList<Lop> queuedNodes, Lop node) { if ( queuedNodes.isEmpty() ) return false; boolean[] nodeMarked = node.get_reachable(); boolean[] tmpMarked = tmpNode.get_reachable(); long nodeid = IDMap.get(node.getID()); long tmpid = IDMap.get(tmpNode.getID()); for ( Lop qnode : queuedNodes ) { int id = IDMap.get(qnode.getID()); if ((id != nodeid && nodeMarked[id]) && (id != tmpid && tmpMarked[id]) ) return true; } return false; } /** * Method to print the lops grouped by job type * * @param jobNodes list of lists of low-level operators * @throws DMLRuntimeException if DMLRuntimeException occurs */ private static void printJobNodes(ArrayList<ArrayList<Lop>> jobNodes) throws DMLRuntimeException { if (LOG.isTraceEnabled()){ for ( JobType jt : JobType.values() ) { int i = jt.getId(); if (i > 0 && jobNodes.get(i) != null && !jobNodes.get(i).isEmpty() ) { LOG.trace(jt.getName() + " Job Nodes:"); for (int j = 0; j < jobNodes.get(i).size(); j++) { LOG.trace(" " + jobNodes.get(i).get(j).getID() + ") " + jobNodes.get(i).get(j).toString()); } } } } } /** * Method to check if there exists any lops with ExecLocation=RecordReader * * @param nodes list of low-level operators * @param loc exec location * @return true if there is a node with RecordReader exec location */ private static boolean hasANode(ArrayList<Lop> nodes, ExecLocation loc) { for ( Lop n : nodes ) { if (n.getExecLocation() == ExecLocation.RecordReader) return true; } return false; } private ArrayList<ArrayList<Lop>> splitGMRNodesByRecordReader(ArrayList<Lop> gmrnodes) { // obtain the list of record reader nodes ArrayList<Lop> rrnodes = new ArrayList<Lop>(); for (Lop gmrnode : gmrnodes ) { if (gmrnode.getExecLocation() == ExecLocation.RecordReader) rrnodes.add(gmrnode); } // We allocate one extra vector to hold lops that do not depend on any // recordreader lops ArrayList<ArrayList<Lop>> splitGMR = createNodeVectors(rrnodes.size() + 1); // flags to indicate whether a lop has been added to one of the node vectors boolean[] flags = new boolean[gmrnodes.size()]; Arrays.fill(flags, false); // first, obtain all ancestors of recordreader lops for (int rrid = 0; rrid < rrnodes.size(); rrid++) { // prepare node list for i^th record reader lop // add record reader lop splitGMR.get(rrid).add(rrnodes.get(rrid)); for (int j = 0; j < gmrnodes.size(); j++) { if (rrnodes.get(rrid).equals(gmrnodes.get(j))) flags[j] = true; else if (isChild(rrnodes.get(rrid), gmrnodes.get(j), IDMap)) { splitGMR.get(rrid).add(gmrnodes.get(j)); flags[j] = true; } } } // add all remaining lops to a separate job int jobindex = rrnodes.size(); // the last node vector for (int i = 0; i < gmrnodes.size(); i++) { if (!flags[i]) { splitGMR.get(jobindex).add(gmrnodes.get(i)); flags[i] = true; } } return splitGMR; } /** * Method to generate hadoop jobs. Exec nodes can contains a mixture of node * types requiring different mr jobs. This method breaks the job into * sub-types and then invokes the appropriate method to generate * instructions. * * @param execNodes list of exec nodes * @param inst list of instructions * @param writeinst list of write instructions * @param deleteinst list of delete instructions * @param jobNodes list of list of low-level operators * @throws LopsException if LopsException occurs * @throws DMLRuntimeException if DMLRuntimeException occurs */ private void generateMRJobs(ArrayList<Lop> execNodes, ArrayList<Instruction> inst, ArrayList<Instruction> writeinst, ArrayList<Instruction> deleteinst, ArrayList<ArrayList<Lop>> jobNodes) throws LopsException, DMLRuntimeException { printJobNodes(jobNodes); ArrayList<Instruction> rmvarinst = new ArrayList<Instruction>(); for (JobType jt : JobType.values()) { // do nothing, if jt = INVALID or ANY if ( jt == JobType.INVALID || jt == JobType.ANY ) continue; int index = jt.getId(); // job id is used as an index into jobNodes ArrayList<Lop> currNodes = jobNodes.get(index); // generate MR job if (currNodes != null && !currNodes.isEmpty() ) { if( LOG.isTraceEnabled() ) LOG.trace("Generating " + jt.getName() + " job"); if (jt.allowsRecordReaderInstructions() && hasANode(jobNodes.get(index), ExecLocation.RecordReader)) { // split the nodes by recordReader lops ArrayList<ArrayList<Lop>> rrlist = splitGMRNodesByRecordReader(jobNodes.get(index)); for (int i = 0; i < rrlist.size(); i++) { generateMapReduceInstructions(rrlist.get(i), inst, writeinst, deleteinst, rmvarinst, jt); } } else if ( jt.allowsSingleShuffleInstruction() ) { // These jobs allow a single shuffle instruction. // We should split the nodes so that a separate job is produced for each shuffle instruction. Lop.Type splittingLopType = jt.getShuffleLopType(); ArrayList<Lop> nodesForASingleJob = new ArrayList<Lop>(); for (int i = 0; i < jobNodes.get(index).size(); i++) { if (jobNodes.get(index).get(i).getType() == splittingLopType) { nodesForASingleJob.clear(); // Add the lop that defines the split nodesForASingleJob.add(jobNodes.get(index).get(i)); /* * Add the splitting lop's children. This call is redundant when jt=SORT * because a sort job ALWAYS has a SINGLE lop in the entire job * i.e., there are no children to add when jt=SORT. */ addChildren(jobNodes.get(index).get(i), nodesForASingleJob, jobNodes.get(index)); if ( jt.isCompatibleWithParentNodes() ) { /* * If the splitting lop is compatible with parent nodes * then they must be added to the job. For example, MMRJ lop * may have a Data(Write) lop as its parent, which can be * executed along with MMRJ. */ addParents(jobNodes.get(index).get(i), nodesForASingleJob, jobNodes.get(index)); } generateMapReduceInstructions(nodesForASingleJob, inst, writeinst, deleteinst, rmvarinst, jt); } } } else { // the default case generateMapReduceInstructions(jobNodes.get(index), inst, writeinst, deleteinst, rmvarinst, jt); } } } inst.addAll(rmvarinst); } /** * Method to add all parents of "node" in exec_n to node_v. * * @param node low-level operator * @param node_v list of nodes * @param exec_n list of nodes */ private void addParents(Lop node, ArrayList<Lop> node_v, ArrayList<Lop> exec_n) { for (Lop enode : exec_n ) { if (isChild(node, enode, IDMap)) { if (!node_v.contains(enode)) { if( LOG.isTraceEnabled() ) LOG.trace("Adding parent - " + enode.toString()); node_v.add(enode); } } } } /** * Method to add all relevant data nodes for set of exec nodes. * * @param node low-level operator * @param node_v list of nodes * @param exec_n list of nodes */ private static void addChildren(Lop node, ArrayList<Lop> node_v, ArrayList<Lop> exec_n) { // add child in exec nodes that is not of type scalar if (exec_n.contains(node) && node.getExecLocation() != ExecLocation.ControlProgram) { if (!node_v.contains(node)) { node_v.add(node); if(LOG.isTraceEnabled()) LOG.trace(" Added child " + node.toString()); } } if (!exec_n.contains(node)) return; // recurse for (Lop n : node.getInputs() ) { addChildren(n, node_v, exec_n); } } /** * Method that determines the output format for a given node. * * @param node low-level operator * @param cellModeOverride override mode * @return output info * @throws LopsException if LopsException occurs */ private static OutputInfo getOutputInfo(Lop node, boolean cellModeOverride) throws LopsException { if ( (node.getDataType() == DataType.SCALAR && node.getExecType() == ExecType.CP) || node instanceof FunctionCallCP ) return null; OutputInfo oinfo = null; OutputParameters oparams = node.getOutputParameters(); if (oparams.isBlocked()) { if ( !cellModeOverride ) oinfo = OutputInfo.BinaryBlockOutputInfo; else { // output format is overridden, for example, due to recordReaderInstructions in the job oinfo = OutputInfo.BinaryCellOutputInfo; // record decision of overriding in lop's outputParameters so that // subsequent jobs that use this lop's output know the correct format. // TODO: ideally, this should be done by having a member variable in Lop // which stores the outputInfo. try { oparams.setDimensions(oparams.getNumRows(), oparams.getNumCols(), -1, -1, oparams.getNnz(), oparams.getUpdateType()); } catch(HopsException e) { throw new LopsException(node.printErrorLocation() + "error in getOutputInfo in Dag ", e); } } } else { if (oparams.getFormat() == Format.TEXT || oparams.getFormat() == Format.MM) oinfo = OutputInfo.TextCellOutputInfo; else if ( oparams.getFormat() == Format.CSV ) { oinfo = OutputInfo.CSVOutputInfo; } else { oinfo = OutputInfo.BinaryCellOutputInfo; } } /* Instead of following hardcoding, one must get this information from Lops */ if (node.getType() == Type.SortKeys && node.getExecType() == ExecType.MR) { if( ((SortKeys)node).getOpType() == SortKeys.OperationTypes.Indexes) oinfo = OutputInfo.BinaryBlockOutputInfo; else oinfo = OutputInfo.OutputInfoForSortOutput; } else if (node.getType() == Type.CombineBinary) { // Output format of CombineBinary (CB) depends on how the output is consumed CombineBinary combine = (CombineBinary) node; if ( combine.getOperation() == org.apache.sysml.lops.CombineBinary.OperationTypes.PreSort ) { oinfo = OutputInfo.OutputInfoForSortInput; } else if ( combine.getOperation() == org.apache.sysml.lops.CombineBinary.OperationTypes.PreCentralMoment || combine.getOperation() == org.apache.sysml.lops.CombineBinary.OperationTypes.PreCovUnweighted || combine.getOperation() == org.apache.sysml.lops.CombineBinary.OperationTypes.PreGroupedAggUnweighted ) { oinfo = OutputInfo.WeightedPairOutputInfo; } } else if ( node.getType() == Type.CombineTernary) { oinfo = OutputInfo.WeightedPairOutputInfo; } else if (node.getType() == Type.CentralMoment || node.getType() == Type.CoVariance ) { // CMMR always operate in "cell mode", // and the output is always in cell format oinfo = OutputInfo.BinaryCellOutputInfo; } return oinfo; } private String prepareAssignVarInstruction(Lop input, Lop node) { StringBuilder sb = new StringBuilder(); sb.append(ExecType.CP); sb.append(Lop.OPERAND_DELIMITOR); sb.append("assignvar"); sb.append(Lop.OPERAND_DELIMITOR); sb.append( input.prepScalarInputOperand(ExecType.CP) ); sb.append(Lop.OPERAND_DELIMITOR); sb.append(node.prepOutputOperand()); return sb.toString(); } /** * Method to setup output filenames and outputInfos, and to generate related instructions * * @param node low-level operator * @param et exec type * @param cellModeOverride override mode * @param copyTWrite ? * @return node output * @throws DMLRuntimeException if DMLRuntimeException occurs * @throws LopsException if LopsException occurs */ private NodeOutput setupNodeOutputs(Lop node, ExecType et, boolean cellModeOverride, boolean copyTWrite) throws DMLRuntimeException, LopsException { OutputParameters oparams = node.getOutputParameters(); NodeOutput out = new NodeOutput(); node.setConsumerCount(node.getOutputs().size()); // Compute the output format for this node out.setOutInfo(getOutputInfo(node, cellModeOverride)); // If node is NOT of type Data then we must generate // a variable to hold the value produced by this node // note: functioncallcp requires no createvar, rmvar since // since outputs are explicitly specified if (node.getExecLocation() != ExecLocation.Data ) { if (node.getDataType() == DataType.SCALAR) { oparams.setLabel(Lop.SCALAR_VAR_NAME_PREFIX + var_index.getNextID()); out.setVarName(oparams.getLabel()); Instruction currInstr = VariableCPInstruction.prepareRemoveInstruction(oparams.getLabel()); currInstr.setLocation(node); out.addLastInstruction(currInstr); } else if(node instanceof ParameterizedBuiltin && ((ParameterizedBuiltin)node).getOp() == org.apache.sysml.lops.ParameterizedBuiltin.OperationTypes.TRANSFORM) { ParameterizedBuiltin pbi = (ParameterizedBuiltin)node; Lop input = pbi.getNamedInput(ParameterizedBuiltinFunctionExpression.TF_FN_PARAM_DATA); if(input.getDataType()== DataType.FRAME) { // Output of transform is in CSV format, which gets subsequently reblocked // TODO: change it to output binaryblock Data dataInput = (Data) input; oparams.setFile_name(getNextUniqueFilename()); oparams.setLabel(getNextUniqueVarname(DataType.MATRIX)); // generate an instruction that creates a symbol table entry for the new variable in CSV format Data delimLop = (Data) dataInput.getNamedInputLop( DataExpression.DELIM_DELIMITER, DataExpression.DEFAULT_DELIM_DELIMITER); Instruction createvarInst = VariableCPInstruction.prepareCreateVariableInstruction( oparams.getLabel(), oparams.getFile_name(), true, DataType.MATRIX, OutputInfo.outputInfoToString(OutputInfo.CSVOutputInfo), new MatrixCharacteristics(oparams.getNumRows(), oparams.getNumCols(), -1, -1, oparams.getNnz()), oparams.getUpdateType(), false, delimLop.getStringValue(), true ); createvarInst.setLocation(node); out.addPreInstruction(createvarInst); // temp file as well as the variable has to be deleted at the end Instruction currInstr = VariableCPInstruction.prepareRemoveInstruction(oparams.getLabel()); currInstr.setLocation(node); out.addLastInstruction(currInstr); // finally, add the generated filename and variable name to the list of outputs out.setFileName(oparams.getFile_name()); out.setVarName(oparams.getLabel()); } else { throw new LopsException("Input to transform() has an invalid type: " + input.getDataType() + ", it must be FRAME."); } } else if(!(node instanceof FunctionCallCP)) //general case { // generate temporary filename and a variable name to hold the // output produced by "rootNode" oparams.setFile_name(getNextUniqueFilename()); oparams.setLabel(getNextUniqueVarname(node.getDataType())); // generate an instruction that creates a symbol table entry for the new variable //String createInst = prepareVariableInstruction("createvar", node); //out.addPreInstruction(CPInstructionParser.parseSingleInstruction(createInst)); int rpb = (int) oparams.getRowsInBlock(); int cpb = (int) oparams.getColsInBlock(); Instruction createvarInst = VariableCPInstruction.prepareCreateVariableInstruction( oparams.getLabel(), oparams.getFile_name(), true, node.getDataType(), OutputInfo.outputInfoToString(getOutputInfo(node, false)), new MatrixCharacteristics(oparams.getNumRows(), oparams.getNumCols(), rpb, cpb, oparams.getNnz()), oparams.getUpdateType() ); createvarInst.setLocation(node); out.addPreInstruction(createvarInst); // temp file as well as the variable has to be deleted at the end Instruction currInstr = VariableCPInstruction.prepareRemoveInstruction(oparams.getLabel()); currInstr.setLocation(node); out.addLastInstruction(currInstr); // finally, add the generated filename and variable name to the list of outputs out.setFileName(oparams.getFile_name()); out.setVarName(oparams.getLabel()); } else { // If the function call is set with output lops (e.g., multi return builtin), // generate a createvar instruction for each function output FunctionCallCP fcall = (FunctionCallCP) node; if ( fcall.getFunctionOutputs() != null ) { for( Lop fnOut: fcall.getFunctionOutputs()) { OutputParameters fnOutParams = fnOut.getOutputParameters(); //OutputInfo oinfo = getOutputInfo((N)fnOut, false); Instruction createvarInst = VariableCPInstruction.prepareCreateVariableInstruction( fnOutParams.getLabel(), getFilePath() + fnOutParams.getLabel(), true, fnOut.getDataType(), OutputInfo.outputInfoToString(getOutputInfo(fnOut, false)), new MatrixCharacteristics(fnOutParams.getNumRows(), fnOutParams.getNumCols(), (int)fnOutParams.getRowsInBlock(), (int)fnOutParams.getColsInBlock(), fnOutParams.getNnz()), oparams.getUpdateType() ); if (node._beginLine != 0) createvarInst.setLocation(node); else createvarInst.setLocation(fnOut); out.addPreInstruction(createvarInst); } } } } // rootNode is of type Data else { if ( node.getDataType() == DataType.SCALAR ) { // generate assignment operations for final and transient writes if ( oparams.getFile_name() == null && !(node instanceof Data && ((Data)node).isPersistentWrite()) ) { String io_inst = prepareAssignVarInstruction(node.getInputs().get(0), node); CPInstruction currInstr = CPInstructionParser.parseSingleInstruction(io_inst); if (node._beginLine != 0) currInstr.setLocation(node); else if ( !node.getInputs().isEmpty() ) currInstr.setLocation(node.getInputs().get(0)); out.addLastInstruction(currInstr); } else { //CP PERSISTENT WRITE SCALARS Lop fname = ((Data)node).getNamedInputLop(DataExpression.IO_FILENAME); String io_inst = node.getInstructions(node.getInputs().get(0).getOutputParameters().getLabel(), fname.getOutputParameters().getLabel()); CPInstruction currInstr = CPInstructionParser.parseSingleInstruction(io_inst); if (node._beginLine != 0) currInstr.setLocation(node); else if ( !node.getInputs().isEmpty() ) currInstr.setLocation(node.getInputs().get(0)); out.addLastInstruction(currInstr); } } else { if ( ((Data)node).isTransient() ) { if ( et == ExecType.CP ) { // If transient matrix write is in CP then its input MUST be executed in CP as well. // get variable and filename associated with the input String inputFileName = node.getInputs().get(0).getOutputParameters().getFile_name(); String inputVarName = node.getInputs().get(0).getOutputParameters().getLabel(); String constVarName = oparams.getLabel(); String constFileName = inputFileName + constVarName; /* * Symbol Table state must change as follows: * * FROM: * mvar1 -> temp21 * * TO: * mVar1 -> temp21 * tVarH -> temp21 */ Instruction currInstr = VariableCPInstruction.prepareCopyInstruction(inputVarName, constVarName); currInstr.setLocation(node); out.addLastInstruction(currInstr); out.setFileName(constFileName); } else { if(copyTWrite) { Instruction currInstr = VariableCPInstruction.prepareCopyInstruction(node.getInputs().get(0).getOutputParameters().getLabel(), oparams.getLabel()); currInstr.setLocation(node); out.addLastInstruction(currInstr); return out; } /* * Since the "rootNode" is a transient data node, we first need to generate a * temporary filename as well as a variable name to hold the <i>immediate</i> * output produced by "rootNode". These generated HDFS filename and the * variable name must be changed at the end of an iteration/program block * so that the subsequent iteration/program block can correctly access the * generated data. Therefore, we need to distinguish between the following: * * 1) Temporary file name & variable name: They hold the immediate output * produced by "rootNode". Both names are generated below. * * 2) Constant file name & variable name: They are constant across iterations. * Variable name is given by rootNode's label that is created in the upper layers. * File name is generated by concatenating "temporary file name" and "constant variable name". * * Temporary files must be moved to constant files at the end of the iteration/program block. */ // generate temporary filename & var name String tempVarName = oparams.getLabel() + "temp"; String tempFileName = getNextUniqueFilename(); //String createInst = prepareVariableInstruction("createvar", tempVarName, node.getDataType(), node.getValueType(), tempFileName, oparams, out.getOutInfo()); //out.addPreInstruction(CPInstructionParser.parseSingleInstruction(createInst)); int rpb = (int) oparams.getRowsInBlock(); int cpb = (int) oparams.getColsInBlock(); Instruction createvarInst = VariableCPInstruction.prepareCreateVariableInstruction( tempVarName, tempFileName, true, node.getDataType(), OutputInfo.outputInfoToString(out.getOutInfo()), new MatrixCharacteristics(oparams.getNumRows(), oparams.getNumCols(), rpb, cpb, oparams.getNnz()), oparams.getUpdateType() ); createvarInst.setLocation(node); out.addPreInstruction(createvarInst); String constVarName = oparams.getLabel(); String constFileName = tempFileName + constVarName; oparams.setFile_name(getFilePath() + constFileName); /* * Since this is a node that denotes a transient read/write, we need to make sure * that the data computed for a given variable in a given iteration is passed on * to the next iteration. This is done by generating miscellaneous instructions * that gets executed at the end of the program block. * * The state of the symbol table must change * * FROM: * tVarA -> temp21tVarA (old copy of temp21) * tVarAtemp -> temp21 (new copy that should override the old copy) * * TO: * tVarA -> temp21tVarA */ // rename the temp variable to constant variable (e.g., cpvar tVarAtemp tVarA) /*Instruction currInstr = VariableCPInstruction.prepareCopyInstruction(tempVarName, constVarName); if(DMLScript.ENABLE_DEBUG_MODE) { currInstr.setLineNum(node._beginLine); } out.addLastInstruction(currInstr); Instruction tempInstr = VariableCPInstruction.prepareRemoveInstruction(tempVarName); if(DMLScript.ENABLE_DEBUG_MODE) { tempInstr.setLineNum(node._beginLine); } out.addLastInstruction(tempInstr);*/ // Generate a single mvvar instruction (e.g., mvvar tempA A) // instead of two instructions "cpvar tempA A" and "rmvar tempA" Instruction currInstr = VariableCPInstruction.prepareMoveInstruction(tempVarName, constVarName); currInstr.setLocation(node); out.addLastInstruction(currInstr); // finally, add the temporary filename and variable name to the list of outputs out.setFileName(tempFileName); out.setVarName(tempVarName); } } // rootNode is not a transient write. It is a persistent write. else { if(et == ExecType.MR) { //MR PERSISTENT WRITE // create a variable to hold the result produced by this "rootNode" oparams.setLabel("pVar" + var_index.getNextID() ); //String createInst = prepareVariableInstruction("createvar", node); //out.addPreInstruction(CPInstructionParser.parseSingleInstruction(createInst)); int rpb = (int) oparams.getRowsInBlock(); int cpb = (int) oparams.getColsInBlock(); Lop fnameLop = ((Data)node).getNamedInputLop(DataExpression.IO_FILENAME); String fnameStr = (fnameLop instanceof Data && ((Data)fnameLop).isLiteral()) ? fnameLop.getOutputParameters().getLabel() : Lop.VARIABLE_NAME_PLACEHOLDER + fnameLop.getOutputParameters().getLabel() + Lop.VARIABLE_NAME_PLACEHOLDER; Instruction createvarInst; // for MatrixMarket format, the creatvar will output the result to a temporary file in textcell format // the CP write instruction (post instruction) after the MR instruction will merge the result into a single // part MM format file on hdfs. if (oparams.getFormat() == Format.CSV) { String tempFileName = getNextUniqueFilename(); String createInst = node.getInstructions(tempFileName); createvarInst= CPInstructionParser.parseSingleInstruction(createInst); //NOTE: no instruction patching because final write from cp instruction String writeInst = node.getInstructions(oparams.getLabel(), fnameLop.getOutputParameters().getLabel() ); CPInstruction currInstr = CPInstructionParser.parseSingleInstruction(writeInst); currInstr.setLocation(node); out.addPostInstruction(currInstr); // remove the variable CPInstruction tempInstr = CPInstructionParser.parseSingleInstruction( "CP" + Lop.OPERAND_DELIMITOR + "rmfilevar" + Lop.OPERAND_DELIMITOR + oparams.getLabel() + Lop.VALUETYPE_PREFIX + Expression.ValueType.UNKNOWN + Lop.OPERAND_DELIMITOR + "true" + Lop.VALUETYPE_PREFIX + "BOOLEAN"); tempInstr.setLocation(node); out.addLastInstruction(tempInstr); } else if (oparams.getFormat() == Format.MM ) { createvarInst= VariableCPInstruction.prepareCreateVariableInstruction( oparams.getLabel(), getNextUniqueFilename(), false, node.getDataType(), OutputInfo.outputInfoToString(getOutputInfo(node, false)), new MatrixCharacteristics(oparams.getNumRows(), oparams.getNumCols(), rpb, cpb, oparams.getNnz()), oparams.getUpdateType() ); //NOTE: no instruction patching because final write from cp instruction String writeInst = node.getInstructions(oparams.getLabel(), fnameLop.getOutputParameters().getLabel()); CPInstruction currInstr = CPInstructionParser.parseSingleInstruction(writeInst); currInstr.setLocation(node); out.addPostInstruction(currInstr); // remove the variable CPInstruction tempInstr = CPInstructionParser.parseSingleInstruction( "CP" + Lop.OPERAND_DELIMITOR + "rmfilevar" + Lop.OPERAND_DELIMITOR + oparams.getLabel() + Lop.VALUETYPE_PREFIX + Expression.ValueType.UNKNOWN + Lop.OPERAND_DELIMITOR + "true" + Lop.VALUETYPE_PREFIX + "BOOLEAN"); tempInstr.setLocation(node); out.addLastInstruction(tempInstr); } else { createvarInst= VariableCPInstruction.prepareCreateVariableInstruction( oparams.getLabel(), fnameStr, false, node.getDataType(), OutputInfo.outputInfoToString(getOutputInfo(node, false)), new MatrixCharacteristics(oparams.getNumRows(), oparams.getNumCols(), rpb, cpb, oparams.getNnz()), oparams.getUpdateType() ); // remove the variable CPInstruction currInstr = CPInstructionParser.parseSingleInstruction( "CP" + Lop.OPERAND_DELIMITOR + "rmfilevar" + Lop.OPERAND_DELIMITOR + oparams.getLabel() + Lop.VALUETYPE_PREFIX + Expression.ValueType.UNKNOWN + Lop.OPERAND_DELIMITOR + "false" + Lop.VALUETYPE_PREFIX + "BOOLEAN"); currInstr.setLocation(node); out.addLastInstruction(currInstr); } createvarInst.setLocation(node); out.addPreInstruction(createvarInst); // finally, add the filename and variable name to the list of outputs out.setFileName(oparams.getFile_name()); out.setVarName(oparams.getLabel()); } else { //CP PERSISTENT WRITE // generate a write instruction that writes matrix to HDFS Lop fname = ((Data)node).getNamedInputLop(DataExpression.IO_FILENAME); Instruction currInstr = null; Lop inputLop = node.getInputs().get(0); // Case of a transient read feeding into only one output persistent binaryblock write // Move the temporary file on HDFS to required persistent location, insteadof copying. if (inputLop.getExecLocation() == ExecLocation.Data && inputLop.getOutputs().size() == 1 && ((Data)inputLop).isTransient() && ((Data)inputLop).getOutputParameters().isBlocked() && node.getOutputParameters().isBlocked() ) { // transient read feeding into persistent write in blocked representation // simply, move the file //prepare filename (literal or variable in order to support dynamic write) String fnameStr = (fname instanceof Data && ((Data)fname).isLiteral()) ? fname.getOutputParameters().getLabel() : Lop.VARIABLE_NAME_PLACEHOLDER + fname.getOutputParameters().getLabel() + Lop.VARIABLE_NAME_PLACEHOLDER; currInstr = (CPInstruction) VariableCPInstruction.prepareMoveInstruction( inputLop.getOutputParameters().getLabel(), fnameStr, "binaryblock" ); } else { String io_inst = node.getInstructions( node.getInputs().get(0).getOutputParameters().getLabel(), fname.getOutputParameters().getLabel()); if(node.getExecType() == ExecType.SPARK) // This will throw an exception if the exectype of hop is set incorrectly // Note: the exec type and exec location of lops needs to be set to SPARK and ControlProgram respectively currInstr = SPInstructionParser.parseSingleInstruction(io_inst); else currInstr = CPInstructionParser.parseSingleInstruction(io_inst); } if ( !node.getInputs().isEmpty() && node.getInputs().get(0)._beginLine != 0) currInstr.setLocation(node.getInputs().get(0)); else currInstr.setLocation(node); out.addLastInstruction(currInstr); } } } } return out; } /** * Method to generate MapReduce job instructions from a given set of nodes. * * @param execNodes list of exec nodes * @param inst list of instructions * @param writeinst list of write instructions * @param deleteinst list of delete instructions * @param rmvarinst list of rmvar instructions * @param jt job type * @throws LopsException if LopsException occurs * @throws DMLRuntimeException if DMLRuntimeException occurs */ private void generateMapReduceInstructions(ArrayList<Lop> execNodes, ArrayList<Instruction> inst, ArrayList<Instruction> writeinst, ArrayList<Instruction> deleteinst, ArrayList<Instruction> rmvarinst, JobType jt) throws LopsException, DMLRuntimeException { ArrayList<Byte> resultIndices = new ArrayList<Byte>(); ArrayList<String> inputs = new ArrayList<String>(); ArrayList<String> outputs = new ArrayList<String>(); ArrayList<InputInfo> inputInfos = new ArrayList<InputInfo>(); ArrayList<OutputInfo> outputInfos = new ArrayList<OutputInfo>(); ArrayList<Long> numRows = new ArrayList<Long>(); ArrayList<Long> numCols = new ArrayList<Long>(); ArrayList<Long> numRowsPerBlock = new ArrayList<Long>(); ArrayList<Long> numColsPerBlock = new ArrayList<Long>(); ArrayList<String> mapperInstructions = new ArrayList<String>(); ArrayList<String> randInstructions = new ArrayList<String>(); ArrayList<String> recordReaderInstructions = new ArrayList<String>(); int numReducers = 0; int replication = 1; ArrayList<String> inputLabels = new ArrayList<String>(); ArrayList<String> outputLabels = new ArrayList<String>(); ArrayList<Instruction> renameInstructions = new ArrayList<Instruction>(); ArrayList<Instruction> variableInstructions = new ArrayList<Instruction>(); ArrayList<Instruction> postInstructions = new ArrayList<Instruction>(); ArrayList<Integer> MRJobLineNumbers = null; if(DMLScript.ENABLE_DEBUG_MODE) { MRJobLineNumbers = new ArrayList<Integer>(); } ArrayList<Lop> inputLops = new ArrayList<Lop>(); boolean cellModeOverride = false; /* Find the nodes that produce an output */ ArrayList<Lop> rootNodes = new ArrayList<Lop>(); getOutputNodes(execNodes, rootNodes, jt); if( LOG.isTraceEnabled() ) LOG.trace("# of root nodes = " + rootNodes.size()); /* Remove transient writes that are simple copy of transient reads */ if (jt == JobType.GMR || jt == JobType.GMRCELL) { ArrayList<Lop> markedNodes = new ArrayList<Lop>(); // only keep data nodes that are results of some computation. for ( Lop rnode : rootNodes ) { if (rnode.getExecLocation() == ExecLocation.Data && ((Data) rnode).isTransient() && ((Data) rnode).getOperationType() == OperationTypes.WRITE && ((Data) rnode).getDataType() == DataType.MATRIX) { // no computation, just a copy if (rnode.getInputs().get(0).getExecLocation() == ExecLocation.Data && ((Data) rnode.getInputs().get(0)).isTransient() && rnode.getOutputParameters().getLabel().equals( rnode.getInputs().get(0).getOutputParameters().getLabel())) { markedNodes.add(rnode); } } } // delete marked nodes rootNodes.removeAll(markedNodes); markedNodes.clear(); if ( rootNodes.isEmpty() ) return; } // structure that maps node to their indices that will be used in the instructions HashMap<Lop, Integer> nodeIndexMapping = new HashMap<Lop, Integer>(); /* Determine all input data files */ for ( Lop rnode : rootNodes ) { getInputPathsAndParameters(rnode, execNodes, inputs, inputInfos, numRows, numCols, numRowsPerBlock, numColsPerBlock, nodeIndexMapping, inputLabels, inputLops, MRJobLineNumbers); } // In case of RAND job, instructions are defined in the input file if (jt == JobType.DATAGEN) randInstructions = inputs; int[] start_index = new int[1]; start_index[0] = inputs.size(); /* Get RecordReader Instructions */ // currently, recordreader instructions are allowed only in GMR jobs if (jt == JobType.GMR || jt == JobType.GMRCELL) { for ( Lop rnode : rootNodes ) { getRecordReaderInstructions(rnode, execNodes, inputs, recordReaderInstructions, nodeIndexMapping, start_index, inputLabels, inputLops, MRJobLineNumbers); if ( recordReaderInstructions.size() > 1 ) throw new LopsException("MapReduce job can only have a single recordreader instruction: " + recordReaderInstructions.toString()); } } /* * Handle cases when job's output is FORCED to be cell format. * - If there exist a cell input, then output can not be blocked. * Only exception is when jobType = REBLOCK/CSVREBLOCK (for obvisous reason) * or when jobType = RAND since RandJob takes a special input file, * whose format should not be used to dictate the output format. * - If there exists a recordReader instruction * - If jobtype = GroupedAgg. This job can only run in cell mode. */ // if ( jt != JobType.REBLOCK && jt != JobType.CSV_REBLOCK && jt != JobType.DATAGEN && jt != JobType.TRANSFORM) { for (int i=0; i < inputInfos.size(); i++) if ( inputInfos.get(i) == InputInfo.BinaryCellInputInfo || inputInfos.get(i) == InputInfo.TextCellInputInfo ) cellModeOverride = true; } if ( !recordReaderInstructions.isEmpty() || jt == JobType.GROUPED_AGG ) cellModeOverride = true; /* Get Mapper Instructions */ for (int i = 0; i < rootNodes.size(); i++) { getMapperInstructions(rootNodes.get(i), execNodes, inputs, mapperInstructions, nodeIndexMapping, start_index, inputLabels, inputLops, MRJobLineNumbers); } if (LOG.isTraceEnabled()) { LOG.trace(" Input strings: " + inputs.toString()); if (jt == JobType.DATAGEN) LOG.trace(" Rand instructions: " + getCSVString(randInstructions)); if (jt == JobType.GMR) LOG.trace(" RecordReader instructions: " + getCSVString(recordReaderInstructions)); LOG.trace(" Mapper instructions: " + getCSVString(mapperInstructions)); } /* Get Shuffle and Reducer Instructions */ ArrayList<String> shuffleInstructions = new ArrayList<String>(); ArrayList<String> aggInstructionsReducer = new ArrayList<String>(); ArrayList<String> otherInstructionsReducer = new ArrayList<String>(); for( Lop rn : rootNodes ) { int resultIndex = getAggAndOtherInstructions( rn, execNodes, shuffleInstructions, aggInstructionsReducer, otherInstructionsReducer, nodeIndexMapping, start_index, inputLabels, inputLops, MRJobLineNumbers); if ( resultIndex == -1) throw new LopsException("Unexpected error in piggybacking!"); if ( rn.getExecLocation() == ExecLocation.Data && ((Data)rn).getOperationType() == Data.OperationTypes.WRITE && ((Data)rn).isTransient() && rootNodes.contains(rn.getInputs().get(0)) ) { // Both rn (a transient write) and its input are root nodes. // Instead of creating two copies of the data, simply generate a cpvar instruction NodeOutput out = setupNodeOutputs(rn, ExecType.MR, cellModeOverride, true); writeinst.addAll(out.getLastInstructions()); } else { resultIndices.add(Byte.valueOf((byte)resultIndex)); // setup output filenames and outputInfos and generate related instructions NodeOutput out = setupNodeOutputs(rn, ExecType.MR, cellModeOverride, false); outputLabels.add(out.getVarName()); outputs.add(out.getFileName()); outputInfos.add(out.getOutInfo()); if (LOG.isTraceEnabled()) { LOG.trace(" Output Info: " + out.getFileName() + ";" + OutputInfo.outputInfoToString(out.getOutInfo()) + ";" + out.getVarName()); } renameInstructions.addAll(out.getLastInstructions()); variableInstructions.addAll(out.getPreInstructions()); postInstructions.addAll(out.getPostInstructions()); } } /* Determine if the output dimensions are known */ byte[] resultIndicesByte = new byte[resultIndices.size()]; for (int i = 0; i < resultIndicesByte.length; i++) { resultIndicesByte[i] = resultIndices.get(i).byteValue(); } if (LOG.isTraceEnabled()) { LOG.trace(" Shuffle Instructions: " + getCSVString(shuffleInstructions)); LOG.trace(" Aggregate Instructions: " + getCSVString(aggInstructionsReducer)); LOG.trace(" Other instructions =" + getCSVString(otherInstructionsReducer)); LOG.trace(" Output strings: " + outputs.toString()); LOG.trace(" ResultIndices = " + resultIndices.toString()); } /* Prepare the MapReduce job instruction */ MRJobInstruction mr = new MRJobInstruction(jt); // check if this is a map-only job. If not, set the number of reducers if ( !shuffleInstructions.isEmpty() || !aggInstructionsReducer.isEmpty() || !otherInstructionsReducer.isEmpty() ) numReducers = total_reducers; // set inputs, outputs, and other other properties for the job mr.setInputOutputLabels(inputLabels.toArray(new String[0]), outputLabels.toArray(new String[0])); mr.setOutputs(resultIndicesByte); mr.setDimsUnknownFilePrefix(getFilePath()); mr.setNumberOfReducers(numReducers); mr.setReplication(replication); // set instructions for recordReader and mapper mr.setRecordReaderInstructions(getCSVString(recordReaderInstructions)); mr.setMapperInstructions(getCSVString(mapperInstructions)); //compute and set mapper memory requirements (for consistency of runtime piggybacking) if( jt == JobType.GMR ) { double mem = 0; for( Lop n : execNodes ) mem += computeFootprintInMapper(n); mr.setMemoryRequirements(mem); } if ( jt == JobType.DATAGEN ) mr.setRandInstructions(getCSVString(randInstructions)); // set shuffle instructions mr.setShuffleInstructions(getCSVString(shuffleInstructions)); // set reducer instruction mr.setAggregateInstructionsInReducer(getCSVString(aggInstructionsReducer)); mr.setOtherInstructionsInReducer(getCSVString(otherInstructionsReducer)); if(DMLScript.ENABLE_DEBUG_MODE) { // set line number information for each MR instruction mr.setMRJobInstructionsLineNumbers(MRJobLineNumbers); } /* Add the prepared instructions to output set */ inst.addAll(variableInstructions); inst.add(mr); inst.addAll(postInstructions); deleteinst.addAll(renameInstructions); for (Lop l : inputLops) { if(DMLScript.ENABLE_DEBUG_MODE) { processConsumers(l, rmvarinst, deleteinst, l); } else { processConsumers(l, rmvarinst, deleteinst, null); } } } /** * converts an array list into a Lop.INSTRUCTION_DELIMITOR separated string * * @param inputStrings list of input strings * @return Lop.INSTRUCTION_DELIMITOR separated string */ private static String getCSVString(ArrayList<String> inputStrings) { StringBuilder sb = new StringBuilder(); for ( String str : inputStrings ) { if( str != null ) { if( sb.length()>0 ) sb.append(Lop.INSTRUCTION_DELIMITOR); sb.append( str ); } } return sb.toString(); } /** * Method to populate aggregate and other instructions in reducer. * * @param node low-level operator * @param execNodes list of exec nodes * @param shuffleInstructions list of shuffle instructions * @param aggInstructionsReducer ? * @param otherInstructionsReducer ? * @param nodeIndexMapping node index mapping * @param start_index start index * @param inputLabels list of input labels * @param inputLops list of input lops * @param MRJobLineNumbers MR job line numbers * @return -1 if problem * @throws LopsException if LopsException occurs */ private int getAggAndOtherInstructions(Lop node, ArrayList<Lop> execNodes, ArrayList<String> shuffleInstructions, ArrayList<String> aggInstructionsReducer, ArrayList<String> otherInstructionsReducer, HashMap<Lop, Integer> nodeIndexMapping, int[] start_index, ArrayList<String> inputLabels, ArrayList<Lop> inputLops, ArrayList<Integer> MRJobLineNumbers) throws LopsException { int ret_val = -1; if (nodeIndexMapping.containsKey(node)) return nodeIndexMapping.get(node); // if not an input source and not in exec nodes, return. if (!execNodes.contains(node)) return ret_val; ArrayList<Integer> inputIndices = new ArrayList<Integer>(); // recurse // For WRITE, since the first element from input is the real input (the other elements // are parameters for the WRITE operation), so we only need to take care of the // first element. if (node.getType() == Lop.Type.Data && ((Data)node).getOperationType() == Data.OperationTypes.WRITE) { ret_val = getAggAndOtherInstructions(node.getInputs().get(0), execNodes, shuffleInstructions, aggInstructionsReducer, otherInstructionsReducer, nodeIndexMapping, start_index, inputLabels, inputLops, MRJobLineNumbers); inputIndices.add(ret_val); } else { for ( Lop cnode : node.getInputs() ) { ret_val = getAggAndOtherInstructions(cnode, execNodes, shuffleInstructions, aggInstructionsReducer, otherInstructionsReducer, nodeIndexMapping, start_index, inputLabels, inputLops, MRJobLineNumbers); inputIndices.add(ret_val); } } if (node.getExecLocation() == ExecLocation.Data ) { if ( ((Data)node).getFileFormatType() == FileFormatTypes.CSV && !(node.getInputs().get(0) instanceof ParameterizedBuiltin && ((ParameterizedBuiltin)node.getInputs().get(0)).getOp() == org.apache.sysml.lops.ParameterizedBuiltin.OperationTypes.TRANSFORM)) { // Generate write instruction, which goes into CSV_WRITE Job int output_index = start_index[0]; shuffleInstructions.add(node.getInstructions(inputIndices.get(0), output_index)); if(DMLScript.ENABLE_DEBUG_MODE) { MRJobLineNumbers.add(node._beginLine); } nodeIndexMapping.put(node, output_index); start_index[0]++; return output_index; } else { return ret_val; } } if (node.getExecLocation() == ExecLocation.MapAndReduce) { /* Generate Shuffle Instruction for "node", and return the index associated with produced output */ boolean instGenerated = true; int output_index = start_index[0]; switch(node.getType()) { /* Lop types that take a single input */ case ReBlock: case CSVReBlock: case SortKeys: case CentralMoment: case CoVariance: case GroupedAgg: case DataPartition: shuffleInstructions.add(node.getInstructions(inputIndices.get(0), output_index)); if(DMLScript.ENABLE_DEBUG_MODE) { MRJobLineNumbers.add(node._beginLine); } break; case ParameterizedBuiltin: if( ((ParameterizedBuiltin)node).getOp() == org.apache.sysml.lops.ParameterizedBuiltin.OperationTypes.TRANSFORM ) { shuffleInstructions.add(node.getInstructions(output_index)); if(DMLScript.ENABLE_DEBUG_MODE) { MRJobLineNumbers.add(node._beginLine); } } break; /* Lop types that take two inputs */ case MMCJ: case MMRJ: case CombineBinary: shuffleInstructions.add(node.getInstructions(inputIndices.get(0), inputIndices.get(1), output_index)); if(DMLScript.ENABLE_DEBUG_MODE) { MRJobLineNumbers.add(node._beginLine); } break; /* Lop types that take three inputs */ case CombineTernary: shuffleInstructions.add(node.getInstructions(inputIndices .get(0), inputIndices.get(1), inputIndices.get(2), output_index)); if(DMLScript.ENABLE_DEBUG_MODE) { MRJobLineNumbers.add(node._beginLine); } break; default: instGenerated = false; break; } if ( instGenerated ) { nodeIndexMapping.put(node, output_index); start_index[0]++; return output_index; } else { return inputIndices.get(0); } } /* Get instructions for aligned reduce and other lops below the reduce. */ if (node.getExecLocation() == ExecLocation.Reduce || node.getExecLocation() == ExecLocation.MapOrReduce || hasChildNode(node, execNodes, ExecLocation.MapAndReduce)) { if (inputIndices.size() == 1) { int output_index = start_index[0]; start_index[0]++; if (node.getType() == Type.Aggregate) { aggInstructionsReducer.add(node.getInstructions( inputIndices.get(0), output_index)); if(DMLScript.ENABLE_DEBUG_MODE) { MRJobLineNumbers.add(node._beginLine); } } else { otherInstructionsReducer.add(node.getInstructions( inputIndices.get(0), output_index)); } if(DMLScript.ENABLE_DEBUG_MODE) { MRJobLineNumbers.add(node._beginLine); } nodeIndexMapping.put(node, output_index); return output_index; } else if (inputIndices.size() == 2) { int output_index = start_index[0]; start_index[0]++; otherInstructionsReducer.add(node.getInstructions(inputIndices .get(0), inputIndices.get(1), output_index)); if(DMLScript.ENABLE_DEBUG_MODE) { MRJobLineNumbers.add(node._beginLine); } nodeIndexMapping.put(node, output_index); // populate list of input labels. // only Unary lops can contribute to labels if (node instanceof Unary && node.getInputs().size() > 1) { int index = 0; for (int i = 0; i < node.getInputs().size(); i++) { if (node.getInputs().get(i).getDataType() == DataType.SCALAR) { index = i; break; } } if (node.getInputs().get(index).getExecLocation() == ExecLocation.Data && !((Data) (node.getInputs().get(index))).isLiteral()) { inputLabels.add(node.getInputs().get(index).getOutputParameters().getLabel()); inputLops.add(node.getInputs().get(index)); } if (node.getInputs().get(index).getExecLocation() != ExecLocation.Data) { inputLabels.add(node.getInputs().get(index).getOutputParameters().getLabel()); inputLops.add(node.getInputs().get(index)); } } return output_index; } else if (inputIndices.size() == 3 || node.getType() == Type.Ternary) { int output_index = start_index[0]; start_index[0]++; if (node.getType() == Type.Ternary ) { // in case of CTABLE_TRANSFORM_SCALAR_WEIGHT: inputIndices.get(2) would be -1 otherInstructionsReducer.add(node.getInstructions( inputIndices.get(0), inputIndices.get(1), inputIndices.get(2), output_index)); if(DMLScript.ENABLE_DEBUG_MODE) { MRJobLineNumbers.add(node._beginLine); } nodeIndexMapping.put(node, output_index); } else if( node.getType() == Type.ParameterizedBuiltin ){ otherInstructionsReducer.add(node.getInstructions( inputIndices.get(0), inputIndices.get(1), inputIndices.get(2), output_index)); if(DMLScript.ENABLE_DEBUG_MODE) { MRJobLineNumbers.add(node._beginLine); } nodeIndexMapping.put(node, output_index); } else { otherInstructionsReducer.add(node.getInstructions( inputIndices.get(0), inputIndices.get(1), inputIndices.get(2), output_index)); if(DMLScript.ENABLE_DEBUG_MODE) { MRJobLineNumbers.add(node._beginLine); } nodeIndexMapping.put(node, output_index); return output_index; } return output_index; } else if (inputIndices.size() == 4) { int output_index = start_index[0]; start_index[0]++; otherInstructionsReducer.add(node.getInstructions( inputIndices.get(0), inputIndices.get(1), inputIndices.get(2), inputIndices.get(3), output_index)); if(DMLScript.ENABLE_DEBUG_MODE) { MRJobLineNumbers.add(node._beginLine); } nodeIndexMapping.put(node, output_index); return output_index; } else throw new LopsException("Invalid number of inputs to a lop: " + inputIndices.size()); } return -1; } /** * Method to get record reader instructions for a MR job. * * @param node low-level operator * @param execNodes list of exec nodes * @param inputStrings list of input strings * @param recordReaderInstructions list of record reader instructions * @param nodeIndexMapping node index mapping * @param start_index start index * @param inputLabels list of input labels * @param inputLops list of input lops * @param MRJobLineNumbers MR job line numbers * @return -1 if problem * @throws LopsException if LopsException occurs */ private static int getRecordReaderInstructions(Lop node, ArrayList<Lop> execNodes, ArrayList<String> inputStrings, ArrayList<String> recordReaderInstructions, HashMap<Lop, Integer> nodeIndexMapping, int[] start_index, ArrayList<String> inputLabels, ArrayList<Lop> inputLops, ArrayList<Integer> MRJobLineNumbers) throws LopsException { // if input source, return index if (nodeIndexMapping.containsKey(node)) return nodeIndexMapping.get(node); // not input source and not in exec nodes, then return. if (!execNodes.contains(node)) return -1; ArrayList<Integer> inputIndices = new ArrayList<Integer>(); int max_input_index = -1; //N child_for_max_input_index = null; // get mapper instructions for (int i = 0; i < node.getInputs().size(); i++) { // recurse Lop childNode = node.getInputs().get(i); int ret_val = getRecordReaderInstructions(childNode, execNodes, inputStrings, recordReaderInstructions, nodeIndexMapping, start_index, inputLabels, inputLops, MRJobLineNumbers); inputIndices.add(ret_val); if (ret_val > max_input_index) { max_input_index = ret_val; //child_for_max_input_index = childNode; } } // only lops with execLocation as RecordReader can contribute // instructions if ((node.getExecLocation() == ExecLocation.RecordReader)) { int output_index = max_input_index; // cannot reuse index if this is true // need to add better indexing schemes output_index = start_index[0]; start_index[0]++; nodeIndexMapping.put(node, output_index); // populate list of input labels. // only Ranagepick lop can contribute to labels if (node.getType() == Type.PickValues) { PickByCount pbc = (PickByCount) node; if (pbc.getOperationType() == PickByCount.OperationTypes.RANGEPICK) { int scalarIndex = 1; // always the second input is a scalar // if data lop not a literal -- add label if (node.getInputs().get(scalarIndex).getExecLocation() == ExecLocation.Data && !((Data) (node.getInputs().get(scalarIndex))).isLiteral()) { inputLabels.add(node.getInputs().get(scalarIndex).getOutputParameters().getLabel()); inputLops.add(node.getInputs().get(scalarIndex)); } // if not data lop, then this is an intermediate variable. if (node.getInputs().get(scalarIndex).getExecLocation() != ExecLocation.Data) { inputLabels.add(node.getInputs().get(scalarIndex).getOutputParameters().getLabel()); inputLops.add(node.getInputs().get(scalarIndex)); } } } // get recordreader instruction. if (node.getInputs().size() == 2) { recordReaderInstructions.add(node.getInstructions(inputIndices .get(0), inputIndices.get(1), output_index)); if(DMLScript.ENABLE_DEBUG_MODE) { MRJobLineNumbers.add(node._beginLine); } } else throw new LopsException( "Unexpected number of inputs while generating a RecordReader Instruction"); return output_index; } return -1; } /** * Method to get mapper instructions for a MR job. * * @param node low-level operator * @param execNodes list of exec nodes * @param inputStrings list of input strings * @param instructionsInMapper list of instructions in mapper * @param nodeIndexMapping ? * @param start_index starting index * @param inputLabels input labels * @param MRJoblineNumbers MR job line numbers * @return -1 if problem * @throws LopsException if LopsException occurs */ private int getMapperInstructions(Lop node, ArrayList<Lop> execNodes, ArrayList<String> inputStrings, ArrayList<String> instructionsInMapper, HashMap<Lop, Integer> nodeIndexMapping, int[] start_index, ArrayList<String> inputLabels, ArrayList<Lop> inputLops, ArrayList<Integer> MRJobLineNumbers) throws LopsException { // if input source, return index if (nodeIndexMapping.containsKey(node)) return nodeIndexMapping.get(node); // not input source and not in exec nodes, then return. if (!execNodes.contains(node)) return -1; ArrayList<Integer> inputIndices = new ArrayList<Integer>(); int max_input_index = -1; // get mapper instructions for( Lop childNode : node.getInputs()) { int ret_val = getMapperInstructions(childNode, execNodes, inputStrings, instructionsInMapper, nodeIndexMapping, start_index, inputLabels, inputLops, MRJobLineNumbers); inputIndices.add(ret_val); if (ret_val > max_input_index) { max_input_index = ret_val; } } // only map and map-or-reduce without a reduce child node can contribute // to mapper instructions. if ((node.getExecLocation() == ExecLocation.Map || node .getExecLocation() == ExecLocation.MapOrReduce) && !hasChildNode(node, execNodes, ExecLocation.MapAndReduce) && !hasChildNode(node, execNodes, ExecLocation.Reduce) ) { int output_index = max_input_index; // cannot reuse index if this is true // need to add better indexing schemes // if (child_for_max_input_index.getOutputs().size() > 1) { output_index = start_index[0]; start_index[0]++; // } nodeIndexMapping.put(node, output_index); // populate list of input labels. // only Unary lops can contribute to labels if (node instanceof Unary && node.getInputs().size() > 1) { // Following code must be executed only for those Unary // operators that have more than one input // It should not be executed for "true" unary operators like // cos(A). int index = 0; for (int i1 = 0; i1 < node.getInputs().size(); i1++) { if (node.getInputs().get(i1).getDataType() == DataType.SCALAR) { index = i1; break; } } // if data lop not a literal -- add label if (node.getInputs().get(index).getExecLocation() == ExecLocation.Data && !((Data) (node.getInputs().get(index))).isLiteral()) { inputLabels.add(node.getInputs().get(index).getOutputParameters().getLabel()); inputLops.add(node.getInputs().get(index)); } // if not data lop, then this is an intermediate variable. if (node.getInputs().get(index).getExecLocation() != ExecLocation.Data) { inputLabels.add(node.getInputs().get(index).getOutputParameters().getLabel()); inputLops.add(node.getInputs().get(index)); } } // get mapper instruction. if (node.getInputs().size() == 1) instructionsInMapper.add(node.getInstructions(inputIndices .get(0), output_index)); else if (node.getInputs().size() == 2) { instructionsInMapper.add(node.getInstructions(inputIndices .get(0), inputIndices.get(1), output_index)); } else if (node.getInputs().size() == 3) instructionsInMapper.add(node.getInstructions(inputIndices.get(0), inputIndices.get(1), inputIndices.get(2), output_index)); else if ( node.getInputs().size() == 4) { // Example: Reshape instructionsInMapper.add(node.getInstructions( inputIndices.get(0), inputIndices.get(1), inputIndices.get(2), inputIndices.get(3), output_index )); } else if ( node.getInputs().size() == 5) { // Example: RangeBasedReIndex A[row_l:row_u, col_l:col_u] instructionsInMapper.add(node.getInstructions( inputIndices.get(0), inputIndices.get(1), inputIndices.get(2), inputIndices.get(3), inputIndices.get(4), output_index )); } else if ( node.getInputs().size() == 7 ) { // Example: RangeBasedReIndex A[row_l:row_u, col_l:col_u] = B instructionsInMapper.add(node.getInstructions( inputIndices.get(0), inputIndices.get(1), inputIndices.get(2), inputIndices.get(3), inputIndices.get(4), inputIndices.get(5), inputIndices.get(6), output_index )); } else throw new LopsException("Node with " + node.getInputs().size() + " inputs is not supported in dag.java."); if(DMLScript.ENABLE_DEBUG_MODE) { MRJobLineNumbers.add(node._beginLine); } return output_index; } return -1; } // Method to populate inputs and also populates node index mapping. private static void getInputPathsAndParameters(Lop node, ArrayList<Lop> execNodes, ArrayList<String> inputStrings, ArrayList<InputInfo> inputInfos, ArrayList<Long> numRows, ArrayList<Long> numCols, ArrayList<Long> numRowsPerBlock, ArrayList<Long> numColsPerBlock, HashMap<Lop, Integer> nodeIndexMapping, ArrayList<String> inputLabels, ArrayList<Lop> inputLops, ArrayList<Integer> MRJobLineNumbers) throws LopsException { // treat rand as an input. if (node.getType() == Type.DataGen && execNodes.contains(node) && !nodeIndexMapping.containsKey(node)) { numRows.add(node.getOutputParameters().getNumRows()); numCols.add(node.getOutputParameters().getNumCols()); numRowsPerBlock.add(node.getOutputParameters().getRowsInBlock()); numColsPerBlock.add(node.getOutputParameters().getColsInBlock()); inputStrings.add(node.getInstructions(inputStrings.size(), inputStrings.size())); if(DMLScript.ENABLE_DEBUG_MODE) { MRJobLineNumbers.add(node._beginLine); } inputInfos.add(InputInfo.TextCellInputInfo); nodeIndexMapping.put(node, inputStrings.size() - 1); return; } // get input file names if (!execNodes.contains(node) && !nodeIndexMapping.containsKey(node) && !(node.getExecLocation() == ExecLocation.Data) && (!(node.getExecLocation() == ExecLocation.ControlProgram && node .getDataType() == DataType.SCALAR)) || (!execNodes.contains(node) && node.getExecLocation() == ExecLocation.Data && ((Data) node).getOperationType() == Data.OperationTypes.READ && ((Data) node).getDataType() != DataType.SCALAR && !nodeIndexMapping .containsKey(node))) { if (node.getOutputParameters().getFile_name() != null) { inputStrings.add(node.getOutputParameters().getFile_name()); } else { // use label name inputStrings.add(Lop.VARIABLE_NAME_PLACEHOLDER + node.getOutputParameters().getLabel() + Lop.VARIABLE_NAME_PLACEHOLDER); } inputLabels.add(node.getOutputParameters().getLabel()); inputLops.add(node); numRows.add(node.getOutputParameters().getNumRows()); numCols.add(node.getOutputParameters().getNumCols()); numRowsPerBlock.add(node.getOutputParameters().getRowsInBlock()); numColsPerBlock.add(node.getOutputParameters().getColsInBlock()); InputInfo nodeInputInfo = null; // Check if file format type is binary or text and update infos if (node.getOutputParameters().isBlocked()) { if (node.getOutputParameters().getFormat() == Format.BINARY) nodeInputInfo = InputInfo.BinaryBlockInputInfo; else throw new LopsException("Invalid format (" + node.getOutputParameters().getFormat() + ") encountered for a node/lop (ID=" + node.getID() + ") with blocked output."); } else { if (node.getOutputParameters().getFormat() == Format.TEXT) nodeInputInfo = InputInfo.TextCellInputInfo; else nodeInputInfo = InputInfo.BinaryCellInputInfo; } /* * Hardcode output Key and Value Classes for SortKeys */ // TODO: statiko -- remove this hardcoding -- i.e., lops must encode // the information on key/value classes if (node.getType() == Type.SortKeys) { // SortKeys is the input to some other lop (say, L) // InputInfo of L is the ouputInfo of SortKeys, which is // (compactformat, doubleWriteable, IntWritable) nodeInputInfo = new InputInfo(PickFromCompactInputFormat.class, DoubleWritable.class, IntWritable.class); } else if (node.getType() == Type.CombineBinary) { // CombineBinary is the input to some other lop (say, L) // InputInfo of L is the ouputInfo of CombineBinary // And, the outputInfo of CombineBinary depends on the operation! CombineBinary combine = (CombineBinary) node; if ( combine.getOperation() == org.apache.sysml.lops.CombineBinary.OperationTypes.PreSort ) { nodeInputInfo = new InputInfo(SequenceFileInputFormat.class, DoubleWritable.class, IntWritable.class); } else if ( combine.getOperation() == org.apache.sysml.lops.CombineBinary.OperationTypes.PreCentralMoment || combine.getOperation() == org.apache.sysml.lops.CombineBinary.OperationTypes.PreCovUnweighted || combine.getOperation() == org.apache.sysml.lops.CombineBinary.OperationTypes.PreGroupedAggUnweighted ) { nodeInputInfo = InputInfo.WeightedPairInputInfo; } } else if ( node.getType() == Type.CombineTernary ) { nodeInputInfo = InputInfo.WeightedPairInputInfo; } inputInfos.add(nodeInputInfo); nodeIndexMapping.put(node, inputStrings.size() - 1); return; } // if exec nodes does not contain node at this point, return. if (!execNodes.contains(node)) return; // process children recursively for ( Lop lop : node.getInputs() ) { getInputPathsAndParameters(lop, execNodes, inputStrings, inputInfos, numRows, numCols, numRowsPerBlock, numColsPerBlock, nodeIndexMapping, inputLabels, inputLops, MRJobLineNumbers); } } /** * Method to find all terminal nodes. * * @param execNodes list of exec nodes * @param rootNodes list of root nodes * @param jt job type */ private static void getOutputNodes(ArrayList<Lop> execNodes, ArrayList<Lop> rootNodes, JobType jt) { for ( Lop node : execNodes ) { // terminal node if (node.getOutputs().isEmpty() && !rootNodes.contains(node)) { rootNodes.add(node); } else { // check for nodes with at least one child outside execnodes int cnt = 0; for (Lop lop : node.getOutputs() ) { cnt += (!execNodes.contains(lop)) ? 1 : 0; } if (cnt > 0 && !rootNodes.contains(node) // not already a rootnode && !(node.getExecLocation() == ExecLocation.Data && ((Data) node).getOperationType() == OperationTypes.READ && ((Data) node).getDataType() == DataType.MATRIX) ) // Not a matrix Data READ { if ( jt.allowsSingleShuffleInstruction() && node.getExecLocation() != ExecLocation.MapAndReduce) continue; if (cnt < node.getOutputs().size()) { if(!node.getProducesIntermediateOutput()) rootNodes.add(node); } else rootNodes.add(node); } } } } /** * check to see if a is the child of b (i.e., there is a directed path from a to b) * * @param a child lop * @param b parent lop * @param IDMap id map * @return true if a child of b */ private static boolean isChild(Lop a, Lop b, HashMap<Long, Integer> IDMap) { int bID = IDMap.get(b.getID()); return a.get_reachable()[bID]; } /** * Method to topologically sort lops * * @param v list of lops */ @SuppressWarnings({ "unchecked", "rawtypes" }) private void doTopologicalSort_strict_order(ArrayList<Lop> v) { //int numNodes = v.size(); /* * Step 1: compute the level for each node in the DAG. Level for each node is * computed as lops are created. So, this step is need not be performed here. * Step 2: sort the nodes by level, and within a level by node ID. */ // Step1: Performed at the time of creating Lops // Step2: sort nodes by level, and then by node ID Lop[] nodearray = v.toArray(new Lop[0]); Arrays.sort(nodearray, new LopComparator()); // Copy sorted nodes into "v" and construct a mapping between Lop IDs and sequence of numbers v.clear(); IDMap.clear(); for (int i = 0; i < nodearray.length; i++) { v.add(nodearray[i]); IDMap.put(v.get(i).getID(), i); } /* * Compute of All-pair reachability graph (Transitive Closure) of the DAG. * - Perform a depth-first search (DFS) from every node $u$ in the DAG * - and construct the list of reachable nodes from the node $u$ * - store the constructed reachability information in $u$.reachable[] boolean array */ // // for (int i = 0; i < nodearray.length; i++) { boolean[] arr = v.get(i).create_reachable(nodearray.length); Arrays.fill(arr, false); dagDFS(v.get(i), arr); } // print the nodes in sorted order if (LOG.isTraceEnabled()) { for ( Lop vnode : v ) { StringBuilder sb = new StringBuilder(); sb.append(vnode.getID()); sb.append("("); sb.append(vnode.getLevel()); sb.append(") "); sb.append(vnode.getType()); sb.append("("); for(Lop vin : vnode.getInputs()) { sb.append(vin.getID()); sb.append(","); } sb.append("), "); LOG.trace(sb.toString()); } LOG.trace("topological sort -- done"); } } /** * Method to perform depth-first traversal from a given node in the DAG. * Store the reachability information in marked[] boolean array. * * @param root low-level operator * @param marked reachability results */ private void dagDFS(Lop root, boolean[] marked) { //contains check currently required for globalopt, will be removed when cleaned up if( !IDMap.containsKey(root.getID()) ) return; int mapID = IDMap.get(root.getID()); if ( marked[mapID] ) return; marked[mapID] = true; for( Lop lop : root.getOutputs() ) { dagDFS(lop, marked); } } private static boolean hasDirectChildNode(Lop node, ArrayList<Lop> childNodes) { if ( childNodes.isEmpty() ) return false; for( Lop cnode : childNodes ) { if ( cnode.getOutputs().contains(node)) return true; } return false; } private boolean hasChildNode(Lop node, ArrayList<Lop> nodes) { return hasChildNode(node, nodes, ExecLocation.INVALID); } private boolean hasChildNode(Lop node, ArrayList<Lop> childNodes, ExecLocation type) { if ( childNodes.isEmpty() ) return false; int index = IDMap.get(node.getID()); for( Lop cnode : childNodes ) { if ( (type == ExecLocation.INVALID || cnode.getExecLocation() == type) && cnode.get_reachable()[index]) return true; } return false; } private Lop getChildNode(Lop node, ArrayList<Lop> childNodes, ExecLocation type) { if ( childNodes.isEmpty() ) return null; int index = IDMap.get(node.getID()); for( Lop cnode : childNodes ) { if ( cnode.getExecLocation() == type && cnode.get_reachable()[index]) return cnode; } return null; } /* * Returns a node "n" such that * 1) n \in parentNodes * 2) n is an ancestor of "node" * 3) n.ExecLocation = type * * Returns null if no such "n" exists * */ private Lop getParentNode(Lop node, ArrayList<Lop> parentNodes, ExecLocation type) { if ( parentNodes.isEmpty() ) return null; for( Lop pn : parentNodes ) { int index = IDMap.get( pn.getID() ); if ( pn.getExecLocation() == type && node.get_reachable()[index]) return pn; } return null; } // Checks if "node" has any descendants in nodesVec with definedMRJob flag // set to true private boolean hasMRJobChildNode(Lop node, ArrayList<Lop> nodesVec) { if ( nodesVec.isEmpty() ) return false; int index = IDMap.get(node.getID()); for( Lop n : nodesVec ) { if ( n.definesMRJob() && n.get_reachable()[index]) return true; } return false; } private boolean checkDataGenAsChildNode(Lop node, ArrayList<Lop> nodesVec) { if( nodesVec.isEmpty() ) return true; int index = IDMap.get(node.getID()); boolean onlyDatagen = true; for( Lop n : nodesVec ) { if ( n.definesMRJob() && n.get_reachable()[index] && JobType.findJobTypeFromLop(n) != JobType.DATAGEN ) onlyDatagen = false; } // return true also when there is no lop in "nodesVec" that defines a MR job. return onlyDatagen; } private static int getChildAlignment(Lop node, ArrayList<Lop> execNodes, ExecLocation type) { for (Lop n : node.getInputs() ) { if (!execNodes.contains(n)) continue; if (execNodes.contains(n) && n.getExecLocation() == type) { if (n.getBreaksAlignment()) return MR_CHILD_FOUND_BREAKS_ALIGNMENT; else return MR_CHILD_FOUND_DOES_NOT_BREAK_ALIGNMENT; } else { int ret = getChildAlignment(n, execNodes, type); if (ret == MR_CHILD_FOUND_DOES_NOT_BREAK_ALIGNMENT || ret == CHILD_DOES_NOT_BREAK_ALIGNMENT) { if (n.getBreaksAlignment()) return CHILD_BREAKS_ALIGNMENT; else return CHILD_DOES_NOT_BREAK_ALIGNMENT; } else if (ret == MRCHILD_NOT_FOUND || ret == CHILD_BREAKS_ALIGNMENT || ret == MR_CHILD_FOUND_BREAKS_ALIGNMENT) return ret; else throw new RuntimeException("Something wrong in getChildAlignment()."); } } return MRCHILD_NOT_FOUND; } private boolean hasParentNode(Lop node, ArrayList<Lop> parentNodes) { if ( parentNodes.isEmpty() ) return false; for( Lop pnode : parentNodes ) { int index = IDMap.get( pnode.getID() ); if ( node.get_reachable()[index]) return true; } return false; } }
Java
package com.iservport.et.service; import java.nio.charset.Charset; import org.apache.commons.codec.binary.Base64; import org.springframework.http.HttpHeaders; import org.springframework.web.util.UriComponentsBuilder; /** * Base class to Enterprise tester API calls. * * @author mauriciofernandesdecastro */ public class AbstractETApiService { private String scheme = "http"; private String host = "et2.primecontrol.com.br"; private int port = 8807; private String app = "/EnterpriseTester"; protected final UriComponentsBuilder getApiUriBuilder() { return UriComponentsBuilder.newInstance().scheme(scheme).host(host).port(port).path(app); } /** * Basic headers (for testing). * * @param username * @param password */ @SuppressWarnings("serial") protected HttpHeaders createHeaders(final String username, final String password ){ return new HttpHeaders(){ { String auth = username + ":" + password; byte[] encodedAuth = Base64.encodeBase64( auth.getBytes(Charset.forName("US-ASCII")) ); String authHeader = "Basic " + new String( encodedAuth ); set( "Authorization", authHeader ); } }; } }
Java
from artnet import * import SocketServer import time, os, random, datetime, sys import argparse import socket import struct from subprocess import Popen, PIPE, STDOUT import glob DEBUG = False UDP_IP = "2.0.0.61" UDP_PORT = 6454
Java
/** * Created by dmitry on 21.11.16. */ import React, { Component } from 'react'; import { Container, Content, Spinner } from 'native-base'; // TODO: Рядом лежат спиннеры, поди можно прикрячить export default class Loading extends Component { render() { return ( <Container> <Content contentContainerStyle={{ flex: 1, flexDirection: 'row', justifyContent: 'center' }}> <Spinner color="blue"/> </Content> </Container> ); } }
Java
=head1 LICENSE Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute 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. =cut =head1 NAME Bio::Tools::Run::Search::sge_wublastp - SGE BLASTP searches =head1 SYNOPSIS see Bio::Tools::Run::Search::SGE_WuBlast see Bio::Tools::Run::Search::wublastp =head1 DESCRIPTION Multiple inheretance object combining Bio::Tools::Run::Search::SGE_WuBlast and Bio::Tools::Run::Search::wublastp =cut # Let the code begin... package Bio::Tools::Run::Search::sge_wublastp; use strict; use vars qw( @ISA ); use Bio::Tools::Run::Search::SGE_WuBlast; use Bio::Tools::Run::Search::wublastp; @ISA = qw( Bio::Tools::Run::Search::SGE_WuBlast Bio::Tools::Run::Search::wublastp ); BEGIN{ } # Nastyness to get round multiple inheretance problems. sub program_name{return Bio::Tools::Run::Search::wublastp::program_name(@_)} sub algorithm {return Bio::Tools::Run::Search::wublastp::algorithm(@_)} sub version {return Bio::Tools::Run::Search::wublastp::version(@_)} sub parameter_options{ return Bio::Tools::Run::Search::wublastp::parameter_options(@_) } #---------------------------------------------------------------------- 1;
Java
/* * Copyright 2017 GcsSloop * * 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. * * Last modified 2017-03-08 01:01:18 * * GitHub: https://github.com/GcsSloop * Website: http://www.gcssloop.com * Weibo: http://weibo.com/GcsSloop */ package com.github.florent37.expectanim.core.position; import android.view.View; /** * Created by florentchampigny on 17/02/2017. */ public class PositionAnimExpectationRightOf extends PositionAnimationViewDependant { public PositionAnimExpectationRightOf(View otherView) { super(otherView); setForPositionX(true); } @Override public Float getCalculatedValueX(View viewToMove) { return viewCalculator.finalPositionRightOfView(otherView) + getMargin(viewToMove); } @Override public Float getCalculatedValueY(View viewToMove) { return null; } }
Java
/* * Copyright 2007 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.jsefa.common.converter; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Enum constant annotation. * * @author Norman Lahme-Huetig * */ @Retention(RUNTIME) @Target({FIELD}) public @interface EnumConstant { /** * The display name of the enum constant. */ String value(); }
Java