repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
mechanicalobject/sandbox
MechanicalObject.Sandbox.TodoWithSQLite/MechanicalObject.Sandbox.TodoWithSQLite.Tests/Properties/AssemblyInfo.cs
1466
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MechanicalObject.Sandbox.TodoWithSQLite.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MechanicalObject.Sandbox.TodoWithSQLite.Tests")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a67aa212-6e71-4894-af9b-b96619dd2c84")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
eval1749/elang
elang/vm/collectable.cc
647
// Copyright 2014-2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "elang/vm/collectable.h" #include "base/logging.h" #include "elang/vm/factory.h" namespace elang { namespace vm { void Collectable::operator delete(void* pointer, Factory* factory) { __assume(pointer); __assume(factory); NOTREACHED(); } void* Collectable::operator new(size_t size, Factory* factory) { return factory->NewDataBlob(size); } Collectable::Collectable() { } Collectable::~Collectable() { NOTREACHED(); } } // namespace vm } // namespace elang
apache-2.0
NotFound403/WePay
src/main/java/cn/felord/wepay/ali/sdk/api/response/AlipayOfflineProviderUseractionRecordResponse.java
384
package cn.felord.wepay.ali.sdk.api.response; import cn.felord.wepay.ali.sdk.api.AlipayResponse; /** * ALIPAY API: alipay.offline.provider.useraction.record response. * * @author auto create * @version $Id: $Id */ public class AlipayOfflineProviderUseractionRecordResponse extends AlipayResponse { private static final long serialVersionUID = 1337192588328586596L; }
apache-2.0
fupslot/linkmator
client/js/component/Sidebar.js
787
import React from 'react'; import { connect } from 'react-redux'; import PersonAvatar from './PersonAvatar'; class Sidebar extends React.Component { renderPersonAvatar() { if (!this.props.person) { return null; } const person = this.props.person; const fullName = `${person.givenName} ${person.surname}`; return ( <PersonAvatar fullName={fullName} gravatarUrl={person.gravatarUrl} /> ); } render() { return ( <section className="Sidebar"> { this.renderPersonAvatar() } </section> ); } } Sidebar.propTypes = { person: React.PropTypes.object }; const mapStateToProps = (state) => { return { person: state.feed.person }; }; export default connect( mapStateToProps, {} )(Sidebar);
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/ListCACertificatesResult.java
6594
/* * 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.iot.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * The output from the ListCACertificates operation. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListCACertificatesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The CA certificates registered in your AWS account. * </p> */ private java.util.List<CACertificate> certificates; /** * <p> * The current position within the list of CA certificates. * </p> */ private String nextMarker; /** * <p> * The CA certificates registered in your AWS account. * </p> * * @return The CA certificates registered in your AWS account. */ public java.util.List<CACertificate> getCertificates() { return certificates; } /** * <p> * The CA certificates registered in your AWS account. * </p> * * @param certificates * The CA certificates registered in your AWS account. */ public void setCertificates(java.util.Collection<CACertificate> certificates) { if (certificates == null) { this.certificates = null; return; } this.certificates = new java.util.ArrayList<CACertificate>(certificates); } /** * <p> * The CA certificates registered in your AWS account. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setCertificates(java.util.Collection)} or {@link #withCertificates(java.util.Collection)} if you want to * override the existing values. * </p> * * @param certificates * The CA certificates registered in your AWS account. * @return Returns a reference to this object so that method calls can be chained together. */ public ListCACertificatesResult withCertificates(CACertificate... certificates) { if (this.certificates == null) { setCertificates(new java.util.ArrayList<CACertificate>(certificates.length)); } for (CACertificate ele : certificates) { this.certificates.add(ele); } return this; } /** * <p> * The CA certificates registered in your AWS account. * </p> * * @param certificates * The CA certificates registered in your AWS account. * @return Returns a reference to this object so that method calls can be chained together. */ public ListCACertificatesResult withCertificates(java.util.Collection<CACertificate> certificates) { setCertificates(certificates); return this; } /** * <p> * The current position within the list of CA certificates. * </p> * * @param nextMarker * The current position within the list of CA certificates. */ public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } /** * <p> * The current position within the list of CA certificates. * </p> * * @return The current position within the list of CA certificates. */ public String getNextMarker() { return this.nextMarker; } /** * <p> * The current position within the list of CA certificates. * </p> * * @param nextMarker * The current position within the list of CA certificates. * @return Returns a reference to this object so that method calls can be chained together. */ public ListCACertificatesResult withNextMarker(String nextMarker) { setNextMarker(nextMarker); 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 (getCertificates() != null) sb.append("Certificates: ").append(getCertificates()).append(","); if (getNextMarker() != null) sb.append("NextMarker: ").append(getNextMarker()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListCACertificatesResult == false) return false; ListCACertificatesResult other = (ListCACertificatesResult) obj; if (other.getCertificates() == null ^ this.getCertificates() == null) return false; if (other.getCertificates() != null && other.getCertificates().equals(this.getCertificates()) == false) return false; if (other.getNextMarker() == null ^ this.getNextMarker() == null) return false; if (other.getNextMarker() != null && other.getNextMarker().equals(this.getNextMarker()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getCertificates() == null) ? 0 : getCertificates().hashCode()); hashCode = prime * hashCode + ((getNextMarker() == null) ? 0 : getNextMarker().hashCode()); return hashCode; } @Override public ListCACertificatesResult clone() { try { return (ListCACertificatesResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
dirk-thomas/vcstool
vcstool/clients/hg.py
11970
import os from shutil import which from threading import Lock from vcstool.executor import USE_COLOR from .vcs_base import VcsClientBase from ..util import rmtree class HgClient(VcsClientBase): type = 'hg' _executable = None _config_color = None _config_color_lock = Lock() @staticmethod def is_repository(path): return os.path.isdir(os.path.join(path, '.hg')) def __init__(self, path): super(HgClient, self).__init__(path) def branch(self, command): self._check_executable() cmd = [HgClient._executable, 'branches' if command.all else 'branch'] self._check_color(cmd) return self._run_command(cmd) def custom(self, command): self._check_executable() cmd = [HgClient._executable] + command.args return self._run_command(cmd) def diff(self, command): self._check_executable() cmd = [HgClient._executable, 'diff'] self._check_color(cmd) if command.context: cmd += ['--unified %d' % command.context] return self._run_command(cmd) def export(self, command): self._check_executable() result_url = self._get_url() if result_url['returncode']: return result_url url = result_url['output'] cmd_id = [HgClient._executable, 'identify', '--id'] result_id = self._run_command(cmd_id) if result_id['returncode']: result_id['output'] = \ 'Could not determine id: ' + result_id['output'] return result_id id_ = result_id['output'] if not command.exact: cmd_branch = [HgClient._executable, 'identify', '--branch'] result_branch = self._run_command(cmd_branch) if result_branch['returncode']: result_branch['output'] = \ 'Could not determine branch: ' + result_branch['output'] return result_branch branch = result_branch['output'] cmd_branch_id = [ HgClient._executable, 'identify', '-r', branch, '--id'] result_branch_id = self._run_command(cmd_branch_id) if result_branch_id['returncode']: result_branch_id['output'] = \ 'Could not determine branch id: ' + \ result_branch_id['output'] return result_branch_id if result_branch_id['output'] == id_: id_ = branch cmd_branch = cmd_branch_id return { 'cmd': '%s && %s' % (result_url['cmd'], ' '.join(cmd_id)), 'cwd': self.path, 'output': '\n'.join([url, id_]), 'returncode': 0, 'export_data': {'url': url, 'version': id_} } def _get_url(self): cmd_url = [HgClient._executable, 'paths', 'default'] result_url = self._run_command(cmd_url) if result_url['returncode']: result_url['output'] = \ 'Could not determine url: ' + result_url['output'] return result_url return result_url def import_(self, command): if not command.url or not command.version: if not command.url and not command.version: value_missing = "'url' and 'version'" elif not command.url: value_missing = "'url'" else: value_missing = "'version'" return { 'cmd': '', 'cwd': self.path, 'output': 'Repository data lacks the %s value' % value_missing, 'returncode': 1 } self._check_executable() if HgClient.is_repository(self.path): # verify that existing repository is the same result_url = self._get_url() if result_url['returncode']: return result_url url = result_url['output'] if url != command.url: if not command.force: return { 'cmd': '', 'cwd': self.path, 'output': 'Path already exists and contains a different ' 'repository', 'returncode': 1 } try: rmtree(self.path) except OSError: os.remove(self.path) not_exist = self._create_path() if not_exist: return not_exist if HgClient.is_repository(self.path): # pull updates for existing repo cmd_pull = [ HgClient._executable, '--noninteractive', 'pull', '--update'] result_pull = self._run_command(cmd_pull, retry=command.retry) if result_pull['returncode']: return result_pull cmd = result_pull['cmd'] output = result_pull['output'] else: cmd_clone = [ HgClient._executable, '--noninteractive', 'clone', command.url, '.'] result_clone = self._run_command(cmd_clone, retry=command.retry) if result_clone['returncode']: result_clone['output'] = \ "Could not clone repository '%s': %s" % \ (command.url, result_clone['output']) return result_clone cmd = result_clone['cmd'] output = result_clone['output'] if command.version: cmd_checkout = [ HgClient._executable, '--noninteractive', 'checkout', command.version] result_checkout = self._run_command(cmd_checkout) if result_checkout['returncode']: result_checkout['output'] = \ "Could not checkout '%s': %s" % \ (command.version, result_checkout['output']) return result_checkout cmd += ' && ' + ' '.join(cmd_checkout) output = '\n'.join([output, result_checkout['output']]) return { 'cmd': cmd, 'cwd': self.path, 'output': output, 'returncode': 0 } def log(self, command): self._check_executable() if command.limit_tag: # check if specific tag exists cmd_log = [ HgClient._executable, 'log', '--rev', 'tag(%s)' % command.limit_tag] result_log = self._run_command(cmd_log) if result_log['returncode']: return { 'cmd': '', 'cwd': self.path, 'output': "Repository lacks the tag '%s'" % command.limit_tag, 'returncode': 1 } # output log since specific tag cmd = [ HgClient._executable, 'log', '--rev', 'sort(tag(%s)::, -rev) and not tag (%s)' % (command.limit_tag, command.limit_tag)] elif command.limit_untagged: # determine distance to nearest tag cmd_log = [ HgClient._executable, 'log', '--rev', '.', '--template', '{latesttagdistance}'] result_log = self._run_command(cmd_log) if result_log['returncode']: return result_log # output log since nearest tag cmd = [ HgClient._executable, 'log', '--limit', result_log['output'], '-b', '.'] else: cmd = [HgClient._executable, 'log'] if command.limit != 0: cmd += ['--limit', '%d' % command.limit] if command.verbose: cmd += ['--verbose'] self._check_color(cmd) return self._run_command(cmd) def pull(self, _command): self._check_executable() cmd = [HgClient._executable, '--noninteractive', 'pull', '--update'] self._check_color(cmd) return self._run_command(cmd) def push(self, _command): self._check_executable() cmd = [HgClient._executable, '--noninteractive', 'push'] return self._run_command(cmd) def remotes(self, _command): self._check_executable() cmd = [HgClient._executable, 'paths'] return self._run_command(cmd) def status(self, command): self._check_executable() cmd = [HgClient._executable, 'status'] self._check_color(cmd) if command.quiet: cmd += ['--untracked-files=no'] return self._run_command(cmd) def validate(self, command): if not command.url: return { 'cmd': '', 'cwd': self.path, 'output': "Repository data lacks the 'url' value", 'returncode': 1 } self._check_executable() cmd_id_repo = [ HgClient._executable, '--noninteractive', 'identify', command.url] result_id_repo = self._run_command( cmd_id_repo, retry=command.retry) if result_id_repo['returncode']: result_id_repo['output'] = \ "Failed to contact remote repository '%s': %s" % \ (command.url, result_id_repo['output']) return result_id_repo if command.version: cmd_id_ver = [ HgClient._executable, '--noninteractive', 'identify', '-r', command.version, command.url] result_id_ver = self._run_command( cmd_id_ver, retry=command.retry) if result_id_ver['returncode']: result_id_ver['output'] = \ 'Specified version not found on remote repository ' + \ "'%s':'%s' : %s" % \ (command.url, command.version, result_id_ver['output']) return result_id_ver cmd = result_id_ver['cmd'] output = "Found hg repository '%s' with changeset '%s'" % \ (command.url, command.version) else: cmd = result_id_repo['cmd'] output = "Found hg repository '%s' with default branch" % \ command.url return { 'cmd': cmd, 'cwd': self.path, 'output': output, 'returncode': None } def _check_color(self, cmd): if not USE_COLOR: return with HgClient._config_color_lock: # check if user uses colorization if HgClient._config_color is None: HgClient._config_color = False # check if config extension is available _cmd = [HgClient._executable, 'config', '--help'] result = self._run_command(_cmd) if result['returncode']: return # check if color extension is available and not disabled _cmd = [HgClient._executable, 'config', 'extensions.color'] result = self._run_command(_cmd) if result['returncode'] or result['output'].startswith('!'): return # check if color mode is not off or not set _cmd = [HgClient._executable, 'config', 'color.mode'] result = self._run_command(_cmd) if not result['returncode'] and result['output'] == 'off': return HgClient._config_color = True # inject arguments to force colorization if HgClient._config_color: cmd[1:1] = '--color', 'always' def _check_executable(self): assert HgClient._executable is not None, \ "Could not find 'hg' executable" if not HgClient._executable: HgClient._executable = which('hg')
apache-2.0
locationtech/geomesa
geomesa-cassandra/geomesa-cassandra-datastore/src/main/scala/org/locationtech/geomesa/cassandra/data/CassandraDataStore.scala
6127
/*********************************************************************** * Copyright (c) 2017-2022 IBM * Copyright (c) 2013-2022 Commonwealth Computer Research, Inc. * 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.opensource.org/licenses/apache2.0.php. ***********************************************************************/ package org.locationtech.geomesa.cassandra.data import com.datastax.driver.core._ import org.geotools.data.Query import org.locationtech.geomesa.cassandra.data.CassandraDataStoreFactory.CassandraDataStoreConfig import org.locationtech.geomesa.index.geotools.GeoMesaDataStore import org.locationtech.geomesa.index.index.attribute.AttributeIndex import org.locationtech.geomesa.index.index.id.IdIndex import org.locationtech.geomesa.index.index.z2.{XZ2Index, Z2Index} import org.locationtech.geomesa.index.index.z3.{XZ3Index, Z3Index} import org.locationtech.geomesa.index.metadata.{GeoMesaMetadata, MetadataStringSerializer} import org.locationtech.geomesa.index.stats.{GeoMesaStats, RunnableStats} import org.locationtech.geomesa.index.utils.{Explainer, LocalLocking} import org.locationtech.geomesa.utils.conf.IndexId import org.locationtech.geomesa.utils.geotools.SimpleFeatureTypes import org.locationtech.geomesa.utils.geotools.SimpleFeatureTypes.AttributeOptions import org.locationtech.geomesa.utils.geotools.converters.FastConverter import org.locationtech.geomesa.utils.stats.IndexCoverage import org.opengis.feature.simple.SimpleFeatureType class CassandraDataStore(val session: Session, config: CassandraDataStoreConfig) extends GeoMesaDataStore[CassandraDataStore](config) with LocalLocking { import org.locationtech.geomesa.utils.geotools.RichSimpleFeatureType.RichSimpleFeatureType import scala.collection.JavaConverters._ override val metadata: GeoMesaMetadata[String] = new CassandraBackedMetadata(session, config.catalog, MetadataStringSerializer) override val adapter: CassandraIndexAdapter = new CassandraIndexAdapter(this) override val stats: GeoMesaStats = new RunnableStats(this) override def getQueryPlan(query: Query, index: Option[String], explainer: Explainer): Seq[CassandraQueryPlan] = super.getQueryPlan(query, index, explainer).asInstanceOf[Seq[CassandraQueryPlan]] override def delete(): Unit = { val tables = getTypeNames.flatMap(getAllIndexTableNames) (tables.distinct :+ config.catalog).par.foreach { table => session.execute(s"drop table $table") } } override protected def preSchemaUpdate(sft: SimpleFeatureType, previous: SimpleFeatureType): Unit = { val rename = sft.getUserData.remove(SimpleFeatureTypes.Configs.UpdateRenameTables) if (FastConverter.convert(rename, classOf[java.lang.Boolean]) == java.lang.Boolean.TRUE) { logger.warn("Cassandra does not support renaming tables - disabling rename option") } sft.getUserData.put(SimpleFeatureTypes.Configs.UpdateRenameTables, java.lang.Boolean.FALSE) super.preSchemaUpdate(sft, previous) } override protected def transitionIndices(sft: SimpleFeatureType): Unit = { val dtg = sft.getDtgField.toSeq val geom = Option(sft.getGeomField).toSeq val indices = Seq.newBuilder[IndexId] val tableNameKeys = Seq.newBuilder[(String, String)] sft.getIndices.foreach { case id if id.name == IdIndex.name => require(id.version == 1, s"Expected index version of 1 but got: $id") indices += id.copy(version = 3) tableNameKeys += ((s"table.${IdIndex.name}.v1", s"table.${IdIndex.name}.v3")) case id if id.name == Z3Index.name => require(id.version <= 2, s"Expected index version of 1 or 2 but got: $id") indices += id.copy(attributes = geom ++ dtg, version = id.version + 3) tableNameKeys += ((s"table.${Z3Index.name}.v${id.version}", s"table.${Z3Index.name}.v${id.version + 3}")) case id if id.name == XZ3Index.name => require(id.version == 1, s"Expected index version of 1 but got: $id") indices += id.copy(attributes = geom ++ dtg) case id if id.name == Z2Index.name => require(id.version <= 2, s"Expected index version of 1 or 2 but got: $id") indices += id.copy(attributes = geom, version = id.version + 2) tableNameKeys += ((s"table.${Z2Index.name}.v${id.version}", s"table.${Z2Index.name}.v${id.version + 2}")) case id if id.name == XZ2Index.name => require(id.version == 1, s"Expected index version of 1 but got: $id") indices += id.copy(attributes = geom) case id if id.name == AttributeIndex.name => require(id.version <= 2, s"Expected index version of 1 or 2 but got: $id") val fields = geom ++ dtg sft.getAttributeDescriptors.asScala.foreach { d => val index = d.getUserData.remove(AttributeOptions.OptIndex).asInstanceOf[String] if (index == null || index.equalsIgnoreCase("false") || index.equalsIgnoreCase(IndexCoverage.NONE.toString)) { // no-op } else if (java.lang.Boolean.valueOf(index) || index.equalsIgnoreCase(IndexCoverage.FULL.toString) || index.equalsIgnoreCase(IndexCoverage.JOIN.toString)) { indices += id.copy(attributes = Seq(d.getLocalName) ++ fields, version = id.version + 4) } else { throw new IllegalStateException(s"Expected an index coverage or boolean but got: $index") } } tableNameKeys ++= Seq(s"table.${AttributeIndex.name}.v${id.version}", "tables.idx.attr.name") .map((_, s"table.${AttributeIndex.name}.v${id.version + 4}")) } sft.setIndices(indices.result) // update metadata keys for tables tableNameKeys.result.foreach { case (from, to) => metadata.scan(sft.getTypeName, from, cache = false).foreach { case (key, name) => metadata.insert(sft.getTypeName, to + key.substring(from.length), name) metadata.remove(sft.getTypeName, key) } } } }
apache-2.0
leandrocr/kops
util/pkg/vfs/s3context.go
6363
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package vfs import ( "fmt" "os" "sync" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/s3" "github.com/golang/glog" ) type S3Context struct { mutex sync.Mutex clients map[string]*s3.S3 bucketLocations map[string]string getClient func(region string) (*s3.S3, error) } func NewS3Context() *S3Context { return &S3Context{ clients: make(map[string]*s3.S3), bucketLocations: make(map[string]string), } } func (s *S3Context) getDefaultClient(region string) (*s3.S3, error) { s.mutex.Lock() defer s.mutex.Unlock() s3Client := s.clients[region] if s3Client == nil { config := aws.NewConfig().WithRegion(region) config = config.WithCredentialsChainVerboseErrors(true) session := session.New() s3Client = s3.New(session, config) } s.clients[region] = s3Client return s3Client, nil } func (s *S3Context) getEndpointClient(region string) (*s3.S3, error) { s.mutex.Lock() defer s.mutex.Unlock() s3Client := s.clients[region] if s3Client == nil { Endpoint := os.Getenv("S3_ENDPOINT") if Endpoint == "" { return nil, fmt.Errorf("S3_ENDPOINT is required") } AccessKeyID := os.Getenv("S3_ACCESS_KEY_ID") if AccessKeyID == "" { return nil, fmt.Errorf("S3_ACCESS_KEY_ID cannot be empty when S3_ENDPOINT is not empty") } SecretAccessKey := os.Getenv("S3_SECRET_ACCESS_KEY") if SecretAccessKey == "" { return nil, fmt.Errorf("S3_SECRET_ACCESS_KEY cannot be empty when S3_ENDPOINT is not empty") } s3Config := &aws.Config{ Credentials: credentials.NewStaticCredentials(AccessKeyID, SecretAccessKey, ""), Endpoint: aws.String(Endpoint), Region: aws.String(region), DisableSSL: aws.Bool(true), S3ForcePathStyle: aws.Bool(true), } session := session.New() s3Client = s3.New(session, s3Config) s.clients[region] = s3Client } return s3Client, nil } func (s *S3Context) setClientFunc() { Endpoint := os.Getenv("S3_ENDPOINT") if Endpoint == "" { s.getClient = s.getDefaultClient } else { s.getClient = s.getEndpointClient } } func (s *S3Context) getRegionForBucket(bucket string) (string, error) { region := func() string { s.mutex.Lock() defer s.mutex.Unlock() return s.bucketLocations[bucket] }() if region != "" { return region, nil } // Probe to find correct region for bucket awsRegion := os.Getenv("AWS_REGION") if awsRegion == "" { awsRegion = "us-east-1" } if err := validateRegion(awsRegion); err != nil { return "", err } request := &s3.GetBucketLocationInput{ Bucket: &bucket, } var response *s3.GetBucketLocationOutput s3Client, err := s.getClient(awsRegion) // Attempt one GetBucketLocation call the "normal" way (i.e. as the bucket owner) response, err = s3Client.GetBucketLocation(request) // and fallback to brute-forcing if it fails if err != nil { glog.V(2).Infof("unable to get bucket location from region %q; scanning all regions: %v", awsRegion, err) response, err = bruteforceBucketLocation(&awsRegion, request) } if err != nil { return "", err } if response.LocationConstraint == nil { // US Classic does not return a region region = "us-east-1" } else { region = *response.LocationConstraint // Another special case: "EU" can mean eu-west-1 if region == "EU" { region = "eu-west-1" } } glog.V(2).Infof("Found bucket %q in region %q", bucket, region) s.mutex.Lock() defer s.mutex.Unlock() s.bucketLocations[bucket] = region return region, nil } /* Amazon's S3 API provides the GetBucketLocation call to determine the region in which a bucket is located. This call can however only be used globally by the owner of the bucket, as mentioned on the documentation page. For S3 buckets that are shared across multiple AWS accounts using bucket policies the call will only work if it is sent to the correct region in the first place. This method will attempt to "bruteforce" the bucket location by sending a request to every available region and picking out the first result. See also: https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLocationRequest */ func bruteforceBucketLocation(region *string, request *s3.GetBucketLocationInput) (*s3.GetBucketLocationOutput, error) { session, _ := session.NewSession(&aws.Config{Region: region}) regions, err := ec2.New(session).DescribeRegions(nil) if err != nil { return nil, fmt.Errorf("Unable to list AWS regions: %v", err) } glog.V(2).Infof("Querying S3 for bucket location for %s", *request.Bucket) out := make(chan *s3.GetBucketLocationOutput, len(regions.Regions)) for _, region := range regions.Regions { go func(regionName string) { glog.V(8).Infof("Doing GetBucketLocation in %q", regionName) s3Client := s3.New(session, &aws.Config{Region: aws.String(regionName)}) result, bucketError := s3Client.GetBucketLocation(request) if bucketError == nil { glog.V(8).Infof("GetBucketLocation succeeded in %q", regionName) out <- result } }(*region.RegionName) } select { case bucketLocation := <-out: return bucketLocation, nil case <-time.After(5 * time.Second): return nil, fmt.Errorf("Could not retrieve location for AWS bucket %s", *request.Bucket) } } func validateRegion(region string) error { resolver := endpoints.DefaultResolver() partitions := resolver.(endpoints.EnumPartitions).Partitions() for _, p := range partitions { for _, r := range p.Regions() { if r.ID() == region { return nil } } } return fmt.Errorf("%s is not a valid region\nPlease check that your region is formatted correctly (i.e. us-east-1)", region) }
apache-2.0
GDXN/CoActionOS-Public
CoActionOS-Applib/src/CoActionOS/Signal.cpp
389
/* * Signal.cpp * * Created on: Dec 6, 2013 * Author: tgil */ #include "Signal.hpp" using namespace Signal; int Event::set_handler(Handler * handler) const { if( handler->sigaction()->sa_flags & SA_SIGINFO ){ return ::sigaction(signo_, handler->sigaction(), 0); } else { _sig_func_ptr ptr = handler->sigaction()->sa_handler; ::signal(signo_, ptr); return 0; } }
apache-2.0
tilioteo/vmaps
src/main/java/org/vaadin/maps/client/geometry/wkb/WKBConstants.java
1578
package org.vaadin.maps.client.geometry.wkb; /* * The JTS Topology Suite is a collection of Java classes that * implement the fundamental operations required to validate a given * geo-spatial data set to a known topological specification. * * Copyright (C) 2001 Vivid Solutions * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ /** * Constant values used by the WKB format */ public interface WKBConstants { int wkbXDR = 0; int wkbNDR = 1; int wkbPoint = 1; int wkbLineString = 2; int wkbPolygon = 3; int wkbMultiPoint = 4; int wkbMultiLineString = 5; int wkbMultiPolygon = 6; int wkbGeometryCollection = 7; }
apache-2.0
leepc12/BigDataScript
src/org/bds/data/DataS3.java
9312
package org.bds.data; import java.io.File; import java.io.FileOutputStream; import java.sql.Date; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.bds.Config; import org.bds.util.Gpr; import org.bds.util.Timer; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.AmazonS3URI; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.ListObjectsRequest; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectInputStream; import com.amazonaws.services.s3.model.S3ObjectSummary; /** * A bucket / object in AWS S3 * * @author pcingola */ public class DataS3 extends DataRemote { private static int BUFFER_SIZE = 100 * 1024; public static final String DEFAULT_AWS_REGION = Regions.US_EAST_1.toString(); public static final String AWS_DOMAIN = "amazonaws.com"; public static final String AWS_S3_PREFIX = "s3"; public static final String AWS_S3_PROTOCOL = "s3://"; private static Map<Region, AmazonS3> s3ByRegion = new HashMap<>(); AmazonS3URI s3uri; Region region; String bucketName; String key; public DataS3(String urlStr) { super(); parse(urlStr); canWrite = false; } @Override public boolean delete() { if (!isFile()) return false; // Do not delete bucket getS3().deleteObject(bucketName, key); return true; } @Override public void deleteOnExit() { if (verbose) Timer.showStdErr("Cannot delete file '" + this + "'"); } /** * Download a file */ @Override public boolean download(String localFile) { try { if (!isFile()) return false; S3Object s3object = getS3().getObject(new GetObjectRequest(bucketName, key)); if (verbose) System.out.println("Downloading '" + this + "'"); updateInfo(s3object); // Create local file mkdirsLocal(localFile); FileOutputStream os = new FileOutputStream(getLocalPath()); // Copy S3 object to file S3ObjectInputStream is = s3object.getObjectContent(); int count = 0, total = 0, lastShown = 0; byte data[] = new byte[BUFFER_SIZE]; while ((count = is.read(data, 0, BUFFER_SIZE)) != -1) { os.write(data, 0, count); total += count; if (verbose) { // Show every MB if ((total - lastShown) > (1024 * 1024)) { System.err.print("."); lastShown = total; } } } if (verbose) System.err.println(""); // Close streams is.close(); os.close(); if (verbose) Timer.showStdErr("Donwload finished. Total " + total + " bytes."); // Update last modified info updateLocalFileLastModified(); return true; } catch (Exception e) { Timer.showStdErr("ERROR while downloading " + this); throw new RuntimeException(e); } } /** * Does the directory exist? */ protected boolean existsDir() { ObjectListing objectListing = getS3().listObjects( // new ListObjectsRequest() // .withBucketName(bucketName) // .withPrefix(key) // .withMaxKeys(1) // We only need one to check for existence ); // Are there more than zero objects? return objectListing.getObjectSummaries().size() > 0; } public String getBucket() { return bucketName; } @Override public String getAbsolutePath() { return s3uri.toString(); } public String getKey() { return key; } @Override public String getName() { if (key == null) return ""; int idx = key.lastIndexOf('/'); if (idx >= 0) return key.substring(idx + 1); return key; } @Override public String getParent() { if (key == null) return AWS_S3_PROTOCOL + bucketName; String cp = getAbsolutePath(); int idx = cp.lastIndexOf('/'); if (idx >= 0) return cp.substring(0, idx); return AWS_S3_PROTOCOL + bucketName; } @Override public String getPath() { return bucketName + "/" + key; } public Region getRegion() { return region; } /** * Create an S3 client. * S3 clients are thread safe, thus it is encouraged to have * only one client instead of instantiating one each time. */ protected AmazonS3 getS3() { AmazonS3 s3 = s3ByRegion.get(region); if (s3 == null) { // Create singleton in a thread safe way synchronized (s3ByRegion) { if (s3ByRegion.get(region) == null) { // Create client s3 = new AmazonS3Client(); if (region != null) s3.setRegion(region); s3ByRegion.put(region, s3); } } } return s3; } /** * Is this a bucket? */ @Override public boolean isDirectory() { return (key == null || key.endsWith("/")); } @Override public boolean isFile() { return !isDirectory(); } @Override public ArrayList<String> list() { ArrayList<String> list = new ArrayList<>(); // Files are not supposed to have a 'directory' result if (isFile()) return list; ObjectListing objectListing = getS3().listObjects( // new ListObjectsRequest()// .withBucketName(bucketName)// .withPrefix(key) // ); int keyLen = key.length(); for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) { String fileName = objectSummary.getKey(); if (fileName.length() > keyLen) fileName = fileName.substring(keyLen); // First part is not expected in list (only the file name, no prefix) list.add(fileName); } return list; } @Override protected String localPath() { StringBuilder sb = new StringBuilder(); sb.append(Config.get().getTmpDir() + "/" + TMP_BDS_DATA + "/s3"); // Bucket for (String part : getBucket().split("/")) { if (!part.isEmpty()) sb.append("/" + Gpr.sanityzeName(part)); } // Key if (getKey() != null) { for (String part : getKey().split("/")) { if (!part.isEmpty()) sb.append("/" + Gpr.sanityzeName(part)); } } return sb.toString(); } /** * There is no concept of directory in S3 * Paths created automatically */ @Override public boolean mkdirs() { return true; } /** * Parse string representing an AWS S3 URI */ protected void parse(String s3UriStr) { s3uri = new AmazonS3URI(s3UriStr); bucketName = s3uri.getBucket(); key = s3uri.getKey(); // Parse and set region String regionStr = s3uri.getRegion(); try { // if (regionStr == null) regionStr = Config.get().getString(Config.AWS_REGION, DEFAULT_AWS_REGION); // region = Region.getRegion(Regions.valueOf(regionStr.toUpperCase())); if (regionStr != null) region = Region.getRegion(Regions.valueOf(regionStr.toUpperCase())); } catch (Exception e) { throw new RuntimeException("Cannot parse AWS region '" + regionStr + "'", e); } } /** * Connect and update info */ @Override protected boolean updateInfo() { try { if (region == null) { String regionName = getS3().getBucketLocation(bucketName); // Update region if (regionName.equals("US")) region = Region.getRegion(Regions.valueOf(DEFAULT_AWS_REGION)); else region = Region.getRegion(Regions.fromName(regionName)); } } catch (AmazonClientException e) { throw new RuntimeException("Error accessing S3 bucket '" + bucketName + "'", e); } try { if (isFile()) { S3Object s3object = getS3().getObject(new GetObjectRequest(bucketName, key)); return updateInfo(s3object); } else if (existsDir()) { // Special case when keys are 'directories' exists = true; canRead = true; canWrite = true; lastModified = new Date(0L); size = 0; latestUpdate = new Timer(CACHE_TIMEOUT); return true; } else return false; } catch (AmazonServiceException e) { String errorCode = e.getErrorCode(); if (!errorCode.equals("NoSuchKey")) throw new RuntimeException("Error accessing S3 bucket '" + bucketName + "', key '" + key + "'" + this, e); // The object does not exists exists = false; canRead = false; canWrite = false; lastModified = new Date(0L); size = 0; latestUpdate = new Timer(CACHE_TIMEOUT); return true; } } /** * Update object's information */ protected boolean updateInfo(S3Object s3object) { // Read metadata ObjectMetadata om = s3object.getObjectMetadata(); // Update data size = om.getContentLength(); canRead = true; canWrite = true; lastModified = om.getLastModified(); exists = true; latestUpdate = new Timer(CACHE_TIMEOUT); // Show information if (debug) Timer.showStdErr("Updated infromation for '" + this + "'"// + "\n\tcanRead : " + canRead // + "\n\texists : " + exists // + "\n\tlast modified: " + lastModified // + "\n\tsize : " + size // ); return true; } /** * Cannot upload to a web server */ @Override public boolean upload(String localFileName) { // Create and check file File file = new File(localFileName); if (!file.exists() || !file.isFile() || !file.canRead()) { if (debug) Gpr.debug("Error accessing local file '" + getLocalPath() + "'"); return false; } // Upload getS3().putObject(new PutObjectRequest(bucketName, key, file)); return true; } }
apache-2.0
bykoianko/omim
routing/road_graph.hpp
12245
#pragma once #include "routing/segment.hpp" #include "routing_common/maxspeed_conversion.hpp" #include "routing_common/vehicle_model.hpp" #include "geometry/point2d.hpp" #include "base/string_utils.hpp" #include "indexer/feature_altitude.hpp" #include "indexer/feature_data.hpp" #include <initializer_list> #include <map> #include <vector> namespace routing { double constexpr kPointsEqualEpsilon = 1e-6; /// The Junction class represents a node description on a road network graph class Junction { public: Junction(); Junction(m2::PointD const & point, feature::TAltitude altitude); Junction(Junction const &) = default; Junction & operator=(Junction const &) = default; inline bool operator==(Junction const & r) const { return m_point == r.m_point; } inline bool operator!=(Junction const & r) const { return !(*this == r); } inline bool operator<(Junction const & r) const { return m_point < r.m_point; } inline m2::PointD const & GetPoint() const { return m_point; } inline feature::TAltitude GetAltitude() const { return m_altitude; } private: friend string DebugPrint(Junction const & r); // Point of the junction m2::PointD m_point; feature::TAltitude m_altitude; }; inline Junction MakeJunctionForTesting(m2::PointD const & point) { return Junction(point, feature::kDefaultAltitudeMeters); } inline bool AlmostEqualAbs(Junction const & lhs, Junction const & rhs) { return base::AlmostEqualAbs(lhs.GetPoint(), rhs.GetPoint(), kPointsEqualEpsilon); } /// The Edge class represents an edge description on a road network graph class Edge { enum class Type { Real, // An edge that corresponds to some real segment. FakeWithRealPart, // A fake edge that is a part of some real segment. FakeWithoutRealPart // A fake edge that is not part of any real segment. }; public: Edge() = default; Edge(Edge const &) = default; Edge & operator=(Edge const &) = default; static Edge MakeReal(FeatureID const & featureId, bool forward, uint32_t segId, Junction const & startJunction, Junction const & endJunction); static Edge MakeFakeWithRealPart(FeatureID const & featureId, bool forward, uint32_t segId, Junction const & startJunction, Junction const & endJunctio); static Edge MakeFake(Junction const & startJunction, Junction const & endJunction); static Edge MakeFake(Junction const & startJunction, Junction const & endJunction, Edge const & prototype); inline FeatureID GetFeatureId() const { return m_featureId; } inline bool IsForward() const { return m_forward; } inline uint32_t GetSegId() const { return m_segId; } inline Junction const & GetStartJunction() const { return m_startJunction; } inline Junction const & GetEndJunction() const { return m_endJunction; } inline m2::PointD const & GetStartPoint() const { return m_startJunction.GetPoint(); } inline m2::PointD const & GetEndPoint() const { return m_endJunction.GetPoint(); } inline bool IsFake() const { return m_type != Type::Real; } inline bool HasRealPart() const { return m_type != Type::FakeWithoutRealPart; } inline m2::PointD GetDirection() const { return GetEndJunction().GetPoint() - GetStartJunction().GetPoint(); } Edge GetReverseEdge() const; bool SameRoadSegmentAndDirection(Edge const & r) const; bool operator==(Edge const & r) const; bool operator!=(Edge const & r) const { return !(*this == r); } bool operator<(Edge const & r) const; private: Edge(Type type, FeatureID const & featureId, bool forward, uint32_t segId, Junction const & startJunction, Junction const & endJunction); friend string DebugPrint(Edge const & r); Type m_type = Type::FakeWithoutRealPart; // Feature for which edge is defined. FeatureID m_featureId; // Is the feature along the road. bool m_forward = true; // Ordinal number of the segment on the road. uint32_t m_segId = 0; // Start junction of the segment on the road. Junction m_startJunction; // End junction of the segment on the road. Junction m_endJunction; // Note. If |m_forward| == true index of |m_startJunction| point at the feature |m_featureId| // is less than index |m_endJunction|. // If |m_forward| == false index of |m_startJunction| point at the feature |m_featureId| // is more than index |m_endJunction|. }; class RoadGraphBase { public: typedef vector<Edge> TEdgeVector; /// Finds all nearest outgoing edges, that route to the junction. virtual void GetOutgoingEdges(Junction const & junction, TEdgeVector & edges) const = 0; /// Finds all nearest ingoing edges, that route to the junction. virtual void GetIngoingEdges(Junction const & junction, TEdgeVector & edges) const = 0; /// Returns max speed in KM/H virtual double GetMaxSpeedKMpH() const = 0; /// @return Types for the specified edge virtual void GetEdgeTypes(Edge const & edge, feature::TypesHolder & types) const = 0; /// @return Types for specified junction virtual void GetJunctionTypes(Junction const & junction, feature::TypesHolder & types) const = 0; virtual void GetRouteEdges(TEdgeVector & routeEdges) const; virtual void GetRouteSegments(std::vector<Segment> & segments) const; }; class IRoadGraph : public RoadGraphBase { public: // CheckGraphConnectivity() types aliases: using Vertex = Junction; using Edge = routing::Edge; using Weight = double; using JunctionVec = buffer_vector<Junction, 32>; enum class Mode { ObeyOnewayTag, IgnoreOnewayTag, }; /// This struct contains the part of a feature's metadata that is /// relevant for routing. struct RoadInfo { RoadInfo(); RoadInfo(RoadInfo && ri); RoadInfo(bool bidirectional, double speedKMPH, std::initializer_list<Junction> const & points); RoadInfo(RoadInfo const &) = default; RoadInfo & operator=(RoadInfo const &) = default; JunctionVec m_junctions; double m_speedKMPH; bool m_bidirectional; }; /// This class is responsible for loading edges in a cross. class ICrossEdgesLoader { public: ICrossEdgesLoader(Junction const & cross, IRoadGraph::Mode mode, TEdgeVector & edges) : m_cross(cross), m_mode(mode), m_edges(edges) { } virtual ~ICrossEdgesLoader() = default; void operator()(FeatureID const & featureId, JunctionVec const & junctions, bool bidirectional) { LoadEdges(featureId, junctions, bidirectional); } private: virtual void LoadEdges(FeatureID const & featureId, JunctionVec const & junctions, bool bidirectional) = 0; protected: template <typename TFn> void ForEachEdge(JunctionVec const & junctions, TFn && fn) { for (size_t i = 0; i < junctions.size(); ++i) { if (!base::AlmostEqualAbs(m_cross.GetPoint(), junctions[i].GetPoint(), kPointsEqualEpsilon)) continue; if (i + 1 < junctions.size()) { // Head of the edge. // m_cross // o------------>o fn(i, junctions[i + 1], true /* forward */); } if (i > 0) { // Tail of the edge. // m_cross // o------------>o fn(i - 1, junctions[i - 1], false /* backward */); } } } Junction const m_cross; IRoadGraph::Mode const m_mode; TEdgeVector & m_edges; }; class CrossOutgoingLoader : public ICrossEdgesLoader { public: CrossOutgoingLoader(Junction const & cross, IRoadGraph::Mode mode, TEdgeVector & edges) : ICrossEdgesLoader(cross, mode, edges) { } private: // ICrossEdgesLoader overrides: void LoadEdges(FeatureID const & featureId, JunctionVec const & junctions, bool bidirectional) override; }; class CrossIngoingLoader : public ICrossEdgesLoader { public: CrossIngoingLoader(Junction const & cross, IRoadGraph::Mode mode, TEdgeVector & edges) : ICrossEdgesLoader(cross, mode, edges) { } private: // ICrossEdgesLoader overrides: void LoadEdges(FeatureID const & featureId, JunctionVec const & junctions, bool bidirectional) override; }; virtual ~IRoadGraph() = default; void GetOutgoingEdges(Junction const & junction, TEdgeVector & edges) const override; void GetIngoingEdges(Junction const & junction, TEdgeVector & edges) const override; /// Removes all fake turns and vertices from the graph. void ResetFakes(); /// Adds fake edges from fake position rp to real vicinity /// positions. void AddFakeEdges(Junction const & junction, vector<pair<Edge, Junction>> const & vicinities); void AddOutgoingFakeEdge(Edge const & e); void AddIngoingFakeEdge(Edge const & e); /// Returns RoadInfo for a road corresponding to featureId. virtual RoadInfo GetRoadInfo(FeatureID const & featureId, SpeedParams const & speedParams) const = 0; /// Returns speed in KM/H for a road corresponding to featureId. virtual double GetSpeedKMpH(FeatureID const & featureId, SpeedParams const & speedParams) const = 0; /// Returns speed in KM/H for a road corresponding to edge. double GetSpeedKMpH(Edge const & edge, SpeedParams const & speedParams) const; /// Calls edgesLoader on each feature which is close to cross. virtual void ForEachFeatureClosestToCross(m2::PointD const & cross, ICrossEdgesLoader & edgesLoader) const = 0; /// Finds the closest edges to the point. /// @return Array of pairs of Edge and projection point on the Edge. If there is no the closest edges /// then returns empty array. virtual void FindClosestEdges(m2::PointD const & point, uint32_t count, vector<pair<Edge, Junction>> & vicinities) const = 0; /// @return Types for the specified feature virtual void GetFeatureTypes(FeatureID const & featureId, feature::TypesHolder & types) const = 0; /// @return Types for the specified edge virtual void GetEdgeTypes(Edge const & edge, feature::TypesHolder & types) const override; virtual IRoadGraph::Mode GetMode() const = 0; /// Clear all temporary buffers. virtual void ClearState() {} /// \brief Finds all outgoing regular (non-fake) edges for junction. void GetRegularOutgoingEdges(Junction const & junction, TEdgeVector & edges) const; /// \brief Finds all ingoing regular (non-fake) edges for junction. void GetRegularIngoingEdges(Junction const & junction, TEdgeVector & edges) const; /// \brief Finds all outgoing fake edges for junction. void GetFakeOutgoingEdges(Junction const & junction, TEdgeVector & edges) const; /// \brief Finds all ingoing fake edges for junction. void GetFakeIngoingEdges(Junction const & junction, TEdgeVector & edges) const; private: void AddEdge(Junction const & j, Edge const & e, std::map<Junction, TEdgeVector> & edges); template <typename Fn> void ForEachFakeEdge(Fn && fn) { for (auto const & m : m_fakeIngoingEdges) { for (auto const & e : m.second) fn(e); } for (auto const & m : m_fakeOutgoingEdges) { for (auto const & e : m.second) fn(e); } } /// \note |m_fakeIngoingEdges| and |m_fakeOutgoingEdges| map junctions to sorted vectors. /// Items to these maps should be inserted with AddEdge() method only. std::map<Junction, TEdgeVector> m_fakeIngoingEdges; std::map<Junction, TEdgeVector> m_fakeOutgoingEdges; }; string DebugPrint(IRoadGraph::Mode mode); IRoadGraph::RoadInfo MakeRoadInfoForTesting(bool bidirectional, double speedKMPH, std::initializer_list<m2::PointD> const & points); inline void JunctionsToPoints(vector<Junction> const & junctions, vector<m2::PointD> & points) { points.resize(junctions.size()); for (size_t i = 0; i < junctions.size(); ++i) points[i] = junctions[i].GetPoint(); } inline void JunctionsToAltitudes(vector<Junction> const & junctions, feature::TAltitudes & altitudes) { altitudes.resize(junctions.size()); for (size_t i = 0; i < junctions.size(); ++i) altitudes[i] = junctions[i].GetAltitude(); } } // namespace routing
apache-2.0
kiritbasu/datacollector
commonlib/src/test/java/com/streamsets/pipeline/lib/io/TestLiveFileChunk.java
3607
/** * 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 com.streamsets.pipeline.lib.io; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import java.io.IOException; import java.nio.charset.Charset; public class TestLiveFileChunk { @Test public void testChunkGetters() throws IOException { LiveFile file = Mockito.mock(LiveFile.class); LiveFileChunk chunk = new LiveFileChunk("tag", file, Charset.forName("UTF-8"), "Hola\nHello".getBytes(), 1, 9, true); Assert.assertEquals("tag", chunk.getTag()); Assert.assertEquals(file, chunk.getFile()); Assert.assertEquals("Hola", IOUtils.readLines(chunk.getReader()).get(0)); Assert.assertEquals("Hell", IOUtils.readLines(chunk.getReader()).get(1)); Assert.assertEquals(1, chunk.getOffset()); Assert.assertEquals(9, chunk.getLength()); Assert.assertTrue(chunk.isTruncated()); Assert.assertEquals(2, chunk.getLines().size()); Assert.assertEquals("Hola\n", chunk.getLines().get(0).getText()); Assert.assertEquals(1, chunk.getLines().get(0).getFileOffset()); Assert.assertEquals(chunk.getBuffer(), chunk.getLines().get(0).getBuffer()); Assert.assertEquals(0, chunk.getLines().get(0).getOffset()); Assert.assertEquals(5, chunk.getLines().get(0).getLength()); Assert.assertEquals("Hell", chunk.getLines().get(1).getText()); Assert.assertEquals(6, chunk.getLines().get(1).getFileOffset()); Assert.assertEquals(chunk.getBuffer(), chunk.getLines().get(1).getBuffer()); Assert.assertEquals(5, chunk.getLines().get(1).getOffset()); Assert.assertEquals(4, chunk.getLines().get(1).getLength()); } @Test public void testChunkLinesLF() throws IOException { byte[] data = "Hello\nBye\n".getBytes(Charset.forName("UTF-8")); LiveFileChunk chunk = new LiveFileChunk(null, null, Charset.forName("UTF-8"), data, 1, data.length, true); Assert.assertEquals(2, chunk.getLines().size()); Assert.assertEquals("Hello\n", chunk.getLines().get(0).getText()); Assert.assertEquals(1, chunk.getLines().get(0).getFileOffset()); Assert.assertEquals("Bye\n", chunk.getLines().get(1).getText()); Assert.assertEquals(7, chunk.getLines().get(1).getFileOffset()); } @Test public void testChunkLinesCRLF() throws IOException { byte[] data = "Hello\r\nBye\r\n".getBytes(Charset.forName("UTF-8")); LiveFileChunk chunk = new LiveFileChunk(null, null, Charset.forName("UTF-8"), data, 1, data.length, true); Assert.assertEquals(2, chunk.getLines().size()); Assert.assertEquals("Hello\r\n", chunk.getLines().get(0).getText()); Assert.assertEquals(1, chunk.getLines().get(0).getFileOffset()); Assert.assertEquals("Bye\r\n", chunk.getLines().get(1).getText()); Assert.assertEquals(8, chunk.getLines().get(1).getFileOffset()); } }
apache-2.0
Kiosani/OpenGTS
src/org/opengts/db/RuleFactoryAdapter.java
3589
// ---------------------------------------------------------------------------- // Copyright 2007-2017, GeoTelematic Solutions, 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. // // ---------------------------------------------------------------------------- // Change History: // 2008/02/21 Martin D. Flynn // -Initial release // ---------------------------------------------------------------------------- package org.opengts.db; import java.lang.*; import java.util.*; import org.opengts.util.*; import org.opengts.dbtools.*; import org.opengts.db.tables.*; public abstract class RuleFactoryAdapter implements RuleFactory { // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ /* adjust action mask */ public static int ValidateActionMask(int actionMask) { int m = actionMask & (int)EnumTools.getValueMask(NotifyAction.class); if (m != 0) { if (((m & ACTION_NOTIFY_MASK) != 0) && ((m & RuleFactory.ACTION_VIA_MASK) == 0)) { // Apparently an action notify recipient was specified // (ie Account/Device/Rule), but no 'via' was specified. // Enable ACTION_VIA_EMAIL by default. m |= RuleFactory.ACTION_VIA_EMAIL; } } return m; } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ public RuleFactoryAdapter() { super(); } // ------------------------------------------------------------------------ /** *** Returns this RuleFactory name *** @return This RuleFactory name **/ public abstract String getName(); /** *** Return this RuleFactory version String *** @return This RuleFactory version String **/ public String getVersion() { return "0.0.0"; } // ------------------------------------------------------------------------ /** *** Returns a list of predefined rule actions *** @param bpl The context BasicPrivateLabel instance *** @return The list of predefined rule actions (or null, if no predefined *** rule actions have been defined **/ public PredefinedRuleAction[] getPredefinedRuleActions(BasicPrivateLabel bpl) { return null; } // ------------------------------------------------------------------------ /** *** Gets the description for the specified GeoCorridor ID. *** Will return null if GeoCorridor is not supported. *** Will return blank if the specified GeoCorridor ID was not found. *** @param account The Account that owns the specified GeoCorridor ID *** @param corrID The GeoCorridor ID **/ public String getGeoCorridorDescription(Account account, String corrID) { return null; } }
apache-2.0
nblair/bw-util
bw-util-servlet-filters/src/main/java/org/bedework/util/servlet/filters/XSLTFilterConfigInfo.java
8875
/* ******************************************************************** Licensed to Jasig under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Jasig 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.bedework.util.servlet.filters; import java.io.Serializable; import java.util.Locale; /** This is what affects the state of ConfiguredXSLTFilter. * * @author Mike Douglass douglm@bedework.edu * @version June 18th 2003 */ public class XSLTFilterConfigInfo implements Serializable { /** appRoot does not get reset when the filter tries a default path. * This must be set to some valid value. */ private String appRoot; /** Default values (for some) */ /** Use this if we can't derive it from the system. */ private static final String localeInfoDefaultDefault = "default"; /** Try to obtain from Locale.getDefault() */ private static final Locale localeDefault = Locale.getDefault(); private static final String langDefault; private static final String countryDefault; //private static final String localeInfoDefault; static { langDefault = localeDefault.getLanguage(); countryDefault = localeDefault.getCountry(); //localeInfoDefault = makeLocale(langDefault, countryDefault); } private static final String localeInfoDefault = "default"; private static final String browserTypeDefault = "default"; private static final String skinNameDefault = "default"; private String localeInfo = localeInfoDefault; private String browserType = browserTypeDefault; private String skinName = skinNameDefault; /** These don't take part in equality checks. */ private boolean dontFilter; /** Should be set during call to obtainConfigInfo to force a reload * of the transformer */ private boolean forceReload; private boolean reloadAlways; /** Will be set on call to updatedConfigInfo if the filter forced us * back to default locale. * * <p>The superclass should respond by preserving the values and * representing them on the next call to obtainConfigInfo. */ private boolean forceDefaultLocale; /** Will be set on call to updatedConfigInfo if the filter forced us * back to default browser type. * * <p>The superclass should respond by preserving the values and * representing them on the next call to obtainConfigInfo. */ private boolean forceDefaultBrowserType; /** Will be set on call to updatedConfigInfo if the filter forced us * back to default skin name. * * <p>The superclass should respond by preserving the values and * representing them on the next call to obtainConfigInfo. */ private boolean forceDefaultSkinName; /** Content type may be set to force the content type to a certain value. * Normally it will be set by the transform. */ private String contentType; /** Reset all defaults, used before setting current values. */ public void reset() { localeInfo = localeInfoDefault; browserType = browserTypeDefault; skinName = skinNameDefault; } /** * */ public void resetBrowserType() { browserType = browserTypeDefault; } /** * */ public void resetSkinName() { skinName = skinNameDefault; } /* ==================================================================== Properties methods ==================================================================== */ /** * @param val */ public void setAppRoot(String val) { appRoot = val; } /** * @return String app root for stylesheets */ public String getAppRoot() { return appRoot; } /** * @param val */ public void setLocaleInfo(String val) { localeInfo = val; } /** * @return locale */ public String getLocaleInfo() { if (getForceDefaultLocale()) { return localeInfoDefault; } return localeInfo; } /** * @return default locale */ public String getDefaultLocaleInfo() { return localeInfoDefault; } /** * @return default language */ public String getDefaultLang() { return langDefault; } /** * @return default country */ public String getDefaultCountry() { return countryDefault; } /** * @param val */ public void setBrowserType(String val) { browserType = val; } /** * @return browser type */ public String getBrowserType() { if (getForceDefaultBrowserType()) { return browserTypeDefault; } return browserType; } /** * @return default browser type */ public String getDefaultBrowserType() { return browserTypeDefault; } /** * @param val */ public void setSkinName(String val) { skinName = val; } /** * @return skin name */ public String getSkinName() { if (getForceDefaultSkinName()) { return skinNameDefault; } return skinName; } /** * @return String default skin name */ public String getDefaultSkinName() { return skinNameDefault; } /** * @param val */ public void setDontFilter(boolean val) { dontFilter = val; } /** * @return true for no filtering */ public boolean getDontFilter() { return dontFilter; } /** * @param val */ public void setForceReload(boolean val) { forceReload = val; } /** * @return true to force reload */ public boolean getForceReload() { return forceReload; } /** * @param val */ public void setReloadAlways(boolean val) { reloadAlways = val; } /** * @return true to force reload always */ public boolean getReloadAlways() { return reloadAlways; } /** * @param val */ public void setForceDefaultLocale(boolean val) { forceDefaultLocale = val; } /** * @return true to force default locale */ public boolean getForceDefaultLocale() { return forceDefaultLocale; } /** * @param val */ public void setForceDefaultBrowserType(boolean val) { forceDefaultBrowserType = val; } /** * @return default browser type */ public boolean getForceDefaultBrowserType() { return forceDefaultBrowserType; } /** * @param val */ public void setForceDefaultSkinName(boolean val) { forceDefaultSkinName = val; } /** * @return default skin name */ public boolean getForceDefaultSkinName() { return forceDefaultSkinName; } /** * @param val */ public void setContentType(String val) { contentType = val; } /** * @return content type */ public String getContentType() { return contentType; } /** * @param that */ public void updateFrom(XSLTFilterConfigInfo that) { contentType = that.getContentType(); appRoot = that.getAppRoot(); localeInfo = that.getLocaleInfo(); browserType = that.getBrowserType(); skinName = that.getSkinName(); } public int hashCode() { int i = String.valueOf(appRoot).hashCode() + String.valueOf(localeInfo).hashCode() + String.valueOf(browserType).hashCode() + String.valueOf(skinName).hashCode(); return i; } /** If either the lang or country is null we provide a default value for * the whole locale. Otherwise we construct one. * * @param lang * @param country * @return locale */ public static String makeLocale(String lang, String country) { if ((lang == null) || (lang.length() == 0)) { return localeInfoDefaultDefault; } if ((country == null) || (country.length() == 0)) { return localeInfoDefaultDefault; } return lang + "_" + country; } public boolean equals(Object o) { if (!(o instanceof XSLTFilterConfigInfo)) { return false; } if (o.hashCode() != this.hashCode()) { return false; } XSLTFilterConfigInfo that = (XSLTFilterConfigInfo)o; return isEqual(appRoot, that.appRoot) && isEqual(localeInfo, that.localeInfo) && isEqual(browserType, that.browserType) && isEqual(skinName, that.skinName); } private boolean isEqual(String a, String b) { if (a == null) { return (b == null); } if (b == null) { return false; } return a.equals(b); } }
apache-2.0
paladique/nodejstools
Nodejs/Product/Nodejs/Debugger/Communication/ExceptionEventArgs.cs
553
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.NodejsTools.Debugger.Events; namespace Microsoft.NodejsTools.Debugger.Communication { internal sealed class ExceptionEventArgs : EventArgs { public ExceptionEventArgs(ExceptionEvent exceptionEvent) { this.ExceptionEvent = exceptionEvent; } public ExceptionEvent ExceptionEvent { get; private set; } } }
apache-2.0
Autodesk/hig
packages/theme-data/src/colorSchemes/darkBlue/components/iconButton.js
263
export default { "iconButton.dynamic.on.hover.iconColor": { value: { ref: "basics.colors.primary.autodeskBlue.300" } }, "iconButton.dynamic.on.pressed.iconColor": { value: { ref: "basics.colors.primary.autodeskBlue.300" } } };
apache-2.0
RomanPavliuk/taskRepo
Booking/Booking/App_Start/NinjectWebCommon.cs
2329
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(Booking.App_Start.NinjectWebCommon), "Start")] [assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(Booking.App_Start.NinjectWebCommon), "Stop")] namespace Booking.App_Start { using System; using System.Web; using Microsoft.Web.Infrastructure.DynamicModuleHelper; using Ninject; using Ninject.Web.Common; using DataAccess; using DataAccess.Repositories; using CoursesProject.DataAccess.Repositories; public static class NinjectWebCommon { private static readonly Bootstrapper bootstrapper = new Bootstrapper(); /// <summary> /// Starts the application /// </summary> public static void Start() { DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule)); DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule)); bootstrapper.Initialize(CreateKernel); } /// <summary> /// Stops the application. /// </summary> public static void Stop() { bootstrapper.ShutDown(); } /// <summary> /// Creates the kernel that will manage your application. /// </summary> /// <returns>The created kernel.</returns> private static IKernel CreateKernel() { var kernel = new StandardKernel(); try { kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); RegisterServices(kernel); return kernel; } catch { kernel.Dispose(); throw; } } /// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { kernel.Bind<IDbConnectionFactory>().To<DbConnectionFactory>(); kernel.Bind<IUserRepository>().To<UserRepository>(); //kernel.Bind<ITimeTableRepository>().To<TimeTableRepository>(); } } }
apache-2.0
shakamunyi/drill
contrib/storage-hbase/src/test/java/org/apache/drill/hbase/BaseHBaseTest.java
4358
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.drill.hbase; import java.io.IOException; import java.util.List; import org.apache.drill.BaseTestQuery; import org.apache.drill.common.util.FileUtils; import org.apache.drill.exec.exception.SchemaChangeException; import org.apache.drill.exec.rpc.user.QueryDataBatch; import org.apache.drill.exec.store.StoragePluginRegistry; import org.apache.drill.exec.store.hbase.HBaseStoragePlugin; import org.apache.drill.exec.store.hbase.HBaseStoragePluginConfig; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import com.google.common.base.Charsets; import com.google.common.io.Files; public class BaseHBaseTest extends BaseTestQuery { public static final String HBASE_STORAGE_PLUGIN_NAME = "hbase"; protected static Configuration conf = HBaseConfiguration.create(); protected static HBaseStoragePlugin storagePlugin; protected static HBaseStoragePluginConfig storagePluginConfig; @BeforeClass public static void setupDefaultTestCluster() throws Exception { /* * Change the following to HBaseTestsSuite.configure(false, true) * if you want to test against an externally running HBase cluster. */ HBaseTestsSuite.configure(true /*manageHBaseCluster*/, true /*createTables*/); HBaseTestsSuite.initCluster(); BaseTestQuery.setupDefaultTestCluster(); final StoragePluginRegistry pluginRegistry = getDrillbitContext().getStorage(); storagePlugin = (HBaseStoragePlugin) pluginRegistry.getPlugin(HBASE_STORAGE_PLUGIN_NAME); storagePluginConfig = storagePlugin.getConfig(); storagePluginConfig.setEnabled(true); storagePluginConfig.setZookeeperPort(HBaseTestsSuite.getZookeeperPort()); pluginRegistry.createOrUpdate(HBASE_STORAGE_PLUGIN_NAME, storagePluginConfig, true); } @AfterClass public static void tearDownAfterClass() throws Exception { HBaseTestsSuite.tearDownCluster(); } protected String getPlanText(String planFile, String tableName) throws IOException { return Files.toString(FileUtils.getResourceAsFile(planFile), Charsets.UTF_8) .replaceFirst("\"hbase\\.zookeeper\\.property\\.clientPort\".*:.*\\d+", "\"hbase.zookeeper.property.clientPort\" : " + HBaseTestsSuite.getZookeeperPort()) .replace("[TABLE_NAME]", tableName); } protected void runHBasePhysicalVerifyCount(String planFile, String tableName, int expectedRowCount) throws Exception{ String physicalPlan = getPlanText(planFile, tableName); List<QueryDataBatch> results = testPhysicalWithResults(physicalPlan); printResultAndVerifyRowCount(results, expectedRowCount); } protected List<QueryDataBatch> runHBaseSQLlWithResults(String sql) throws Exception { sql = canonizeHBaseSQL(sql); System.out.println("Running query:\n" + sql); return testSqlWithResults(sql); } protected void runHBaseSQLVerifyCount(String sql, int expectedRowCount) throws Exception{ List<QueryDataBatch> results = runHBaseSQLlWithResults(sql); printResultAndVerifyRowCount(results, expectedRowCount); } private void printResultAndVerifyRowCount(List<QueryDataBatch> results, int expectedRowCount) throws SchemaChangeException { int rowCount = printResult(results); if (expectedRowCount != -1) { Assert.assertEquals(expectedRowCount, rowCount); } } protected String canonizeHBaseSQL(String sql) { return sql.replace("[TABLE_NAME]", HBaseTestsSuite.TEST_TABLE_1.getNameAsString()); } }
apache-2.0
TeoVincent/TEO-KONKURS
Parser_v_4_1/Protocol/Asci.cs
484
namespace v_4_1.Protocol { public static class Asci { public const byte CR = 13; public const byte LF = 10; public const byte T = 84; public const byte R = 82; public const byte D = 68; public const byte H = 72; public const byte a = 97; public const byte o = 111; public const byte L = 76; public const byte P = 80; public const byte U = 85; public const byte S = 83; } }
apache-2.0
super5000/aliapi
Alipay/Controller/AlipayController.class.php
3651
<?php namespace Alipay\Controller; use Think\Controller; class AlipayController extends Controller { // 支付宝支付示例 public function alipay(){ // 组装业务数据,然后支付 $pay_data=array( 'order_no'=> $order_no, //订单号,不能重复 'price'=> $price, //交易金额 'subject'=> '商品名称' ); $_SESSION['order_no'] = $order[0]['order_no']; alipay($pay_data); } // 支付宝支付完成返回状态判断(同步通知) public function ali_return(){ $order_no = $_GET['out_trade_no']; $trade_no = $_GET['trade_no']; $total_fee = $_GET['total_fee']; $is_success = $_GET['is_success']; $trade_status = $_GET['trade_status']; // 判断支付是否成功 if ($is_success == 'T' && $order_no == $_SESSION['order_no']) { if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') { // 确认支付成功前做签名验证,并校验返回的订单金额是否与商户侧的订单金额一致,防止数据泄漏导致出现“假通知”,造成资金损失, // 1、验证订单金额是否一致 // 2、判断订单是否已做支付成功处理 // 支付成功后的业务逻辑 // 1、将订单更新为已支付 // 2、根据自己具体业务是否将订单中商品加入用户已购 }else { $this->error('支付失败'); } }else { $this->error('支付失败'); } } // 支付宝支付完成返回状态判断(异步通知) public function ali_notify(){ $order_no = $_POST['out_trade_no']; $trade_no = $_POST['trade_no']; $total_fee = $_POST['price']; $trade_status = $_POST['trade_status']; $gmt_payment = strtotime($_POST['gmt_payment']); // 判断支付是否成功 if($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') { // 确认支付成功前做签名验证,并校验返回的订单金额是否与商户侧的订单金额一致,防止数据泄漏导致出现“假通知”,造成资金损失, // 1、验证订单金额是否一致 // 2、判断订单是否已做支付成功处理(异步通知可能会多次请求) // 支付成功后的业务逻辑 // 1、将订单更新为已支付 // 2、根据自己具体业务是否将订单中商品加入用户已购 // 支付宝主动发起通知,该方式才会被启用; // 服务器间的交互,不像页面跳转同步通知可以在页面上显示出来,这种交互方式是不可见的; // 第一次交易状态改变(即时到账中此时交易状态是交易完成)时,不仅会返回同步处理结果,而且服务器异步通知页面也会收到支付宝发来的处理结果通知; // 程序执行完后必须打印输出“success”(不包含引号)。如果商户反馈给支付宝的字符不是success这7个字符,支付宝服务器会不断重发通知,直到超过24小时22分钟。一般情况下,25小时以内完成8次通知(通知的间隔频率一般是:4m,10m,10m,1h,2h,6h,15h); // 程序执行完成后,该页面不能执行页面跳转。如果执行页面跳转,支付宝会收不到success字符,会被支付宝服务器判定为该页面程序运行出现异常,而重发处理结果通知; // cookies、session等在此页面会失效,即无法获取这些数据; // 该方式的调试与运行必须在服务器上,即互联网上能访问; } } }
apache-2.0
jwennerberg/puppet-module-swrepo
spec/spec_helper.rb
606
require 'puppetlabs_spec_helper/module_spec_helper' RSpec.configure do |config| config.hiera_config = 'spec/fixtures/hiera/hiera.yaml' config.before :each do # Ensure that we don't accidentally cache facts and environment between # test cases. This requires each example group to explicitly load the # facts being exercised with something like # Facter.collection.loader.load(:ipaddress) Facter.clear Facter.clear_messages end config.default_facts = { :osfamily => 'RedHat', :common => nil, # used in hiera tests :environment => 'rp_env', } end
apache-2.0
Aarhus-BSS/Aarhus-Research-Rebuilt
src/Common/Logging/cLogFile.java
2643
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Common.Logging; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import Common.MsgBoxer.MBox; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.util.Date; /** * * @author d3vil401 */ // This one goes into a file, very usefull in case we have a console mode. public class cLogFile extends cLogConsole implements ILogManager { private File _file = null; private PrintStream _printStream = null; private boolean _isFileStream = false; public cLogFile() { } @Override public void initializeSession(String _fileName) { super.initializeSession(_fileName); DateFormat _dateFormat = new SimpleDateFormat("dd.MM.yyyy-HH.mm.ss"); String _fName = _fileName + "_" + _dateFormat.format(new Date()) + ".txt"; this._file = new File(_fName); try { // Required auto flush, so we don't have to update the buffer continuosly. this._printStream = new PrintStream(new BufferedOutputStream(new FileOutputStream(_file, true))); System.setOut(this._printStream); this._isFileStream = true; } catch (FileNotFoundException ex) { MBox.showBox("Unable to write " + _fName + ": " + ex.getMessage(), "Error trying to write log file", MBox._MSGBOX_TYPE.TYPE_ERROR); } } @Override public void print(_LOG_TYPE _type, String _msg) { super.print(_type, _msg); } @Override public void destroySession() { super.destroySession(); this._printStream.flush(); this._printStream.close(); this._switch(); // Just to be sure. } // Whenever it's needed to get back to console || file public void _switch() { if (this._isFileStream) { System.setOut(System.out); this._isFileStream = false; } else { System.setOut(this._printStream); this._isFileStream = true; } } @Override public String getSessionName() { return this._file.getName(); } @Override public void setDebugMode(boolean _status) { } }
apache-2.0
dbflute-test/dbflute-test-dbms-db2
src/main/java/org/docksidestage/db2/dbflute/bsentity/customize/BsVendorCheckDecimalSum.java
5837
package org.docksidestage.db2.dbflute.bsentity.customize; import java.util.List; import java.util.ArrayList; import org.dbflute.dbmeta.DBMeta; import org.dbflute.dbmeta.AbstractEntity; import org.dbflute.dbmeta.accessory.CustomizeEntity; import org.docksidestage.db2.dbflute.exentity.customize.*; /** * The entity of VendorCheckDecimalSum. <br> * <pre> * [primary-key] * * * [column] * DECIMAL_DIGIT_SUM * * [sequence] * * * [identity] * * * [version-no] * * * [foreign table] * * * [referrer table] * * * [foreign property] * * * [referrer property] * * * [get/set template] * /= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * java.math.BigDecimal decimalDigitSum = entity.getDecimalDigitSum(); * entity.setDecimalDigitSum(decimalDigitSum); * = = = = = = = = = =/ * </pre> * @author DBFlute(AutoGenerator) */ public abstract class BsVendorCheckDecimalSum extends AbstractEntity implements CustomizeEntity { // =================================================================================== // Definition // ========== /** The serial version UID for object serialization. (Default) */ private static final long serialVersionUID = 1L; // =================================================================================== // Attribute // ========= /** DECIMAL_DIGIT_SUM: {DECIMAL(31, 3)} */ protected java.math.BigDecimal _decimalDigitSum; // =================================================================================== // DB Meta // ======= /** {@inheritDoc} */ public DBMeta asDBMeta() { return org.docksidestage.db2.dbflute.bsentity.customize.dbmeta.VendorCheckDecimalSumDbm.getInstance(); } /** {@inheritDoc} */ public String asTableDbName() { return "VendorCheckDecimalSum"; } // =================================================================================== // Key Handling // ============ /** {@inheritDoc} */ public boolean hasPrimaryKeyValue() { return false; } // =================================================================================== // Foreign Property // ================ // =================================================================================== // Referrer Property // ================= protected <ELEMENT> List<ELEMENT> newReferrerList() { // overriding to import return new ArrayList<ELEMENT>(); } // =================================================================================== // Basic Override // ============== @Override protected boolean doEquals(Object obj) { if (obj instanceof BsVendorCheckDecimalSum) { BsVendorCheckDecimalSum other = (BsVendorCheckDecimalSum)obj; if (!xSV(_decimalDigitSum, other._decimalDigitSum)) { return false; } return true; } else { return false; } } @Override protected int doHashCode(int initial) { int hs = initial; hs = xCH(hs, asTableDbName()); hs = xCH(hs, _decimalDigitSum); return hs; } @Override protected String doBuildStringWithRelation(String li) { return ""; } @Override protected String doBuildColumnString(String dm) { StringBuilder sb = new StringBuilder(); sb.append(dm).append(xfND(_decimalDigitSum)); if (sb.length() > dm.length()) { sb.delete(0, dm.length()); } sb.insert(0, "{").append("}"); return sb.toString(); } @Override protected String doBuildRelationString(String dm) { return ""; } @Override public VendorCheckDecimalSum clone() { return (VendorCheckDecimalSum)super.clone(); } // =================================================================================== // Accessor // ======== /** * [get] DECIMAL_DIGIT_SUM: {DECIMAL(31, 3)} <br> * @return The value of the column 'DECIMAL_DIGIT_SUM'. (NullAllowed even if selected: for no constraint) */ public java.math.BigDecimal getDecimalDigitSum() { checkSpecifiedProperty("decimalDigitSum"); return _decimalDigitSum; } /** * [set] DECIMAL_DIGIT_SUM: {DECIMAL(31, 3)} <br> * @param decimalDigitSum The value of the column 'DECIMAL_DIGIT_SUM'. (NullAllowed: null update allowed for no constraint) */ public void setDecimalDigitSum(java.math.BigDecimal decimalDigitSum) { registerModifiedProperty("decimalDigitSum"); _decimalDigitSum = decimalDigitSum; } }
apache-2.0
hereacg/popo
static/js/home.js
1210
//The Javascript By Alxtit $("main").slideDown(); $(document).ready(function(){ $(".header_menu").click(function(){ menu_top.innerHTML=(menu_top.innerHTML=='expand_less'?'menu':'expand_less'); $("#menu_list").slideToggle("slow"); }); }); $(document).ready(function(){ $(function () {hitokotodata();}); function hitokotodata(){ $.ajax({ timeout: 1000, async: true, type: "GET", url: "https://sslapi.hitokoto.cn/", dataType: "json", success: function (data) { $("#hitokoto").html('<p>『'+ data["hitokoto"] +'』-「'+ data["from"] +'」</p>'); if(data){ echohitokoto(); } } }); } $(function(){rernd()}); function rernd(){ $(".hitokotornd").stop(true,false).animate({width:'100%'},15000, function(){ $(".header_hitokoto").animate({bottom: '-80px'},1000, function() { rernd2(); }); }); } function rernd2(){ $(".hitokotornd").stop(true,false).animate({width:'0%'},0, function() { hitokotodata(); }); } function echohitokoto(){ $(".header_hitokoto").animate({bottom: '0'},1000); rernd(); } }); $(function (){ $(".header_line").animate({width:'100%'},800); $(".htitle").fadeIn(1000); });
apache-2.0
Schinzel/basic-utils
src/main/java/io/schinzel/samples/file/ResourceReaderSample.java
478
package io.schinzel.samples.file; import io.schinzel.basicutils.file.ResourceReader; /** * Purpose of this class is to provide sample usage of ResourceReader * <p> * Created by Schinzel on 2018-01-13 */ public class ResourceReaderSample { public static void main(String[] args) { String fileContent = ResourceReader .read("io/schinzel/samples/sample_resource.txt") .asString(); System.out.println(fileContent); } }
apache-2.0
attatrol/Orekit
src/main/java/org/orekit/models/earth/tessellation/EllipsoidTessellator.java
40354
/* Copyright 2002-2015 CS Systèmes d'Information * Licensed to CS Systèmes d'Information (CS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * CS 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.orekit.models.earth.tessellation; import java.util.ArrayList; import java.util.Collection; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Queue; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.apache.commons.math3.geometry.partitioning.BSPTree; import org.apache.commons.math3.geometry.partitioning.Hyperplane; import org.apache.commons.math3.geometry.partitioning.RegionFactory; import org.apache.commons.math3.geometry.partitioning.SubHyperplane; import org.apache.commons.math3.geometry.spherical.oned.ArcsSet; import org.apache.commons.math3.geometry.spherical.twod.Circle; import org.apache.commons.math3.geometry.spherical.twod.S2Point; import org.apache.commons.math3.geometry.spherical.twod.Sphere2D; import org.apache.commons.math3.geometry.spherical.twod.SphericalPolygonsSet; import org.apache.commons.math3.geometry.spherical.twod.SubCircle; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathUtils; import org.orekit.bodies.GeodeticPoint; import org.orekit.bodies.OneAxisEllipsoid; import org.orekit.errors.OrekitException; import org.orekit.errors.OrekitInternalError; /** Class used to tessellate an interest zone on an ellipsoid in either * {@link Tile tiles} or grids of {@link GeodeticPoint geodetic points}. * <p> * This class is typically used for Earth Observation missions, in order to * create tiles or grids that may be used as the basis of visibility event * detectors. Tiles are used when surface-related elements are needed, the * tiles created completely cover the zone of interest. Grids are used when * point-related elements are needed, the points created lie entirely within * the zone of interest. * </p> * <p> * One should note that as tessellation essentially creates a 2 dimensional * almost Cartesian map, it can never perfectly fulfill geometrical dimensions * because neither sphere nor ellipsoid are developable surfaces. This implies * that the tesselation will always be distorted, and distortion increases as * the size of the zone to be tessellated increases. * </p> * @author Luc Maisonobe */ public class EllipsoidTessellator { /** Number of segments tiles sides are split into for tiles fine positioning. */ private final int quantization; /** Aiming used for orienting tiles. */ private final TileAiming aiming; /** Underlying ellipsoid. */ private final OneAxisEllipsoid ellipsoid; /** Simple constructor. * <p> * The {@code quantization} parameter is used internally to adjust points positioning. * For example when quantization is set to 4, a complete tile that has 4 corner points * separated by the tile lengths will really be computed on a grid containing 25 points * (5 rows of 5 points, as each side will be split in 4 segments, hence will have 5 * points). This quantization allows rough adjustment to balance margins around the * zone of interest and improves geometric accuracy as the along and across directions * are readjusted at each points. * </p> * <p> * It is recommended to use at least 2 as the quantization parameter for tiling. The * rationale is that using only 1 for quantization would imply all points used are tiles * vertices, and hence would lead small zones to generate 4 tiles with a shared vertex * inside the zone and the 4 tiles covering the four quadrants at North-West, North-East, * South-East and South-West. A quantization value of at least 2 allows to shift the * tiles so the center point is an inside point rather than a tile vertex, hence allowing * a single tile to cover the small zone. A value even greater like 4 or 8 would allow even * finer positioning to balance the tiles margins around the zone. * </p> * @param ellipsoid underlying ellipsoid * @param aiming aiming used for orienting tiles * @param quantization number of segments tiles sides are split into for tiles fine positioning */ public EllipsoidTessellator(final OneAxisEllipsoid ellipsoid, final TileAiming aiming, final int quantization) { this.ellipsoid = ellipsoid; this.aiming = aiming; this.quantization = quantization; } /** Tessellate a zone of interest into tiles. * <p> * The created tiles will completely cover the zone of interest. * </p> * <p> * The distance between a vertex at a tile corner and the vertex at the same corner * in the next vertex are computed by subtracting the overlap width (resp. overlap length) * from the full width (resp. full length). If for example the full width is specified to * be 55 km and the overlap in width is specified to be +5 km, successive tiles would span * as follows: * </p> * <ul> * <li>tile 1 covering from 0 km to 55 km</li> * <li>tile 2 covering from 50 km to 105 km</li> * <li>tile 3 covering from 100 km to 155 km</li> * <li>...</li> * </ul> * <p> * In order to achieve the same 50 km step but using a 5 km gap instead of an overlap, one would * need to specify the full width to be 45 km and the overlap to be -5 km. With these settings, * successive tiles would span as follows: * </p> * <ul> * <li>tile 1 covering from 0 km to 45 km</li> * <li>tile 2 covering from 50 km to 95 km</li> * <li>tile 3 covering from 100 km to 155 km</li> * <li>...</li> * </ul> * @param zone zone of interest to tessellate * @param fullWidth full tiles width as a distance on surface, including overlap (in meters) * @param fullLength full tiles length as a distance on surface, including overlap (in meters) * @param widthOverlap overlap between adjacent tiles (in meters), if negative the tiles * will have a gap between each other instead of an overlap * @param lengthOverlap overlap between adjacent tiles (in meters), if negative the tiles * will have a gap between each other instead of an overlap * @param truncateLastWidth if true, the first tiles strip will be started as close as * possible to the zone of interest, and the last tiles strip will have its width reduced * to also remain close to the zone of interest; if false all tiles strip will have the * same {@code fullWidth} and they will be balanced around zone of interest * @param truncateLastLength if true, the first tile in each strip will be started as close as * possible to the zone of interest, and the last tile in each strip will have its length reduced * to also remain close to the zone of interest; if false all tiles in each strip will have the * same {@code fullLength} and they will be balanced around zone of interest * @return a list of lists of tiles covering the zone of interest, * each sub-list corresponding to a part not connected to the other * parts (for example for islands) * @exception OrekitException if the zone cannot be tessellated */ public List<List<Tile>> tessellate(final SphericalPolygonsSet zone, final double fullWidth, final double fullLength, final double widthOverlap, final double lengthOverlap, final boolean truncateLastWidth, final boolean truncateLastLength) throws OrekitException { final double splitWidth = (fullWidth - widthOverlap) / quantization; final double splitLength = (fullLength - lengthOverlap) / quantization; final Map<Mesh, List<Tile>> map = new IdentityHashMap<Mesh, List<Tile>>(); final RegionFactory<Sphere2D> factory = new RegionFactory<Sphere2D>(); SphericalPolygonsSet remaining = (SphericalPolygonsSet) zone.copySelf(); S2Point inside = getInsidePoint(remaining); while (inside != null) { // find a mesh covering at least one connected part of the zone final List<Mesh.Node> mergingSeeds = new ArrayList<Mesh.Node>(); Mesh mesh = new Mesh(ellipsoid, zone, aiming, splitLength, splitWidth, inside); mergingSeeds.add(mesh.getNode(0, 0)); List<Tile> tiles = null; while (!mergingSeeds.isEmpty()) { // expand the mesh around the seed neighborExpandMesh(mesh, mergingSeeds, zone); // extract the tiles from the mesh // this further expands the mesh so tiles dimensions are multiples of quantization, // hence it must be performed here before checking meshes independence tiles = extractTiles(mesh, zone, lengthOverlap, widthOverlap, truncateLastWidth, truncateLastLength); // check the mesh is independent from existing meshes mergingSeeds.clear(); for (final Map.Entry<Mesh, List<Tile>> entry : map.entrySet()) { if (!factory.intersection(mesh.getCoverage(), entry.getKey().getCoverage()).isEmpty()) { // the meshes are not independent, they intersect each other! // merge the two meshes together mesh = mergeMeshes(mesh, entry.getKey(), mergingSeeds); map.remove(entry.getKey()); break; } } } // remove the part of the zone covered by the mesh remaining = (SphericalPolygonsSet) factory.difference(remaining, mesh.getCoverage()); inside = getInsidePoint(remaining); map.put(mesh, tiles); } // concatenate the lists from the independent meshes final List<List<Tile>> tilesLists = new ArrayList<List<Tile>>(map.size()); for (final Map.Entry<Mesh, List<Tile>> entry : map.entrySet()) { tilesLists.add(entry.getValue()); } return tilesLists; } /** Sample a zone of interest into a grid sample of {@link GeodeticPoint geodetic points}. * <p> * The created points will be entirely within the zone of interest. * </p> * @param zone zone of interest to sample * @param width grid sample cells width as a distance on surface (in meters) * @param length grid sample cells length as a distance on surface (in meters) * @return a list of lists of points sampling the zone of interest, * each sub-list corresponding to a part not connected to the other * parts (for example for islands) * @exception OrekitException if the zone cannot be sampled */ public List<List<GeodeticPoint>> sample(final SphericalPolygonsSet zone, final double width, final double length) throws OrekitException { final double splitWidth = width / quantization; final double splitLength = length / quantization; final Map<Mesh, List<GeodeticPoint>> map = new IdentityHashMap<Mesh, List<GeodeticPoint>>(); final RegionFactory<Sphere2D> factory = new RegionFactory<Sphere2D>(); SphericalPolygonsSet remaining = (SphericalPolygonsSet) zone.copySelf(); S2Point inside = getInsidePoint(remaining); while (inside != null) { // find a mesh covering at least one connected part of the zone final List<Mesh.Node> mergingSeeds = new ArrayList<Mesh.Node>(); Mesh mesh = new Mesh(ellipsoid, zone, aiming, splitLength, splitWidth, inside); mergingSeeds.add(mesh.getNode(0, 0)); List<GeodeticPoint> sample = null; while (!mergingSeeds.isEmpty()) { // expand the mesh around the seed neighborExpandMesh(mesh, mergingSeeds, zone); // extract the sample from the mesh // this further expands the mesh so sample cells dimensions are multiples of quantization, // hence it must be performed here before checking meshes independence sample = extractSample(mesh, zone); // check the mesh is independent from existing meshes mergingSeeds.clear(); for (final Map.Entry<Mesh, List<GeodeticPoint>> entry : map.entrySet()) { if (!factory.intersection(mesh.getCoverage(), entry.getKey().getCoverage()).isEmpty()) { // the meshes are not independent, they intersect each other! // merge the two meshes together mesh = mergeMeshes(mesh, entry.getKey(), mergingSeeds); map.remove(entry.getKey()); break; } } } // remove the part of the zone covered by the mesh remaining = (SphericalPolygonsSet) factory.difference(remaining, mesh.getCoverage()); inside = getInsidePoint(remaining); map.put(mesh, sample); } // concatenate the lists from the independent meshes final List<List<GeodeticPoint>> sampleLists = new ArrayList<List<GeodeticPoint>>(map.size()); for (final Map.Entry<Mesh, List<GeodeticPoint>> entry : map.entrySet()) { sampleLists.add(entry.getValue()); } return sampleLists; } /** Get an inside point from a zone of interest. * @param zone zone to mesh * @return a point inside the zone or null if zone is empty or too thin * @exception OrekitException if tile direction cannot be computed */ private static S2Point getInsidePoint(final SphericalPolygonsSet zone) throws OrekitException { final InsideFinder finder = new InsideFinder(zone); zone.getTree(false).visit(finder); return finder.getInsidePoint(); } /** Expand a mesh so it surrounds at least one connected part of a zone. * <p> * This part of mesh expansion is neighbors based. It includes the seed * node neighbors, and their neighbors, and the neighbors of their * neighbors until the path-connected sub-parts of the zone these nodes * belong to are completely surrounded by the mesh taxicab boundary. * </p> * @param mesh mesh to expand * @param seeds seed nodes (already in the mesh) from which to start expansion * @param zone zone to mesh * @exception OrekitException if tile direction cannot be computed */ private void neighborExpandMesh(final Mesh mesh, final Collection<Mesh.Node> seeds, final SphericalPolygonsSet zone) throws OrekitException { // mesh expansion loop boolean expanding = true; final Queue<Mesh.Node> newNodes = new LinkedList<Mesh.Node>(); newNodes.addAll(seeds); while (expanding) { // first expansion step: set up the mesh so that all its // inside nodes are completely surrounded by at least // one layer of outside nodes while (!newNodes.isEmpty()) { // retrieve an active node final Mesh.Node node = newNodes.remove(); if (node.isInside()) { // the node is inside the zone, the mesh must contain its 8 neighbors addAllNeighborsIfNeeded(node, mesh, newNodes); } } // second expansion step: check if the loop of outside nodes // completely surrounds the zone, i.e. there are no peaks // pointing out of the loop between two nodes expanding = false; final List<Mesh.Node> boundary = mesh.getTaxicabBoundary(false); if (boundary.size() > 1) { Mesh.Node previous = boundary.get(boundary.size() - 1); for (final Mesh.Node node : boundary) { if (meetInside(previous.getS2P(), node.getS2P(), zone)) { // part of the mesh boundary is still inside the zone! // the mesh must be expanded again addAllNeighborsIfNeeded(previous, mesh, newNodes); addAllNeighborsIfNeeded(node, mesh, newNodes); expanding = true; } previous = node; } } } } /** Extract tiles from a mesh. * @param mesh mesh from which tiles should be extracted * @param zone zone covered by the mesh * @param lengthOverlap overlap between adjacent tiles * @param widthOverlap overlap between adjacent tiles * @param truncateLastWidth true if we can reduce last tile width * @param truncateLastLength true if we can reduce last tile length * @return extracted tiles * @exception OrekitException if tile direction cannot be computed */ private List<Tile> extractTiles(final Mesh mesh, final SphericalPolygonsSet zone, final double lengthOverlap, final double widthOverlap, final boolean truncateLastWidth, final boolean truncateLastLength) throws OrekitException { final List<Tile> tiles = new ArrayList<Tile>(); final List<RangePair> rangePairs = new ArrayList<RangePair>(); final int minAcross = mesh.getMinAcrossIndex(); final int maxAcross = mesh.getMaxAcrossIndex(); for (Range acrossPair : nodesIndices(minAcross, maxAcross, truncateLastWidth)) { int minAlong = mesh.getMaxAlongIndex() + 1; int maxAlong = mesh.getMinAlongIndex() - 1; for (int c = acrossPair.lower; c <= acrossPair.upper; ++c) { minAlong = FastMath.min(minAlong, mesh.getMinAlongIndex(c)); maxAlong = FastMath.max(maxAlong, mesh.getMaxAlongIndex(c)); } for (Range alongPair : nodesIndices(minAlong, maxAlong, truncateLastLength)) { // get the base vertex nodes final Mesh.Node node0 = mesh.addNode(alongPair.lower, acrossPair.lower); final Mesh.Node node1 = mesh.addNode(alongPair.upper, acrossPair.lower); final Mesh.Node node2 = mesh.addNode(alongPair.upper, acrossPair.upper); final Mesh.Node node3 = mesh.addNode(alongPair.lower, acrossPair.upper); // apply tile overlap final S2Point s2p0 = node0.move(new Vector3D(-0.5 * lengthOverlap, node0.getAlong(), -0.5 * widthOverlap, node0.getAcross())); final S2Point s2p1 = node1.move(new Vector3D(+0.5 * lengthOverlap, node1.getAlong(), -0.5 * widthOverlap, node1.getAcross())); final S2Point s2p2 = node2.move(new Vector3D(+0.5 * lengthOverlap, node2.getAlong(), +0.5 * widthOverlap, node2.getAcross())); final S2Point s2p3 = node3.move(new Vector3D(-0.5 * lengthOverlap, node2.getAlong(), +0.5 * widthOverlap, node2.getAcross())); // create a quadrilateral region corresponding to the candidate tile final SphericalPolygonsSet quadrilateral = new SphericalPolygonsSet(zone.getTolerance(), s2p0, s2p1, s2p2, s2p3); if (!new RegionFactory<Sphere2D>().intersection(zone.copySelf(), quadrilateral).isEmpty()) { // the tile does cover part of the zone, it contributes to the tessellation tiles.add(new Tile(toGeodetic(s2p0), toGeodetic(s2p1), toGeodetic(s2p2), toGeodetic(s2p3))); rangePairs.add(new RangePair(acrossPair, alongPair)); } } } // ensure the taxicab boundary follows the built tile sides // this is done outside of the previous loop because in order // to avoid one tile changing the min/max indices of the // neighboring tile as they share some nodes that will be enabled here for (final RangePair rangePair : rangePairs) { for (int c = rangePair.across.lower; c < rangePair.across.upper; ++c) { mesh.addNode(rangePair.along.lower, c + 1).setEnabled(); mesh.addNode(rangePair.along.upper, c).setEnabled(); } for (int l = rangePair.along.lower; l < rangePair.along.upper; ++l) { mesh.addNode(l, rangePair.across.lower).setEnabled(); mesh.addNode(l + 1, rangePair.across.upper).setEnabled(); } } return tiles; } /** Extract a sample of points from a mesh. * @param mesh mesh from which grid should be extracted * @param zone zone covered by the mesh * @return extracted grid * @exception OrekitException if tile direction cannot be computed */ private List<GeodeticPoint> extractSample(final Mesh mesh, final SphericalPolygonsSet zone) throws OrekitException { // find how to select sample points taking quantization into account // to have the largest possible number of points while still // being inside the zone of interest int selectedAcrossModulus = -1; int selectedAlongModulus = -1; int selectedCount = -1; for (int acrossModulus = 0; acrossModulus < quantization; ++acrossModulus) { for (int alongModulus = 0; alongModulus < quantization; ++alongModulus) { // count how many points would be selected for the current modulus int count = 0; for (int across = mesh.getMinAcrossIndex() + acrossModulus; across <= mesh.getMaxAcrossIndex(); across += quantization) { for (int along = mesh.getMinAlongIndex() + alongModulus; along <= mesh.getMaxAlongIndex(); along += quantization) { final Mesh.Node node = mesh.getNode(along, across); if (node != null && node.isInside()) { ++count; } } } if (count > selectedCount) { // current modulus are better than the selected ones selectedAcrossModulus = acrossModulus; selectedAlongModulus = alongModulus; selectedCount = count; } } } // extract the sample points final List<GeodeticPoint> sample = new ArrayList<GeodeticPoint>(selectedCount); for (int across = mesh.getMinAcrossIndex() + selectedAcrossModulus; across <= mesh.getMaxAcrossIndex(); across += quantization) { for (int along = mesh.getMinAlongIndex() + selectedAlongModulus; along <= mesh.getMaxAlongIndex(); along += quantization) { final Mesh.Node node = mesh.getNode(along, across); if (node != null && node.isInside()) { sample.add(toGeodetic(node.getS2P())); } } } return sample; } /** Merge two meshes together. * @param mesh1 first mesh * @param mesh2 second mesh * @param mergingSeeds collection were to put the nodes created during the merge * @return merged mesh (really one of the instances) * @exception OrekitException if tile direction cannot be computed */ private Mesh mergeMeshes(final Mesh mesh1, final Mesh mesh2, final Collection<Mesh.Node> mergingSeeds) throws OrekitException { // select the way merge will be performed final Mesh larger; final Mesh smaller; if (mesh1.getNumberOfNodes() >= mesh2.getNumberOfNodes()) { // the larger new mesh should absorb the smaller existing mesh larger = mesh1; smaller = mesh2; } else { // the larger existing mesh should absorb the smaller new mesh larger = mesh2; smaller = mesh1; } // prepare seed nodes for next iteration for (final Mesh.Node insideNode : smaller.getInsideNodes()) { // beware we cannot reuse the node itself as the two meshes are not aligned! // we have to create new nodes around the previous location Mesh.Node node = larger.getClosestExistingNode(insideNode.getV()); while (estimateAlongMotion(node, insideNode.getV()) > +mesh1.getAlongGap()) { // the node is before desired index in the along direction // we need to create intermediates nodes up to the desired index node = larger.addNode(node.getAlongIndex() + 1, node.getAcrossIndex()); } while (estimateAlongMotion(node, insideNode.getV()) < -mesh1.getAlongGap()) { // the node is after desired index in the along direction // we need to create intermediates nodes up to the desired index node = larger.addNode(node.getAlongIndex() - 1, node.getAcrossIndex()); } while (estimateAcrossMotion(node, insideNode.getV()) > +mesh1.getAcrossGap()) { // the node is before desired index in the across direction // we need to create intermediates nodes up to the desired index node = larger.addNode(node.getAlongIndex(), node.getAcrossIndex() + 1); } while (estimateAcrossMotion(node, insideNode.getV()) < -mesh1.getAcrossGap()) { // the node is after desired index in the across direction // we need to create intermediates nodes up to the desired index node = larger.addNode(node.getAlongIndex(), node.getAcrossIndex() - 1); } // now we are close to the inside node, // make sure the four surrounding nodes are available final int otherAlong = (estimateAlongMotion(node, insideNode.getV()) < 0.0) ? node.getAlongIndex() - 1 : node.getAlongIndex() + 1; final int otherAcross = (estimateAcrossMotion(node, insideNode.getV()) < 0.0) ? node.getAcrossIndex() - 1 : node.getAcrossIndex() + 1; addNode(node.getAlongIndex(), node.getAcrossIndex(), larger, mergingSeeds); addNode(node.getAlongIndex(), otherAcross, larger, mergingSeeds); addNode(otherAlong, node.getAcrossIndex(), larger, mergingSeeds); addNode(otherAlong, otherAcross, larger, mergingSeeds); } return larger; } /** Ensure all 8 neighbors of a node are in the mesh. * @param base base node * @param mesh complete mesh containing nodes * @param newNodes queue where new node must be put * @exception OrekitException if tile direction cannot be computed */ private static void addAllNeighborsIfNeeded(final Mesh.Node base, final Mesh mesh, final Collection<Mesh.Node> newNodes) throws OrekitException { addNode(base.getAlongIndex() - 1, base.getAcrossIndex() - 1, mesh, newNodes); addNode(base.getAlongIndex() - 1, base.getAcrossIndex(), mesh, newNodes); addNode(base.getAlongIndex() - 1, base.getAcrossIndex() + 1, mesh, newNodes); addNode(base.getAlongIndex(), base.getAcrossIndex() - 1, mesh, newNodes); addNode(base.getAlongIndex(), base.getAcrossIndex() + 1, mesh, newNodes); addNode(base.getAlongIndex() + 1, base.getAcrossIndex() - 1, mesh, newNodes); addNode(base.getAlongIndex() + 1, base.getAcrossIndex(), mesh, newNodes); addNode(base.getAlongIndex() + 1, base.getAcrossIndex() + 1, mesh, newNodes); } /** Add a node to a mesh if not already present. * @param alongIndex index in the along direction * @param acrossIndex index in the across direction * @param mesh complete mesh containing nodes * @param newNodes queue where new node must be put * @exception OrekitException if tile direction cannot be computed */ private static void addNode(final int alongIndex, final int acrossIndex, final Mesh mesh, final Collection<Mesh.Node> newNodes) throws OrekitException { final Mesh.Node node = mesh.addNode(alongIndex, acrossIndex); if (!node.isEnabled()) { // enable the node node.setEnabled(); newNodes.add(node); } } /** Convert a point on the unit 2-sphere to geodetic coordinates. * @param point point on the unit 2-sphere * @return geodetic point (arbitrarily set at altitude 0) */ protected GeodeticPoint toGeodetic(final S2Point point) { return new GeodeticPoint(0.5 * FastMath.PI - point.getPhi(), point.getTheta(), 0.0); } /** Build a simple zone (connected zone without holes). * <p> * In order to build more complex zones (not connected or with * holes), the user should directly call Apache Commons * Math {@link SphericalPolygonsSet} constructors and * {@link RegionFactory region factory} if set operations * are needed (union, intersection, difference ...). * </p> * <p> * Take care that the vertices boundary points must be given <em>counterclockwise</em>. * Using the wrong order defines the complementary of the real zone, * and will often result in tessellation failure as the zone is too * wide. * </p> * @param tolerance angular separation below which points are considered * equal (typically 1.0e-10) * @param points vertices of the boundary, in <em>counterclockwise</em> * order, each point being a two-elements arrays with latitude at index 0 * and longitude at index 1 * @return a zone defined on the unit 2-sphere */ public static SphericalPolygonsSet buildSimpleZone(final double tolerance, final double[] ... points) { final S2Point[] vertices = new S2Point[points.length]; for (int i = 0; i < points.length; ++i) { vertices[i] = new S2Point(points[i][1], 0.5 * FastMath.PI - points[i][0]); } return new SphericalPolygonsSet(tolerance, vertices); } /** Build a simple zone (connected zone without holes). * <p> * In order to build more complex zones (not connected or with * holes), the user should directly call Apache Commons * Math {@link SphericalPolygonsSet} constructors and * {@link RegionFactory region factory} if set operations * are needed (union, intersection, difference ...). * </p> * <p> * Take care that the vertices boundary points must be given <em>counterclockwise</em>. * Using the wrong order defines the complementary of the real zone, * and will often result in tessellation failure as the zone is too * wide. * </p> * @param tolerance angular separation below which points are considered * equal (typically 1.0e-10) * @param points vertices of the boundary, in <em>counterclockwise</em> * order * @return a zone defined on the unit 2-sphere */ public static SphericalPolygonsSet buildSimpleZone(final double tolerance, final GeodeticPoint ... points) { final S2Point[] vertices = new S2Point[points.length]; for (int i = 0; i < points.length; ++i) { vertices[i] = new S2Point(points[i].getLongitude(), 0.5 * FastMath.PI - points[i].getLatitude()); } return new SphericalPolygonsSet(tolerance, vertices); } /** Estimate an approximate motion in the along direction. * @param start node at start of motion * @param end desired point at end of motion * @return approximate motion in the along direction */ private double estimateAlongMotion(final Mesh.Node start, final Vector3D end) { return Vector3D.dotProduct(start.getAlong(), end.subtract(start.getV())); } /** Estimate an approximate motion in the across direction. * @param start node at start of motion * @param end desired point at end of motion * @return approximate motion in the across direction */ private double estimateAcrossMotion(final Mesh.Node start, final Vector3D end) { return Vector3D.dotProduct(start.getAcross(), end.subtract(start.getV())); } /** Check if an arc meets the inside of a zone. * @param s1 first point * @param s2 second point * @param zone zone to check arc against * @return true if the arc meets the inside of the zone */ private boolean meetInside(final S2Point s1, final S2Point s2, final SphericalPolygonsSet zone) { final Circle circle = new Circle(s1, s2, zone.getTolerance()); final double alpha1 = circle.toSubSpace(s1).getAlpha(); final double alpha2 = MathUtils.normalizeAngle(circle.toSubSpace(s2).getAlpha(), alpha1 + FastMath.PI); final SubCircle sub = new SubCircle(circle, new ArcsSet(alpha1, alpha2, zone.getTolerance())); return recurseMeetInside(zone.getTree(false), sub); } /** Check if an arc meets the inside of a zone. * <p> * This method is heavily based on the Characterization class from * Apache Commons Math library, also distributed under the terms * of the Apache Software License V2. * </p> * @param node spherical zone node * @param sub arc to characterize * @return true if the arc meets the inside of the zone */ private boolean recurseMeetInside(final BSPTree<Sphere2D> node, final SubHyperplane<Sphere2D> sub) { if (node.getCut() == null) { // we have reached a leaf node if (sub.isEmpty()) { return false; } else { return (Boolean) node.getAttribute(); } } else { final Hyperplane<Sphere2D> hyperplane = node.getCut().getHyperplane(); switch (sub.side(hyperplane)) { case PLUS: return recurseMeetInside(node.getPlus(), sub); case MINUS: return recurseMeetInside(node.getMinus(), sub); case BOTH: final SubHyperplane.SplitSubHyperplane<Sphere2D> split = sub.split(hyperplane); if (recurseMeetInside(node.getPlus(), split.getPlus())) { return true; } else { return recurseMeetInside(node.getMinus(), split.getMinus()); } default: // this should not happen throw new OrekitInternalError(null); } } } /** Get an iterator over mesh nodes indices. * @param minIndex minimum node index * @param maxIndex maximum node index * @param truncateLast true if we can reduce last tile * @return iterator over mesh nodes indices */ private Iterable<Range> nodesIndices(final int minIndex, final int maxIndex, final boolean truncateLast) { final int first; if (truncateLast) { // truncate last tile rather than balance tiles around the zone of interest first = minIndex; } else { // balance tiles around the zone of interest rather than truncate last tile // number of tiles needed to cover the full indices range final int range = maxIndex - minIndex; final int nbTiles = (range + quantization - 1) / quantization; // extra nodes that must be added to complete the tiles final int extraNodes = nbTiles * quantization - range; // balance the extra nodes before min index and after maxIndex final int extraBefore = (extraNodes + 1) / 2; first = minIndex - extraBefore; } return new Iterable<Range>() { /** {@inheritDoc} */ @Override public Iterator<Range> iterator() { return new Iterator<Range>() { private int nextLower = first; /** {@inheritDoc} */ @Override public boolean hasNext() { return nextLower < maxIndex; } /** {@inheritDoc} */ @Override public Range next() { if (nextLower >= maxIndex) { throw new NoSuchElementException(); } final int lower = nextLower; nextLower += quantization; if (truncateLast && nextLower > maxIndex && lower < maxIndex) { // truncate last tile nextLower = maxIndex; } return new Range(lower, nextLower); } /** {@inheritDoc} */ @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } /** Local class for a range of indices to be used for building a tile. */ private static class Range { /** Lower index. */ private final int lower; /** Upper index. */ private final int upper; /** Simple constructor. * @param lower lower index * @param upper upper index */ Range(final int lower, final int upper) { this.lower = lower; this.upper = upper; } } /** Local class for a pair of ranges of indices to be used for building a tile. */ private static class RangePair { /** Across range. */ private final Range across; /** Along range. */ private final Range along; /** Simple constructor. * @param across across range * @param along along range */ RangePair(final Range across, final Range along) { this.across = across; this.along = along; } } }
apache-2.0
billdawson/tidevtools
templates/one_heavy_window_mapview/app.js
232
/*global Ti, Titanium, alert, JSON */ Titanium.UI.setBackgroundColor('#000'); var win = Titanium.UI.createWindow({ title:'Map Test', backgroundColor:'#fff', fullscreen: true, exitOnClose: true, url: 'win.js' }); win.open();
apache-2.0
bonvoathtanson/mini_pos
app/Models/Import.php
741
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Import extends Model { protected $table = 'Imports'; protected $primaryKey = 'Id'; public $timestamps = false; public static function rules() { $rules = array( 'ImportDate' => 'required', 'SupplierId' => 'required', 'ItemId' => 'required', 'Quantity' => 'required', 'SalePrice' => 'required' ); return $rules; } public function Supplier() { return $this->belongsTo('App\Models\Supplier', 'SupplierId'); } public function Item() { return $this->belongsTo('App\Models\Item', 'ItemId'); } }
apache-2.0
xxlabaza/ping
src/main/java/ru/xxlabaza/test/ping/pitcher/PitcherCommandExecutor.java
2601
/* * Copyright 2017 Artem Labazin <xxlabaza@gmail.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.xxlabaza.test.ping.pitcher; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import java.util.concurrent.Executors; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import lombok.Builder; import lombok.Value; import lombok.extern.slf4j.Slf4j; import lombok.val; import ru.xxlabaza.test.ping.CommandExecutor; /** * The class represents a pitcher command. * <p> * It creates a scheduled thread pool, for periodical submitting {@link MessageSenderTask} * * @see CommandExecutor * * @author Artem Labazin <xxlabaza@gmail.com> * @since 25.06.2017 */ @Slf4j @Value @Builder public class PitcherCommandExecutor implements CommandExecutor { PitcherCommandOptions options; @Override public void execute () { log.info("pitcher.PitcherCommandExecutor.greeting"); log.debug("pitcher.PitcherCommandExecutor.options", options); val statisticHolder = new Statistic(); val sendMessageTask = MessageSenderTask.builder() .inetAddress(options.getHostname()) .port(options.getPort()) .messageSize(options.getSize()) .statistic(statisticHolder) .build(); val period = 1000 / options.getMessagePerSecond(); val tasksThreadPool = new ThreadPoolExecutor( 1, options.getMessagePerSecond() * 4, 20L, SECONDS, new SynchronousQueue<Runnable>() ); Executors.newSingleThreadScheduledExecutor() .scheduleAtFixedRate(() -> tasksThreadPool.execute(sendMessageTask), 0, period, MILLISECONDS); val statisticEchoTask = StatisticEchoTask.builder() .statistic(statisticHolder) .build(); Executors.newSingleThreadScheduledExecutor() .scheduleAtFixedRate(statisticEchoTask, 1, 1, SECONDS); } }
apache-2.0
Blazemeter/jmeter-bzm-plugins
sense-uploader/src/test/java/com/blazemeter/api/explorer/BZAObjectTest.java
841
package com.blazemeter.api.explorer; import kg.apc.jmeter.http.HttpUtils; import kg.apc.jmeter.reporters.notifier.StatusNotifierCallbackTest; import static org.junit.Assert.*; public class BZAObjectTest { @org.junit.Test public void test() throws Exception { HttpUtils httpUtils = new HttpUtils(new StatusNotifierCallbackTest.StatusNotifierCallbackImpl(), "", ""); BZAObject entity = new BZAObject(httpUtils, "id", "name"); assertEquals(httpUtils, entity.getHttpUtils()); assertEquals("id", entity.getId()); assertEquals("name", entity.getName()); entity.setHttpUtils(null); entity.setId("id1"); entity.setName("name1"); assertNull(entity.getHttpUtils()); assertEquals("id1", entity.getId()); assertEquals("name1", entity.getName()); } }
apache-2.0
ampproject/amppackager
vendor/github.com/sacloud/libsacloud/sacloud/bridge.go
1414
// Copyright 2016-2020 The Libsacloud 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 sacloud import ( "encoding/json" ) // Bridge ブリッジ type Bridge struct { *Resource // ID propName // 名称 propDescription // 説明 propServiceClass // サービスクラス propRegion // リージョン propCreatedAt // 作成日時 Info *struct { // インフォ Switches []*struct { // 接続スイッチリスト *Switch // スイッチ ID json.Number `json:",omitempty"` // (HACK) ID } } SwitchInZone *struct { // ゾーン内接続スイッチ *Resource // ID propScope // スコープ Name string `json:",omitempty"` // 名称 ServerCount int `json:",omitempty"` // 接続サーバー数 ApplianceCount int `json:",omitempty"` // 接続アプライアンス数 } }
apache-2.0
xfournet/intellij-community
python/testData/intentions/PyAnnotateVariableTypeIntentionTest/typeCommentLocalSimpleAssignmentTargetInParentheses_after.py
79
from typing import Any def func(): (var) = 'spam' # type: [Any] var
apache-2.0
motorina0/flowable-engine
modules/flowable-cdi/src/test/java/org/flowable/cdi/test/api/annotation/TaskIdTest.java
1368
/* 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.flowable.cdi.test.api.annotation; import org.flowable.cdi.BusinessProcess; import org.flowable.cdi.test.CdiFlowableTestCase; import org.flowable.engine.test.Deployment; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Daniel Meyer */ public class TaskIdTest extends CdiFlowableTestCase { @Test @Deployment public void testTaskIdInjectable() { BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class); businessProcess.startProcessByKey("keyOfTheProcess"); businessProcess.startTask(taskService.createTaskQuery().singleResult().getId()); // assert that now the 'taskId'-bean can be looked up assertNotNull(getBeanInstance("taskId")); businessProcess.completeTask(); } }
apache-2.0
stevemanderson/googleads-dotnet-lib
examples/Dfp/CSharp/v201502/UserTeamAssociationService/CreateUserTeamAssociations.cs
3840
// 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. // Author: Anash P. Oommen using Google.Api.Ads.Dfp.Lib; using Google.Api.Ads.Dfp.v201502; using System; namespace Google.Api.Ads.Dfp.Examples.CSharp.v201502 { /// <summary> /// This code example adds a user to a team by creating an association /// between the two. To determine which teams exist, run GetAllTeams.cs. To /// determine which users exist, run GetAllUsers.cs. /// /// Tags: UserTeamAssociationService.createUserTeamAssociations /// </summary> class CreateUserTeamAssociations : SampleBase { /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example adds a user to a team by creating an association between the " + "two. To determine which teams exist, run GetAllTeams.cs. To determine which users " + "exist, run GetAllUsers.cs."; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { SampleBase codeExample = new CreateUserTeamAssociations(); Console.WriteLine(codeExample.Description); codeExample.Run(new DfpUser()); } /// <summary> /// Run the code example. /// </summary> /// <param name="dfpUser">The DFP user object running the code example.</param> public override void Run(DfpUser dfpUser) { // Get the UserTeamAssociationService. UserTeamAssociationService userTeamAssociationService = (UserTeamAssociationService) dfpUser.GetService(DfpService.v201502.UserTeamAssociationService); // Set the users and team to add them to. long teamId = long.Parse(_T("INSERT_TEAM_ID_HERE")); long[] userIds = new long[] {long.Parse(_T("INSERT_USER_ID_HERE"))}; // Create an array to store local user team association objects. UserTeamAssociation[] userTeamAssociations = new UserTeamAssociation[userIds.Length]; // For each user, associate it with the given team. int i = 0; foreach (long userId in userIds) { UserTeamAssociation userTeamAssociation = new UserTeamAssociation(); userTeamAssociation.userId = userId; userTeamAssociation.teamId = teamId; userTeamAssociations[i++] = userTeamAssociation; } try { // Create the user team associations on the server. userTeamAssociations = userTeamAssociationService.createUserTeamAssociations(userTeamAssociations); if (userTeamAssociations != null) { foreach (UserTeamAssociation userTeamAssociation in userTeamAssociations) { Console.WriteLine("A user team association between user with ID \"{0}\" and team " + "with ID \"{1}\" was created.", userTeamAssociation.userId, userTeamAssociation.teamId); } } else { Console.WriteLine("No user team associations created."); } } catch (Exception ex) { Console.WriteLine("Failed to create user team associations. Exception says \"{0}\"", ex.Message); } } } }
apache-2.0
pkarmstr/NYBC
solr-4.2.1/lucene/queryparser/src/java/org/apache/lucene/queryparser/complexPhrase/ComplexPhraseQueryParser.java
14932
package org.apache.lucene.queryparser.complexPhrase; /* * 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 java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.MultiTermQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TermRangeQuery; import org.apache.lucene.search.spans.SpanNearQuery; import org.apache.lucene.search.spans.SpanNotQuery; import org.apache.lucene.search.spans.SpanOrQuery; import org.apache.lucene.search.spans.SpanQuery; import org.apache.lucene.search.spans.SpanTermQuery; import org.apache.lucene.util.Version; /** * QueryParser which permits complex phrase query syntax eg "(john jon * jonathan~) peters*". * <p> * Performs potentially multiple passes over Query text to parse any nested * logic in PhraseQueries. - First pass takes any PhraseQuery content between * quotes and stores for subsequent pass. All other query content is parsed as * normal - Second pass parses any stored PhraseQuery content, checking all * embedded clauses are referring to the same field and therefore can be * rewritten as Span queries. All PhraseQuery clauses are expressed as * ComplexPhraseQuery objects * </p> * <p> * This could arguably be done in one pass using a new QueryParser but here I am * working within the constraints of the existing parser as a base class. This * currently simply feeds all phrase content through an analyzer to select * phrase terms - any "special" syntax such as * ~ * etc are not given special * status * </p> * */ public class ComplexPhraseQueryParser extends QueryParser { private ArrayList<ComplexPhraseQuery> complexPhrases = null; private boolean isPass2ResolvingPhrases; private ComplexPhraseQuery currentPhraseQuery = null; public ComplexPhraseQueryParser(Version matchVersion, String f, Analyzer a) { super(matchVersion, f, a); } @Override protected Query getFieldQuery(String field, String queryText, int slop) { ComplexPhraseQuery cpq = new ComplexPhraseQuery(field, queryText, slop); complexPhrases.add(cpq); // add to list of phrases to be parsed once // we // are through with this pass return cpq; } @Override public Query parse(String query) throws ParseException { if (isPass2ResolvingPhrases) { MultiTermQuery.RewriteMethod oldMethod = getMultiTermRewriteMethod(); try { // Temporarily force BooleanQuery rewrite so that Parser will // generate visible // collection of terms which we can convert into SpanQueries. // ConstantScoreRewrite mode produces an // opaque ConstantScoreQuery object which cannot be interrogated for // terms in the same way a BooleanQuery can. // QueryParser is not guaranteed threadsafe anyway so this temporary // state change should not // present an issue setMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); return super.parse(query); } finally { setMultiTermRewriteMethod(oldMethod); } } // First pass - parse the top-level query recording any PhraseQuerys // which will need to be resolved complexPhrases = new ArrayList<ComplexPhraseQuery>(); Query q = super.parse(query); // Perform second pass, using this QueryParser to parse any nested // PhraseQueries with different // set of syntax restrictions (i.e. all fields must be same) isPass2ResolvingPhrases = true; try { for (Iterator<ComplexPhraseQuery> iterator = complexPhrases.iterator(); iterator.hasNext();) { currentPhraseQuery = iterator.next(); // in each phrase, now parse the contents between quotes as a // separate parse operation currentPhraseQuery.parsePhraseElements(this); } } finally { isPass2ResolvingPhrases = false; } return q; } // There is No "getTermQuery throws ParseException" method to override so // unfortunately need // to throw a runtime exception here if a term for another field is embedded // in phrase query @Override protected Query newTermQuery(Term term) { if (isPass2ResolvingPhrases) { try { checkPhraseClauseIsForSameField(term.field()); } catch (ParseException pe) { throw new RuntimeException("Error parsing complex phrase", pe); } } return super.newTermQuery(term); } // Helper method used to report on any clauses that appear in query syntax private void checkPhraseClauseIsForSameField(String field) throws ParseException { if (!field.equals(currentPhraseQuery.field)) { throw new ParseException("Cannot have clause for field \"" + field + "\" nested in phrase " + " for field \"" + currentPhraseQuery.field + "\""); } } @Override protected Query getWildcardQuery(String field, String termStr) throws ParseException { if (isPass2ResolvingPhrases) { checkPhraseClauseIsForSameField(field); } return super.getWildcardQuery(field, termStr); } @Override protected Query getRangeQuery(String field, String part1, String part2, boolean startInclusive, boolean endInclusive) throws ParseException { if (isPass2ResolvingPhrases) { checkPhraseClauseIsForSameField(field); } return super.getRangeQuery(field, part1, part2, startInclusive, endInclusive); } @Override protected Query newRangeQuery(String field, String part1, String part2, boolean startInclusive, boolean endInclusive) { if (isPass2ResolvingPhrases) { // Must use old-style RangeQuery in order to produce a BooleanQuery // that can be turned into SpanOr clause TermRangeQuery rangeQuery = TermRangeQuery.newStringRange(field, part1, part2, startInclusive, endInclusive); rangeQuery.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); return rangeQuery; } return super.newRangeQuery(field, part1, part2, startInclusive, endInclusive); } @Override protected Query getFuzzyQuery(String field, String termStr, float minSimilarity) throws ParseException { if (isPass2ResolvingPhrases) { checkPhraseClauseIsForSameField(field); } return super.getFuzzyQuery(field, termStr, minSimilarity); } /* * Used to handle the query content in between quotes and produced Span-based * interpretations of the clauses. */ static class ComplexPhraseQuery extends Query { String field; String phrasedQueryStringContents; int slopFactor; private Query contents; public ComplexPhraseQuery(String field, String phrasedQueryStringContents, int slopFactor) { super(); this.field = field; this.phrasedQueryStringContents = phrasedQueryStringContents; this.slopFactor = slopFactor; } // Called by ComplexPhraseQueryParser for each phrase after the main // parse // thread is through protected void parsePhraseElements(QueryParser qp) throws ParseException { // TODO ensure that field-sensitivity is preserved ie the query // string below is parsed as // field+":("+phrasedQueryStringContents+")" // but this will need code in rewrite to unwrap the first layer of // boolean query contents = qp.parse(phrasedQueryStringContents); } @Override public Query rewrite(IndexReader reader) throws IOException { // ArrayList spanClauses = new ArrayList(); if (contents instanceof TermQuery) { return contents; } // Build a sequence of Span clauses arranged in a SpanNear - child // clauses can be complex // Booleans e.g. nots and ors etc int numNegatives = 0; if (!(contents instanceof BooleanQuery)) { throw new IllegalArgumentException("Unknown query type \"" + contents.getClass().getName() + "\" found in phrase query string \"" + phrasedQueryStringContents + "\""); } BooleanQuery bq = (BooleanQuery) contents; BooleanClause[] bclauses = bq.getClauses(); SpanQuery[] allSpanClauses = new SpanQuery[bclauses.length]; // For all clauses e.g. one* two~ for (int i = 0; i < bclauses.length; i++) { // HashSet bclauseterms=new HashSet(); Query qc = bclauses[i].getQuery(); // Rewrite this clause e.g one* becomes (one OR onerous) qc = qc.rewrite(reader); if (bclauses[i].getOccur().equals(BooleanClause.Occur.MUST_NOT)) { numNegatives++; } if (qc instanceof BooleanQuery) { ArrayList<SpanQuery> sc = new ArrayList<SpanQuery>(); addComplexPhraseClause(sc, (BooleanQuery) qc); if (sc.size() > 0) { allSpanClauses[i] = sc.get(0); } else { // Insert fake term e.g. phrase query was for "Fred Smithe*" and // there were no "Smithe*" terms - need to // prevent match on just "Fred". allSpanClauses[i] = new SpanTermQuery(new Term(field, "Dummy clause because no terms found - must match nothing")); } } else { if (qc instanceof TermQuery) { TermQuery tq = (TermQuery) qc; allSpanClauses[i] = new SpanTermQuery(tq.getTerm()); } else { throw new IllegalArgumentException("Unknown query type \"" + qc.getClass().getName() + "\" found in phrase query string \"" + phrasedQueryStringContents + "\""); } } } if (numNegatives == 0) { // The simple case - no negative elements in phrase return new SpanNearQuery(allSpanClauses, slopFactor, true); } // Complex case - we have mixed positives and negatives in the // sequence. // Need to return a SpanNotQuery ArrayList<SpanQuery> positiveClauses = new ArrayList<SpanQuery>(); for (int j = 0; j < allSpanClauses.length; j++) { if (!bclauses[j].getOccur().equals(BooleanClause.Occur.MUST_NOT)) { positiveClauses.add(allSpanClauses[j]); } } SpanQuery[] includeClauses = positiveClauses .toArray(new SpanQuery[positiveClauses.size()]); SpanQuery include = null; if (includeClauses.length == 1) { include = includeClauses[0]; // only one positive clause } else { // need to increase slop factor based on gaps introduced by // negatives include = new SpanNearQuery(includeClauses, slopFactor + numNegatives, true); } // Use sequence of positive and negative values as the exclude. SpanNearQuery exclude = new SpanNearQuery(allSpanClauses, slopFactor, true); SpanNotQuery snot = new SpanNotQuery(include, exclude); return snot; } private void addComplexPhraseClause(List<SpanQuery> spanClauses, BooleanQuery qc) { ArrayList<SpanQuery> ors = new ArrayList<SpanQuery>(); ArrayList<SpanQuery> nots = new ArrayList<SpanQuery>(); BooleanClause[] bclauses = qc.getClauses(); // For all clauses e.g. one* two~ for (int i = 0; i < bclauses.length; i++) { Query childQuery = bclauses[i].getQuery(); // select the list to which we will add these options ArrayList<SpanQuery> chosenList = ors; if (bclauses[i].getOccur() == BooleanClause.Occur.MUST_NOT) { chosenList = nots; } if (childQuery instanceof TermQuery) { TermQuery tq = (TermQuery) childQuery; SpanTermQuery stq = new SpanTermQuery(tq.getTerm()); stq.setBoost(tq.getBoost()); chosenList.add(stq); } else if (childQuery instanceof BooleanQuery) { BooleanQuery cbq = (BooleanQuery) childQuery; addComplexPhraseClause(chosenList, cbq); } else { // TODO alternatively could call extract terms here? throw new IllegalArgumentException("Unknown query type:" + childQuery.getClass().getName()); } } if (ors.size() == 0) { return; } SpanOrQuery soq = new SpanOrQuery(ors .toArray(new SpanQuery[ors.size()])); if (nots.size() == 0) { spanClauses.add(soq); } else { SpanOrQuery snqs = new SpanOrQuery(nots .toArray(new SpanQuery[nots.size()])); SpanNotQuery snq = new SpanNotQuery(soq, snqs); spanClauses.add(snq); } } @Override public String toString(String field) { return "\"" + phrasedQueryStringContents + "\""; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((field == null) ? 0 : field.hashCode()); result = prime * result + ((phrasedQueryStringContents == null) ? 0 : phrasedQueryStringContents.hashCode()); result = prime * result + slopFactor; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ComplexPhraseQuery other = (ComplexPhraseQuery) obj; if (field == null) { if (other.field != null) return false; } else if (!field.equals(other.field)) return false; if (phrasedQueryStringContents == null) { if (other.phrasedQueryStringContents != null) return false; } else if (!phrasedQueryStringContents .equals(other.phrasedQueryStringContents)) return false; if (slopFactor != other.slopFactor) return false; return true; } } }
apache-2.0
Koichi-Kobayashi/AipoReminder
AlertWindow/Properties/AssemblyInfo.cs
1768
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("AlertWindow")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AlertWindow")] [assembly: AssemblyCopyright("© 2010 k.kobayashi")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です [assembly: Guid("dac0c24d-3c26-4e41-9e98-7339c109e292")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // Major Version // Minor Version // Build Number // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] // AssemblyVersionが変わると設定ファイルのパスが変わってしまうのでこのままで固定 [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
jaxzin/daytrader
javaee6/modules/web/src/main/java/org/apache/geronimo/daytrader/javaee6/core/api/TradeServices.java
12427
/** * 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.geronimo.daytrader.javaee6.core.api; import java.math.BigDecimal; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.Collection; import org.apache.geronimo.daytrader.javaee6.entities.*; import org.apache.geronimo.daytrader.javaee6.core.beans.MarketSummaryDataBean; import org.apache.geronimo.daytrader.javaee6.core.beans.RunStatsDataBean; /** * TradeServices interface specifies the business methods provided by the Trade online broker application. * These business methods represent the features and operations that can be performed by customers of * the brokerage such as login, logout, get a stock quote, buy or sell a stock, etc. * This interface is implemented by {@link Trade} providing an EJB implementation of these * business methods and also by {@link TradeDirect} providing a JDBC implementation. * * @see Trade * @see TradeDirect * */ public interface TradeServices extends Remote { /** * Compute and return a snapshot of the current market conditions * This includes the TSIA - an index of the price of the top 100 Trade stock quotes * The openTSIA ( the index at the open) * The volume of shares traded, * Top Stocks gain and loss * * @return A snapshot of the current market summary */ public MarketSummaryDataBean getMarketSummary() throws Exception, RemoteException; /** * Purchase a stock and create a new holding for the given user. * Given a stock symbol and quantity to purchase, retrieve the current quote price, * debit the user's account balance, and add holdings to user's portfolio. * buy/sell are asynchronous, using J2EE messaging, * A new order is created and submitted for processing to the TradeBroker * * @param userID the customer requesting the stock purchase * @param symbol the symbol of the stock being purchased * @param quantity the quantity of shares to purchase * @return OrderDataBean providing the status of the newly created buy order */ public OrderDataBean buy(String userID, String symbol, double quantity, int orderProcessingMode) throws Exception, RemoteException; /** * Sell a stock holding and removed the holding for the given user. * Given a Holding, retrieve current quote, credit user's account, * and reduce holdings in user's portfolio. * * @param userID the customer requesting the sell * @param holdingID the users holding to be sold * @return OrderDataBean providing the status of the newly created sell order */ public OrderDataBean sell(String userID, Integer holdingID, int orderProcessingMode) throws Exception, RemoteException; /** * Queue the Order identified by orderID to be processed * * Orders are submitted through JMS to a Trading Broker * and completed asynchronously. This method queues the order for processing * * The boolean twoPhase specifies to the server implementation whether or not the * method is to participate in a global transaction * * @param orderID the Order being queued for processing * @return OrderDataBean providing the status of the completed order */ public void queueOrder(Integer orderID, boolean twoPhase) throws Exception, RemoteException; /** * Complete the Order identefied by orderID * Orders are submitted through JMS to a Trading agent * and completed asynchronously. This method completes the order * For a buy, the stock is purchased creating a holding and the users account is debited * For a sell, the stock holding is removed and the users account is credited with the proceeds * * The boolean twoPhase specifies to the server implementation whether or not the * method is to participate in a global transaction * * @param orderID the Order to complete * @return OrderDataBean providing the status of the completed order */ public OrderDataBean completeOrder(Integer orderID, boolean twoPhase) throws Exception, RemoteException; /** * Cancel the Order identefied by orderID * * The boolean twoPhase specifies to the server implementation whether or not the * method is to participate in a global transaction * * @param orderID the Order to complete * @return OrderDataBean providing the status of the completed order */ public void cancelOrder(Integer orderID, boolean twoPhase) throws Exception, RemoteException; /** * Signify an order has been completed for the given userID * * @param userID the user for which an order has completed * @param orderID the order which has completed * */ public void orderCompleted(String userID, Integer orderID) throws Exception, RemoteException; /** * Get the collection of all orders for a given account * * @param userID the customer account to retrieve orders for * @return Collection OrderDataBeans providing detailed order information */ public Collection getOrders(String userID) throws Exception, RemoteException; /** * Get the collection of completed orders for a given account that need to be alerted to the user * * @param userID the customer account to retrieve orders for * @return Collection OrderDataBeans providing detailed order information */ public Collection getClosedOrders(String userID) throws Exception, RemoteException; /** * Given a market symbol, price, and details, create and return a new {@link QuoteDataBean} * * @param symbol the symbol of the stock * @param price the current stock price * @param details a short description of the stock or company * @return a new QuoteDataBean or null if Quote could not be created */ public QuoteDataBean createQuote(String symbol, String companyName, BigDecimal price) throws Exception, RemoteException; /** * Return a {@link QuoteDataBean} describing a current quote for the given stock symbol * * @param symbol the stock symbol to retrieve the current Quote * @return the QuoteDataBean */ public QuoteDataBean getQuote(String symbol) throws Exception, RemoteException; /** * Return a {@link java.util.Collection} of {@link QuoteDataBean} * describing all current quotes * @return A collection of QuoteDataBean */ public Collection getAllQuotes() throws Exception, RemoteException; /** * Update the stock quote price and volume for the specified stock symbol * * @param symbol for stock quote to update * @param price the updated quote price * @return the QuoteDataBean describing the stock */ public QuoteDataBean updateQuotePriceVolume(String symbol, BigDecimal newPrice, double sharesTraded) throws Exception, RemoteException; /** * Return the portfolio of stock holdings for the specified customer * as a collection of HoldingDataBeans * * @param userID the customer requesting the portfolio * @return Collection of the users portfolio of stock holdings */ public Collection getHoldings(String userID) throws Exception, RemoteException; /** * Return a specific user stock holding identifed by the holdingID * * @param holdingID the holdingID to return * @return a HoldingDataBean describing the holding */ public HoldingDataBean getHolding(Integer holdingID) throws Exception, RemoteException; /** * Return an AccountDataBean object for userID describing the account * * @param userID the account userID to lookup * @return User account data in AccountDataBean */ public AccountDataBean getAccountData(String userID) throws Exception, RemoteException; /** * Return an AccountProfileDataBean for userID providing the users profile * * @param userID the account userID to lookup * @param User account profile data in AccountProfileDataBean */ public AccountProfileDataBean getAccountProfileData(String userID) throws Exception, RemoteException; /** * Update userID's account profile information using the provided AccountProfileDataBean object * * @param userID the account userID to lookup * @param User account profile data in AccountProfileDataBean */ public AccountProfileDataBean updateAccountProfile(AccountProfileDataBean profileData) throws Exception, RemoteException; /** * Attempt to authenticate and login a user with the given password * * @param userID the customer to login * @param password the password entered by the customer for authentication * @return User account data in AccountDataBean */ public AccountDataBean login(String userID, String password) throws Exception, RemoteException; /** * Attempt to authenticate and login a user with the given external auth * * @param provider the external authentication provider * @param uid the external uid * @return User account data in AccountDataBean */ public AccountDataBean loginExt(ExternalAuthProvider provider, String uid) throws Exception, RemoteException; /** * Logout the given user * * @param userID the customer to logout * @return the login status */ public void logout(String userID) throws Exception, RemoteException; /** * Register a new Trade customer. * Create a new user profile, user registry entry, account with initial balance, * and empty portfolio. * * @param userID the new customer to register * @param password the customers password * @param fullname the customers fullname * @param address the customers street address * @param email the customers email address * @param creditcard the customers creditcard number * @param openBalance the amount to charge to the customers credit to open the account and set the initial balance * @param provider the external authorization provider (optional) * @param uid the external authorization user id (optional) * @param token the external authorization token (optional) * @return the userID if successful, null otherwise */ public AccountDataBean register(String userID, String password, String fullname, String address, String email, String creditcard, BigDecimal openBalance, ExternalAuthProvider provider, String uid, String token) throws Exception, RemoteException; /** * Reset the TradeData by * - removing all newly registered users by scenario servlet * (i.e. users with userID's beginning with "ru:") * * - removing all buy/sell order pairs * - setting logoutCount = loginCount * * return statistics for this benchmark run */ public RunStatsDataBean resetTrade(boolean deleteAll) throws Exception, RemoteException; void createExternalAuth(ExternalAuthDataBean externalAuth, String userID) throws Exception, RemoteException; }
apache-2.0
cuipengpeng/p1-android
src/com/p1/mobile/p1android/net/withclause/WithParam.java
1089
package com.p1.mobile.p1android.net.withclause; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; public class WithParam implements Param { private Set<String> withStrings = new LinkedHashSet<String>(); private static final String SEPARATOR = ";"; private static final String START = "with="; @Override public boolean isEmpty() { return withStrings.isEmpty(); } @Override public void addParam(String param) { if (isEmpty()) { withStrings.add(START); } withStrings.add(param); } @Override public String getParamString() { StringBuilder builder = new StringBuilder(); Iterator<String> iterator = withStrings.iterator(); if(iterator.hasNext()) { builder.append(iterator.next()); } while (iterator.hasNext()) { builder.append(iterator.next()); if (iterator.hasNext()) { builder.append(SEPARATOR); } } return builder.toString(); } }
apache-2.0
istio/client-go
pkg/informers/externalversions/networking/v1alpha3/workloadentry.gen.go
3748
// Copyright Istio 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. // Code generated by informer-gen. DO NOT EDIT. package v1alpha3 import ( "context" time "time" networkingv1alpha3 "istio.io/client-go/pkg/apis/networking/v1alpha3" versioned "istio.io/client-go/pkg/clientset/versioned" internalinterfaces "istio.io/client-go/pkg/informers/externalversions/internalinterfaces" v1alpha3 "istio.io/client-go/pkg/listers/networking/v1alpha3" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" cache "k8s.io/client-go/tools/cache" ) // WorkloadEntryInformer provides access to a shared informer and lister for // WorkloadEntries. type WorkloadEntryInformer interface { Informer() cache.SharedIndexInformer Lister() v1alpha3.WorkloadEntryLister } type workloadEntryInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc namespace string } // NewWorkloadEntryInformer constructs a new informer for WorkloadEntry type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. func NewWorkloadEntryInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewFilteredWorkloadEntryInformer(client, namespace, resyncPeriod, indexers, nil) } // NewFilteredWorkloadEntryInformer constructs a new informer for WorkloadEntry type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. func NewFilteredWorkloadEntryInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { return cache.NewSharedIndexInformer( &cache.ListWatch{ ListFunc: func(options v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.NetworkingV1alpha3().WorkloadEntries(namespace).List(context.TODO(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.NetworkingV1alpha3().WorkloadEntries(namespace).Watch(context.TODO(), options) }, }, &networkingv1alpha3.WorkloadEntry{}, resyncPeriod, indexers, ) } func (f *workloadEntryInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { return NewFilteredWorkloadEntryInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) } func (f *workloadEntryInformer) Informer() cache.SharedIndexInformer { return f.factory.InformerFor(&networkingv1alpha3.WorkloadEntry{}, f.defaultInformer) } func (f *workloadEntryInformer) Lister() v1alpha3.WorkloadEntryLister { return v1alpha3.NewWorkloadEntryLister(f.Informer().GetIndexer()) }
apache-2.0
swanandmehta/SMPA
src/Java/com/smpa/common/JsonUtility.java
1227
package com.smpa.common; import java.io.IOException; import java.io.Reader; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonUtility { private static ObjectMapper mapper = new ObjectMapper(); private JsonUtility(){ } /** * This method will return obj of given parameter t * @param reader Reader * @param t Parameter t * @return object of t * @throws JsonParseException * @throws JsonMappingException * @throws IOException */ @SuppressWarnings("unchecked") public static <T> T jsonToObj(Reader reader, T t) throws JsonParseException, JsonMappingException, IOException{ t = (T) mapper.readValue(reader, t.getClass()); return t; } /** * This function will return json String for given object * @param t Object to consume * @return String of given obj * @throws JsonProcessingException */ public static <T> String objToJson(T t) throws JsonProcessingException{ String jsonString = mapper.writeValueAsString(t); return jsonString; } }
apache-2.0
amit0701/rally
tests/unit/common/db/test_migrations.py
6964
# Copyright (c) 2016 Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for DB migration.""" import pprint import alembic import mock from oslo_db.sqlalchemy import test_migrations import six import sqlalchemy as sa import rally from rally.common import db from rally.common.db.sqlalchemy import api from rally.common.db.sqlalchemy import models from tests.unit import test as rtest class MigrationTestCase(rtest.DBTestCase, test_migrations.ModelsMigrationsSync): """Test for checking of equality models state and migrations. For the opportunistic testing you need to set up a db named 'openstack_citest' with user 'openstack_citest' and password 'openstack_citest' on localhost. The test will then use that db and user/password combo to run the tests. For PostgreSQL on Ubuntu this can be done with the following commands:: sudo -u postgres psql postgres=# create user openstack_citest with createdb login password 'openstack_citest'; postgres=# create database openstack_citest with owner openstack_citest; For MySQL on Ubuntu this can be done with the following commands:: mysql -u root >create database openstack_citest; >grant all privileges on openstack_citest.* to openstack_citest@localhost identified by 'openstack_citest'; Output is a list that contains information about differences between db and models. Output example:: [('add_table', Table('bat', MetaData(bind=None), Column('info', String(), table=<bat>), schema=None)), ('remove_table', Table(u'bar', MetaData(bind=None), Column(u'data', VARCHAR(), table=<bar>), schema=None)), ('add_column', None, 'foo', Column('data', Integer(), table=<foo>)), ('remove_column', None, 'foo', Column(u'old_data', VARCHAR(), table=None)), [('modify_nullable', None, 'foo', u'x', {'existing_server_default': None, 'existing_type': INTEGER()}, True, False)]] * ``remove_*`` means that there is extra table/column/constraint in db; * ``add_*`` means that it is missing in db; * ``modify_*`` means that on column in db is set wrong type/nullable/server_default. Element contains information: - what should be modified, - schema, - table, - column, - existing correct column parameters, - right value, - wrong value. """ def setUp(self): # we change DB metadata in tests so we reload # models to refresh the metadata to it's original state six.moves.reload_module(rally.common.db.sqlalchemy.models) super(MigrationTestCase, self).setUp() self.alembic_config = api._alembic_config() self.engine = api.get_engine() # remove everything from DB and stamp it as 'base' # so that migration (i.e. upgrade up to 'head') # will actually take place db.schema_cleanup() db.schema_stamp("base") def db_sync(self, engine): db.schema_upgrade() def get_engine(self): return self.engine def get_metadata(self): return models.BASE.metadata def include_object(self, object_, name, type_, reflected, compare_to): if type_ == "table" and name == "alembic_version": return False return super(MigrationTestCase, self).include_object( object_, name, type_, reflected, compare_to) def _create_fake_model(self, table_name): type( "FakeModel", (models.BASE, models.RallyBase), {"__tablename__": table_name, "id": sa.Column(sa.Integer, primary_key=True, autoincrement=True)} ) def _get_metadata_diff(self): with self.get_engine().connect() as conn: opts = { "include_object": self.include_object, "compare_type": self.compare_type, "compare_server_default": self.compare_server_default, } mc = alembic.migration.MigrationContext.configure(conn, opts=opts) # compare schemas and fail with diff, if it"s not empty diff = self.filter_metadata_diff( alembic.autogenerate.compare_metadata(mc, self.get_metadata())) return diff @mock.patch("rally.common.db.sqlalchemy.api.Connection.schema_stamp") def test_models_sync(self, mock_connection_schema_stamp): # drop all tables after a test run self.addCleanup(db.schema_cleanup) # run migration scripts self.db_sync(self.get_engine()) diff = self._get_metadata_diff() if diff: msg = pprint.pformat(diff, indent=2, width=20) self.fail( "Models and migration scripts aren't in sync:\n%s" % msg) @mock.patch("rally.common.db.sqlalchemy.api.Connection.schema_stamp") def test_models_sync_negative__missing_table_in_script( self, mock_connection_schema_stamp): # drop all tables after a test run self.addCleanup(db.schema_cleanup) self._create_fake_model("fake_model") # run migration scripts self.db_sync(self.get_engine()) diff = self._get_metadata_diff() self.assertEqual(1, len(diff)) action, object = diff[0] self.assertEqual("add_table", action) self.assertIsInstance(object, sa.Table) self.assertEqual("fake_model", object.name) @mock.patch("rally.common.db.sqlalchemy.api.Connection.schema_stamp") def test_models_sync_negative__missing_model_in_metadata( self, mock_connection_schema_stamp): # drop all tables after a test run self.addCleanup(db.schema_cleanup) table = self.get_metadata().tables["workers"] self.get_metadata().remove(table) # run migration scripts self.db_sync(self.get_engine()) diff = self._get_metadata_diff() self.assertEqual(1, len(diff)) action, object = diff[0] self.assertEqual("remove_table", action) self.assertIsInstance(object, sa.Table) self.assertEqual("workers", object.name)
apache-2.0
lethalskillzz/Baker
app/src/main/java/com/lethalskillzz/baker/di/DatabaseInfo.java
905
/* * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE 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 * * https://mindorks.com/license/apache-v2 * * 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.lethalskillzz.baker.di; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import javax.inject.Qualifier; /** * Created by ibrahimabdulkadir on 19/06/2017. */ @Qualifier @Retention(RetentionPolicy.RUNTIME) public @interface DatabaseInfo { }
apache-2.0
CenPC434/java-tools
en16931-edifact-to-xml/src/main/java/com/mapforce/core/get_fileext.java
2848
/** * core/get_fileext.java * * This file was generated by MapForce 2017sp2. * * YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE * OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION. * * Refer to the MapForce Documentation for further details. * http://www.altova.com/mapforce */ package com.mapforce.core; import com.altova.mapforce.*; import com.altova.types.*; import com.altova.xml.*; import com.altova.text.tablelike.*; import com.altova.text.*; import com.altova.text.edi.*; import java.util.*; public class get_fileext extends com.altova.TraceProvider { static class main implements IEnumerable { java.lang.String var1_filepath; public main(java.lang.String var1_filepath) { this.var1_filepath = var1_filepath; } public IEnumerator enumerator() {return new Enumerator(this);} public static class Enumerator implements IEnumerator { int pos = 0; int state = 2; Object current; main closure; public Enumerator(main closure) { this.closure = closure; } public Object current() {return current;} public int position() {return pos;} public boolean moveNext() throws Exception { while (state != 0) { switch (state) { case 2: if (moveNext_2()) return true; break; case 3: if (moveNext_3()) return true; break; } } return false; } private boolean moveNext_2() throws Exception { state = 0; if (!(com.altova.functions.Core.equalOrGreater(com.mapforce.core.get_position_of_last_delimiter.eval(closure.var1_filepath, "\\", "/"), com.mapforce.core.get_position_of_last_delimiter.eval(closure.var1_filepath, ".", ".")))) {state = 3; return false; } current = ""; pos++; return true; } private boolean moveNext_3() throws Exception { state = 0; current = com.altova.functions.Core.substring(closure.var1_filepath, com.altova.CoreTypes.decimalToDouble(com.mapforce.core.get_position_of_last_delimiter.eval(closure.var1_filepath, ".", ".")), com.altova.CoreTypes.integerToDouble(com.altova.CoreTypes.longToInteger(com.altova.CoreTypes.intToLong(com.altova.functions.Core.stringLength(closure.var1_filepath))))); pos++; return true; } public void close() { try { } catch (Exception e) { } } } } // instances public static IEnumerable create(java.lang.String var1_filepath) { return new main( var1_filepath ); } public static java.lang.String eval(java.lang.String var1_filepath) throws java.lang.Exception { com.altova.mapforce.IEnumerator e = create(var1_filepath).enumerator(); if (e.moveNext()) { java.lang.String result = ((java.lang.String)e.current()); e.close(); return result; } e.close(); throw new com.altova.AltovaException("Expected a function result."); } }
apache-2.0
spinnaker/kayenta
kayenta-signalfx/src/main/java/com/netflix/kayenta/signalfx/security/SignalFxNamedAccountCredentials.java
1462
/* * Copyright (c) 2018 Nike, inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.kayenta.signalfx.security; import com.fasterxml.jackson.annotation.JsonIgnore; import com.netflix.kayenta.retrofit.config.RemoteService; import com.netflix.kayenta.security.AccountCredentials; import com.netflix.kayenta.signalfx.service.SignalFxSignalFlowRemoteService; import java.util.List; import javax.validation.constraints.NotNull; import lombok.Builder; import lombok.Data; import lombok.Singular; @Builder @Data public class SignalFxNamedAccountCredentials implements AccountCredentials<SignalFxCredentials> { @NotNull private String name; @NotNull @Singular private List<Type> supportedTypes; @NotNull private SignalFxCredentials credentials; @NotNull private RemoteService endpoint; @Override public String getType() { return "signalfx"; } @JsonIgnore SignalFxSignalFlowRemoteService signalFlowService; }
apache-2.0
FasterXML/jackson-databind
src/test/java/com/fasterxml/jackson/databind/module/TestCustomEnumKeyDeserializer.java
10038
package com.fasterxml.jackson.databind.module; import java.io.File; import java.io.IOException; import java.util.*; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.exc.InvalidFormatException; import com.fasterxml.jackson.databind.node.ObjectNode; @SuppressWarnings("serial") public class TestCustomEnumKeyDeserializer extends BaseMapTest { @JsonSerialize(using = TestEnumSerializer.class, keyUsing = TestEnumKeySerializer.class) @JsonDeserialize(using = TestEnumDeserializer.class, keyUsing = TestEnumKeyDeserializer.class) public enum TestEnumMixin { } enum KeyEnum { replacements, rootDirectory, licenseString } enum TestEnum { RED("red"), GREEN("green"); private final String code; TestEnum(String code) { this.code = code; } public static TestEnum lookup(String lower) { for (TestEnum item : values()) { if (item.code().equals(lower)) { return item; } } throw new IllegalArgumentException("Invalid code " + lower); } public String code() { return code; } } static class TestEnumSerializer extends JsonSerializer<TestEnum> { @Override public void serialize(TestEnum languageCode, JsonGenerator g, SerializerProvider serializerProvider) throws IOException { g.writeString(languageCode.code()); } @Override public Class<TestEnum> handledType() { return TestEnum.class; } } static class TestEnumKeyDeserializer extends KeyDeserializer { @Override public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException { try { return TestEnum.lookup(key); } catch (IllegalArgumentException e) { return ctxt.handleWeirdKey(TestEnum.class, key, "Unknown code"); } } } static class TestEnumDeserializer extends StdDeserializer<TestEnum> { public TestEnumDeserializer() { super(TestEnum.class); } @Override public TestEnum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { String code = p.getText(); try { return TestEnum.lookup(code); } catch (IllegalArgumentException e) { throw InvalidFormatException.from(p, "Undefined ISO-639 language code", code, TestEnum.class); } } } static class TestEnumKeySerializer extends JsonSerializer<TestEnum> { @Override public void serialize(TestEnum test, JsonGenerator g, SerializerProvider serializerProvider) throws IOException { g.writeFieldName(test.code()); } @Override public Class<TestEnum> handledType() { return TestEnum.class; } } static class Bean { private File rootDirectory; private String licenseString; private Map<TestEnum, Map<String, String>> replacements; public File getRootDirectory() { return rootDirectory; } public void setRootDirectory(File rootDirectory) { this.rootDirectory = rootDirectory; } public String getLicenseString() { return licenseString; } public void setLicenseString(String licenseString) { this.licenseString = licenseString; } public Map<TestEnum, Map<String, String>> getReplacements() { return replacements; } public void setReplacements(Map<TestEnum, Map<String, String>> replacements) { this.replacements = replacements; } } static class TestEnumModule extends SimpleModule { public TestEnumModule() { super(Version.unknownVersion()); } @Override public void setupModule(SetupContext context) { context.setMixInAnnotations(TestEnum.class, TestEnumMixin.class); SimpleSerializers keySerializers = new SimpleSerializers(); keySerializers.addSerializer(new TestEnumKeySerializer()); context.addKeySerializers(keySerializers); } } // for [databind#1441] enum SuperTypeEnum { FOO; } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "@type", defaultImpl = SuperType.class) static class SuperType { public Map<SuperTypeEnum, String> someMap; } /* /********************************************************** /* Test methods /********************************************************** */ // Test passing with the fix public void testWithEnumKeys() throws Exception { ObjectMapper plainObjectMapper = new ObjectMapper(); JsonNode tree = plainObjectMapper.readTree(a2q("{'red' : [ 'a', 'b']}")); ObjectMapper fancyObjectMapper = new ObjectMapper().registerModule(new TestEnumModule()); // this line is might throw with Jackson 2.6.2. Map<TestEnum, Set<String>> map = fancyObjectMapper.convertValue(tree, new TypeReference<Map<TestEnum, Set<String>>>() { } ); assertNotNull(map); } // and another still failing // NOTE: temporarily named as non-test to ignore it; JsonIgnore doesn't work for some reason // public void testWithTree749() throws Exception public void withTree749() throws Exception { ObjectMapper mapper = new ObjectMapper().registerModule(new TestEnumModule()); Map<KeyEnum, Object> inputMap = new LinkedHashMap<KeyEnum, Object>(); Map<TestEnum, Map<String, String>> replacements = new LinkedHashMap<TestEnum, Map<String, String>>(); Map<String, String> reps = new LinkedHashMap<String, String>(); reps.put("1", "one"); replacements.put(TestEnum.GREEN, reps); inputMap.put(KeyEnum.replacements, replacements); JsonNode tree = mapper.valueToTree(inputMap); ObjectNode ob = (ObjectNode) tree; JsonNode inner = ob.get("replacements"); String firstFieldName = inner.fieldNames().next(); assertEquals("green", firstFieldName); } // [databind#1441] public void testCustomEnumKeySerializerWithPolymorphic() throws IOException { SimpleModule simpleModule = new SimpleModule(); simpleModule.addDeserializer(SuperTypeEnum.class, new JsonDeserializer<SuperTypeEnum>() { @Override public SuperTypeEnum deserialize(JsonParser p, DeserializationContext deserializationContext) throws IOException { return SuperTypeEnum.valueOf(p.getText()); } }); ObjectMapper mapper = new ObjectMapper() .registerModule(simpleModule); SuperType superType = mapper.readValue("{\"someMap\": {\"FOO\": \"bar\"}}", SuperType.class); assertEquals("Deserialized someMap.FOO should equal bar", "bar", superType.someMap.get(SuperTypeEnum.FOO)); } // [databind#1445] @SuppressWarnings({ "unchecked", "rawtypes" }) public void testCustomEnumValueAndKeyViaModifier() throws IOException { SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config, final JavaType type, BeanDescription beanDesc, final JsonDeserializer<?> deserializer) { return new JsonDeserializer<Enum>() { @Override public Enum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass(); final String str = p.getValueAsString().toLowerCase(); return KeyEnum.valueOf(rawClass, str); } }; } @Override public KeyDeserializer modifyKeyDeserializer(DeserializationConfig config, final JavaType type, KeyDeserializer deserializer) { if (!type.isEnumType()) { return deserializer; } return new KeyDeserializer() { @Override public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException { Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass(); return Enum.valueOf(rawClass, key.toLowerCase()); } }; } }); ObjectMapper mapper = new ObjectMapper() .registerModule(module); // First, enum value as is KeyEnum key = mapper.readValue(q(KeyEnum.replacements.name().toUpperCase()), KeyEnum.class); assertSame(KeyEnum.replacements, key); // and then as key EnumMap<KeyEnum,String> map = mapper.readValue( a2q("{'REPlaceMENTS':'foobar'}"), new TypeReference<EnumMap<KeyEnum,String>>() { }); assertEquals(1, map.size()); assertSame(KeyEnum.replacements, map.keySet().iterator().next()); } }
apache-2.0
moosbusch/xbLIDO
src/net/opengis/gml/impl/TrackTypeImpl.java
6414
/* * Copyright 2013 Gunnar Kappei. * * 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 net.opengis.gml.impl; /** * An XML TrackType(@http://www.opengis.net/gml). * * This is a complex type. */ public class TrackTypeImpl extends net.opengis.gml.impl.HistoryPropertyTypeImpl implements net.opengis.gml.TrackType { private static final long serialVersionUID = 1L; public TrackTypeImpl(org.apache.xmlbeans.SchemaType sType) { super(sType); } private static final javax.xml.namespace.QName MOVINGOBJECTSTATUS$0 = new javax.xml.namespace.QName("http://www.opengis.net/gml", "MovingObjectStatus"); /** * Gets a List of "MovingObjectStatus" elements */ public java.util.List<net.opengis.gml.MovingObjectStatusType> getMovingObjectStatusList() { final class MovingObjectStatusList extends java.util.AbstractList<net.opengis.gml.MovingObjectStatusType> { @Override public net.opengis.gml.MovingObjectStatusType get(int i) { return TrackTypeImpl.this.getMovingObjectStatusArray(i); } @Override public net.opengis.gml.MovingObjectStatusType set(int i, net.opengis.gml.MovingObjectStatusType o) { net.opengis.gml.MovingObjectStatusType old = TrackTypeImpl.this.getMovingObjectStatusArray(i); TrackTypeImpl.this.setMovingObjectStatusArray(i, o); return old; } @Override public void add(int i, net.opengis.gml.MovingObjectStatusType o) { TrackTypeImpl.this.insertNewMovingObjectStatus(i).set(o); } @Override public net.opengis.gml.MovingObjectStatusType remove(int i) { net.opengis.gml.MovingObjectStatusType old = TrackTypeImpl.this.getMovingObjectStatusArray(i); TrackTypeImpl.this.removeMovingObjectStatus(i); return old; } @Override public int size() { return TrackTypeImpl.this.sizeOfMovingObjectStatusArray(); } } synchronized (monitor()) { check_orphaned(); return new MovingObjectStatusList(); } } /** * Gets array of all "MovingObjectStatus" elements * @deprecated */ @Deprecated public net.opengis.gml.MovingObjectStatusType[] getMovingObjectStatusArray() { synchronized (monitor()) { check_orphaned(); java.util.List<net.opengis.gml.MovingObjectStatusType> targetList = new java.util.ArrayList<net.opengis.gml.MovingObjectStatusType>(); get_store().find_all_element_users(MOVINGOBJECTSTATUS$0, targetList); net.opengis.gml.MovingObjectStatusType[] result = new net.opengis.gml.MovingObjectStatusType[targetList.size()]; targetList.toArray(result); return result; } } /** * Gets ith "MovingObjectStatus" element */ public net.opengis.gml.MovingObjectStatusType getMovingObjectStatusArray(int i) { synchronized (monitor()) { check_orphaned(); net.opengis.gml.MovingObjectStatusType target = null; target = (net.opengis.gml.MovingObjectStatusType)get_store().find_element_user(MOVINGOBJECTSTATUS$0, i); if (target == null) { throw new IndexOutOfBoundsException(); } return target; } } /** * Returns number of "MovingObjectStatus" element */ public int sizeOfMovingObjectStatusArray() { synchronized (monitor()) { check_orphaned(); return get_store().count_elements(MOVINGOBJECTSTATUS$0); } } /** * Sets array of all "MovingObjectStatus" element WARNING: This method is not atomicaly synchronized. */ public void setMovingObjectStatusArray(net.opengis.gml.MovingObjectStatusType[] movingObjectStatusArray) { check_orphaned(); arraySetterHelper(movingObjectStatusArray, MOVINGOBJECTSTATUS$0); } /** * Sets ith "MovingObjectStatus" element */ public void setMovingObjectStatusArray(int i, net.opengis.gml.MovingObjectStatusType movingObjectStatus) { generatedSetterHelperImpl(movingObjectStatus, MOVINGOBJECTSTATUS$0, i, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_ARRAYITEM); } /** * Inserts and returns a new empty value (as xml) as the ith "MovingObjectStatus" element */ public net.opengis.gml.MovingObjectStatusType insertNewMovingObjectStatus(int i) { synchronized (monitor()) { check_orphaned(); net.opengis.gml.MovingObjectStatusType target = null; target = (net.opengis.gml.MovingObjectStatusType)get_store().insert_element_user(MOVINGOBJECTSTATUS$0, i); return target; } } /** * Appends and returns a new empty value (as xml) as the last "MovingObjectStatus" element */ public net.opengis.gml.MovingObjectStatusType addNewMovingObjectStatus() { synchronized (monitor()) { check_orphaned(); net.opengis.gml.MovingObjectStatusType target = null; target = (net.opengis.gml.MovingObjectStatusType)get_store().add_element_user(MOVINGOBJECTSTATUS$0); return target; } } /** * Removes the ith "MovingObjectStatus" element */ public void removeMovingObjectStatus(int i) { synchronized (monitor()) { check_orphaned(); get_store().remove_element(MOVINGOBJECTSTATUS$0, i); } } }
apache-2.0
Gridtec/lambda4j
lambda4j/src-gen/main/java/at/gridtec/lambda4j/function/conversion/ThrowableIntToCharFunction.java
36303
/* * Copyright (c) 2016 Gridtec. 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 at.gridtec.lambda4j.function.conversion; import at.gridtec.lambda4j.Lambda; import at.gridtec.lambda4j.consumer.ThrowableCharConsumer; import at.gridtec.lambda4j.consumer.ThrowableIntConsumer; import at.gridtec.lambda4j.core.exception.ThrownByFunctionalInterfaceException; import at.gridtec.lambda4j.core.util.ThrowableUtils; import at.gridtec.lambda4j.function.ThrowableCharFunction; import at.gridtec.lambda4j.function.ThrowableFunction; import at.gridtec.lambda4j.function.ThrowableIntFunction; import at.gridtec.lambda4j.function.to.ThrowableToCharFunction; import at.gridtec.lambda4j.function.to.ThrowableToIntFunction; import at.gridtec.lambda4j.operator.unary.ThrowableCharUnaryOperator; import at.gridtec.lambda4j.operator.unary.ThrowableIntUnaryOperator; import at.gridtec.lambda4j.predicate.ThrowableCharPredicate; import at.gridtec.lambda4j.predicate.ThrowableIntPredicate; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; /** * Represents an operation that accepts one {@code int}-valued input argument and produces a * {@code char}-valued result which is able to throw any {@link Throwable}. * This is a primitive specialization of {@link ThrowableFunction}. * <p> * This is a {@link FunctionalInterface} whose functional method is {@link #applyAsCharThrows(int)}. * * @param <X> The type of the throwable to be thrown by this function * @see ThrowableFunction */ @SuppressWarnings("unused") @FunctionalInterface public interface ThrowableIntToCharFunction<X extends Throwable> extends Lambda { /** * Constructs a {@link ThrowableIntToCharFunction} based on a lambda expression or a method reference. Thereby the * given lambda expression or method reference is returned on an as-is basis to implicitly transform it to the * desired type. With this method, it is possible to ensure that correct type is used from lambda expression or * method reference. * * @param <X> The type of the throwable to be thrown by this function * @param expression A lambda expression or (typically) a method reference, e.g. {@code this::method} * @return A {@code ThrowableIntToCharFunction} from given lambda expression or method reference. * @implNote This implementation allows the given argument to be {@code null}, but only if {@code null} given, * {@code null} will be returned. * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#syntax">Lambda * Expression</a> * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html">Method Reference</a> */ static <X extends Throwable> ThrowableIntToCharFunction<X> of( @Nullable final ThrowableIntToCharFunction<X> expression) { return expression; } /** * Calls the given {@link ThrowableIntToCharFunction} with the given argument and returns its result. * * @param <X> The type of the throwable to be thrown by this function * @param function The function to be called * @param value The argument to the function * @return The result from the given {@code ThrowableIntToCharFunction}. * @throws NullPointerException If given argument is {@code null} * @throws X Any throwable from this functions action */ static <X extends Throwable> char call(@Nonnull final ThrowableIntToCharFunction<? extends X> function, int value) throws X { Objects.requireNonNull(function); return function.applyAsCharThrows(value); } /** * Creates a {@link ThrowableIntToCharFunction} which always returns a given value. * * @param <X> The type of the throwable to be thrown by this function * @param ret The return value for the constant * @return A {@code ThrowableIntToCharFunction} which always returns a given value. */ @Nonnull static <X extends Throwable> ThrowableIntToCharFunction<X> constant(char ret) { return (value) -> ret; } /** * Applies this function to the given argument. * * @param value The argument to the function * @return The return value from the function, which is its result. * @throws X Any throwable from this functions action */ char applyAsCharThrows(int value) throws X; /** * Returns the number of arguments for this function. * * @return The number of arguments for this function. * @implSpec The default implementation always returns {@code 1}. */ @Nonnegative default int arity() { return 1; } /** * Returns a composed {@link ThrowableToCharFunction} that first applies the {@code before} function to its input, * and then applies this function to the result. * * @param <A> The type of the argument to the given function, and of composed function * @param before The function to apply before this function is applied * @return A composed {@code ThrowableToCharFunction} that first applies the {@code before} function to its input, * and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is able to handle every type. */ @Nonnull default <A> ThrowableToCharFunction<A, X> compose( @Nonnull final ThrowableToIntFunction<? super A, ? extends X> before) { Objects.requireNonNull(before); return (a) -> applyAsCharThrows(before.applyAsIntThrows(a)); } /** * Returns a composed {@link ThrowableBooleanToCharFunction} that first applies the {@code before} function to its * input, and then applies this function to the result. This method is just convenience, to provide the ability to * execute an operation which accepts {@code boolean} input, before this primitive function is executed. * * @param before The function to apply before this function is applied * @return A composed {@code ThrowableBooleanToCharFunction} that first applies the {@code before} function to its * input, and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * boolean}. */ @Nonnull default ThrowableBooleanToCharFunction<X> composeFromBoolean( @Nonnull final ThrowableBooleanToIntFunction<? extends X> before) { Objects.requireNonNull(before); return (value) -> applyAsCharThrows(before.applyAsIntThrows(value)); } /** * Returns a composed {@link ThrowableByteToCharFunction} that first applies the {@code before} function to * its input, and then applies this function to the result. * This method is just convenience, to provide the ability to execute an operation which accepts {@code byte} input, * before this primitive function is executed. * * @param before The function to apply before this function is applied * @return A composed {@code ThrowableByteToCharFunction} that first applies the {@code before} function to its * input, and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * byte}. */ @Nonnull default ThrowableByteToCharFunction<X> composeFromByte( @Nonnull final ThrowableByteToIntFunction<? extends X> before) { Objects.requireNonNull(before); return (value) -> applyAsCharThrows(before.applyAsIntThrows(value)); } /** * Returns a composed {@link ThrowableCharUnaryOperator} that first applies the {@code before} function to * its input, and then applies this function to the result. * This method is just convenience, to provide the ability to execute an operation which accepts {@code char} input, * before this primitive function is executed. * * @param before The function to apply before this function is applied * @return A composed {@code ThrowableCharUnaryOperator} that first applies the {@code before} function to its * input, and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * char}. */ @Nonnull default ThrowableCharUnaryOperator<X> composeFromChar( @Nonnull final ThrowableCharToIntFunction<? extends X> before) { Objects.requireNonNull(before); return (value) -> applyAsCharThrows(before.applyAsIntThrows(value)); } /** * Returns a composed {@link ThrowableDoubleToCharFunction} that first applies the {@code before} function to its * input, and then applies this function to the result. This method is just convenience, to provide the ability to * execute an operation which accepts {@code double} input, before this primitive function is executed. * * @param before The function to apply before this function is applied * @return A composed {@code ThrowableDoubleToCharFunction} that first applies the {@code before} function to its * input, and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * double}. */ @Nonnull default ThrowableDoubleToCharFunction<X> composeFromDouble( @Nonnull final ThrowableDoubleToIntFunction<? extends X> before) { Objects.requireNonNull(before); return (value) -> applyAsCharThrows(before.applyAsIntThrows(value)); } /** * Returns a composed {@link ThrowableFloatToCharFunction} that first applies the {@code before} function to its * input, and then applies this function to the result. This method is just convenience, to provide the ability to * execute an operation which accepts {@code float} input, before this primitive function is executed. * * @param before The function to apply before this function is applied * @return A composed {@code ThrowableFloatToCharFunction} that first applies the {@code before} function to its * input, and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * float}. */ @Nonnull default ThrowableFloatToCharFunction<X> composeFromFloat( @Nonnull final ThrowableFloatToIntFunction<? extends X> before) { Objects.requireNonNull(before); return (value) -> applyAsCharThrows(before.applyAsIntThrows(value)); } /** * Returns a composed {@link ThrowableIntToCharFunction} that first applies the {@code before} operator to * its input, and then applies this function to the result. * This method is just convenience, to provide the ability to execute an operation which accepts {@code int} input, * before this primitive function is executed. * * @param before The operator to apply before this function is applied * @return A composed {@code ThrowableIntToCharFunction} that first applies the {@code before} operator to its * input, and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * int}. */ @Nonnull default ThrowableIntToCharFunction<X> composeFromInt(@Nonnull final ThrowableIntUnaryOperator<? extends X> before) { Objects.requireNonNull(before); return (value) -> applyAsCharThrows(before.applyAsIntThrows(value)); } /** * Returns a composed {@link ThrowableLongToCharFunction} that first applies the {@code before} function to * its input, and then applies this function to the result. * This method is just convenience, to provide the ability to execute an operation which accepts {@code long} input, * before this primitive function is executed. * * @param before The function to apply before this function is applied * @return A composed {@code ThrowableLongToCharFunction} that first applies the {@code before} function to its * input, and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * long}. */ @Nonnull default ThrowableLongToCharFunction<X> composeFromLong( @Nonnull final ThrowableLongToIntFunction<? extends X> before) { Objects.requireNonNull(before); return (value) -> applyAsCharThrows(before.applyAsIntThrows(value)); } /** * Returns a composed {@link ThrowableShortToCharFunction} that first applies the {@code before} function to its * input, and then applies this function to the result. This method is just convenience, to provide the ability to * execute an operation which accepts {@code short} input, before this primitive function is executed. * * @param before The function to apply before this function is applied * @return A composed {@code ThrowableShortToCharFunction} that first applies the {@code before} function to its * input, and then applies this function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code * short}. */ @Nonnull default ThrowableShortToCharFunction<X> composeFromShort( @Nonnull final ThrowableShortToIntFunction<? extends X> before) { Objects.requireNonNull(before); return (value) -> applyAsCharThrows(before.applyAsIntThrows(value)); } /** * Returns a composed {@link ThrowableIntFunction} that first applies this function to its input, and then applies * the {@code after} function to the result. * * @param <S> The type of return value from the {@code after} function, and of the composed function * @param after The function to apply after this function is applied * @return A composed {@code ThrowableIntFunction} that first applies this function to its input, and then applies * the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is able to return every type. */ @Nonnull default <S> ThrowableIntFunction<S, X> andThen( @Nonnull final ThrowableCharFunction<? extends S, ? extends X> after) { Objects.requireNonNull(after); return (value) -> after.applyThrows(applyAsCharThrows(value)); } /** * Returns a composed {@link ThrowableIntPredicate} that first applies this function to its input, and then applies * the {@code after} predicate to the result. This method is just convenience, to provide the ability to transform * this primitive function to an operation returning {@code boolean}. * * @param after The predicate to apply after this function is applied * @return A composed {@code ThrowableIntPredicate} that first applies this function to its input, and then applies * the {@code after} predicate to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * boolean}. */ @Nonnull default ThrowableIntPredicate<X> andThenToBoolean(@Nonnull final ThrowableCharPredicate<? extends X> after) { Objects.requireNonNull(after); return (value) -> after.testThrows(applyAsCharThrows(value)); } /** * Returns a composed {@link ThrowableIntToByteFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. This method is just convenience, to provide the ability to * transform this primitive function to an operation returning {@code byte}. * * @param after The function to apply after this function is applied * @return A composed {@code ThrowableIntToByteFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * byte}. */ @Nonnull default ThrowableIntToByteFunction<X> andThenToByte(@Nonnull final ThrowableCharToByteFunction<? extends X> after) { Objects.requireNonNull(after); return (value) -> after.applyAsByteThrows(applyAsCharThrows(value)); } /** * Returns a composed {@link ThrowableIntToCharFunction} that first applies this function to its input, and then * applies the {@code after} operator to the result. This method is just convenience, to provide the ability to * transform this primitive function to an operation returning {@code char}. * * @param after The operator to apply after this function is applied * @return A composed {@code ThrowableIntToCharFunction} that first applies this function to its input, and then * applies the {@code after} operator to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * char}. */ @Nonnull default ThrowableIntToCharFunction<X> andThenToChar(@Nonnull final ThrowableCharUnaryOperator<? extends X> after) { Objects.requireNonNull(after); return (value) -> after.applyAsCharThrows(applyAsCharThrows(value)); } /** * Returns a composed {@link ThrowableIntToDoubleFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. This method is just convenience, to provide the ability to * transform this primitive function to an operation returning {@code double}. * * @param after The function to apply after this function is applied * @return A composed {@code ThrowableIntToDoubleFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * double}. */ @Nonnull default ThrowableIntToDoubleFunction<X> andThenToDouble( @Nonnull final ThrowableCharToDoubleFunction<? extends X> after) { Objects.requireNonNull(after); return (value) -> after.applyAsDoubleThrows(applyAsCharThrows(value)); } /** * Returns a composed {@link ThrowableIntToFloatFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. This method is just convenience, to provide the ability to * transform this primitive function to an operation returning {@code float}. * * @param after The function to apply after this function is applied * @return A composed {@code ThrowableIntToFloatFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * float}. */ @Nonnull default ThrowableIntToFloatFunction<X> andThenToFloat( @Nonnull final ThrowableCharToFloatFunction<? extends X> after) { Objects.requireNonNull(after); return (value) -> after.applyAsFloatThrows(applyAsCharThrows(value)); } /** * Returns a composed {@link ThrowableIntUnaryOperator} that first applies this function to its input, and then * applies the {@code after} function to the result. This method is just convenience, to provide the ability to * transform this primitive function to an operation returning {@code int}. * * @param after The function to apply after this function is applied * @return A composed {@code ThrowableIntUnaryOperator} that first applies this function to its input, and then * applies the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * int}. */ @Nonnull default ThrowableIntUnaryOperator<X> andThenToInt(@Nonnull final ThrowableCharToIntFunction<? extends X> after) { Objects.requireNonNull(after); return (value) -> after.applyAsIntThrows(applyAsCharThrows(value)); } /** * Returns a composed {@link ThrowableIntToLongFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. This method is just convenience, to provide the ability to * transform this primitive function to an operation returning {@code long}. * * @param after The function to apply after this function is applied * @return A composed {@code ThrowableIntToLongFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * long}. */ @Nonnull default ThrowableIntToLongFunction<X> andThenToLong(@Nonnull final ThrowableCharToLongFunction<? extends X> after) { Objects.requireNonNull(after); return (value) -> after.applyAsLongThrows(applyAsCharThrows(value)); } /** * Returns a composed {@link ThrowableIntToShortFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. This method is just convenience, to provide the ability to * transform this primitive function to an operation returning {@code short}. * * @param after The function to apply after this function is applied * @return A composed {@code ThrowableIntToShortFunction} that first applies this function to its input, and then * applies the {@code after} function to the result. * @throws NullPointerException If given argument is {@code null} * @implSpec The input argument of this method is a able to return primitive values. In this case this is {@code * short}. */ @Nonnull default ThrowableIntToShortFunction<X> andThenToShort( @Nonnull final ThrowableCharToShortFunction<? extends X> after) { Objects.requireNonNull(after); return (value) -> after.applyAsShortThrows(applyAsCharThrows(value)); } /** * Returns a composed {@link ThrowableIntConsumer} that fist applies this function to its input, and then consumes * the result using the given {@link ThrowableCharConsumer}. * * @param consumer The operation which consumes the result from this operation * @return A composed {@code ThrowableIntConsumer} that first applies this function to its input, and then consumes * the result using the given {@code ThrowableCharConsumer}. * @throws NullPointerException If given argument is {@code null} */ @Nonnull default ThrowableIntConsumer<X> consume(@Nonnull final ThrowableCharConsumer<? extends X> consumer) { Objects.requireNonNull(consumer); return (value) -> consumer.acceptThrows(applyAsCharThrows(value)); } /** * Returns a memoized (caching) version of this {@link ThrowableIntToCharFunction}. Whenever it is called, the * mapping between the input parameter and the return value is preserved in a cache, making subsequent calls * returning the memoized value instead of computing the return value again. * <p> * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values * forever. * * @return A memoized (caching) version of this {@code ThrowableIntToCharFunction}. * @implSpec This implementation does not allow the input parameter or return value to be {@code null} for the * resulting memoized function, as the cache used internally does not permit {@code null} keys or values. * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it * thread-safe. */ @Nonnull default ThrowableIntToCharFunction<X> memoized() { if (isMemoized()) { return this; } else { final Map<Integer, Character> cache = new ConcurrentHashMap<>(); final Object lock = new Object(); return (ThrowableIntToCharFunction<X> & Memoized) (value) -> { final char returnValue; synchronized (lock) { returnValue = cache.computeIfAbsent(value, ThrowableFunction.of(this::applyAsCharThrows)); } return returnValue; }; } } /** * Returns a composed {@link ThrowableFunction} which represents this {@link ThrowableIntToCharFunction}. Thereby * the primitive input argument for this function is autoboxed. This method provides the possibility to use this * {@code ThrowableIntToCharFunction} with methods provided by the {@code JDK}. * * @return A composed {@code ThrowableFunction} which represents this {@code ThrowableIntToCharFunction}. */ @Nonnull default ThrowableFunction<Integer, Character, X> boxed() { return this::applyAsCharThrows; } /** * Returns a composed {@link IntToCharFunction} that applies this function to its input and nests the thrown {@link * Throwable} from it. The {@code Throwable} is nested (wrapped) in a {@link ThrownByFunctionalInterfaceException}, * which is constructed from the thrown {@code Throwable}s message and the thrown {@code Throwable} itself. * * @return A composed {@link IntToCharFunction} that applies this function to its input and nests the thrown {@code * Throwable} from it. * @implNote If thrown {@code Throwable} is of type {@link Error} it is thrown as-is and thus not nested. * @see #nest(Function) * @see ThrownByFunctionalInterfaceException */ @Nonnull default IntToCharFunction nest() { return nest(throwable -> new ThrownByFunctionalInterfaceException(throwable.getMessage(), throwable)); } /** * Returns a composed {@link IntToCharFunction} that applies this function to its input and nests the thrown {@link * Throwable} from it using {@code mapper} operation. Thereby {@code mapper} may modify the thrown {@code * Throwable}, regarding its implementation, and returns it nested (wrapped) in a {@link RuntimeException}. * * @param mapper The operation to map the thrown {@code Throwable} to {@code RuntimeException} * @return A composed {@link IntToCharFunction} that applies this function to its input and nests the thrown {@code * Throwable} from it using {@code mapper} operation. * @throws NullPointerException If given argument is {@code null} * @implNote If thrown {@code Throwable} is of type {@link Error} it is thrown as-is and thus not nested. * @see #nest() */ @Nonnull default IntToCharFunction nest(@Nonnull final Function<? super Throwable, ? extends RuntimeException> mapper) { return recover(throwable -> { throw mapper.apply(throwable); }); } /** * Returns a composed {@link IntToCharFunction} that first applies this function to its input, and then applies the * {@code recover} operation if a {@link Throwable} is thrown from this one. The {@code recover} operation is * represented by a curried operation which is called with throwable information and same argument of this * function. * * @param recover The operation to apply if this function throws a {@code Throwable} * @return A composed {@link IntToCharFunction} that first applies this function to its input, and then applies the * {@code recover} operation if a {@code Throwable} is thrown from this one. * @throws NullPointerException If given argument or the returned enclosing function is {@code null} * @implSpec The implementation checks that the returned enclosing function from {@code recover} operation is not * {@code null}. If it is, then a {@link NullPointerException} with appropriate message is thrown. * @implNote If thrown {@code Throwable} is of type {@link Error}, it is thrown as-is and thus not passed to {@code * recover} operation. */ @Nonnull default IntToCharFunction recover(@Nonnull final Function<? super Throwable, ? extends IntToCharFunction> recover) { Objects.requireNonNull(recover); return (value) -> { try { return this.applyAsCharThrows(value); } catch (Error e) { throw e; } catch (Throwable throwable) { final IntToCharFunction function = recover.apply(throwable); Objects.requireNonNull(function, () -> "recover returned null for " + throwable.getClass() + ": " + throwable.getMessage()); return function.applyAsChar(value); } }; } /** * Returns a composed {@link IntToCharFunction} that applies this function to its input and sneakily throws the * thrown {@link Throwable} from it, if it is not of type {@link RuntimeException} or {@link Error}. This means that * each throwable thrown from the returned composed function behaves exactly the same as an <em>unchecked</em> * throwable does. As a result, there is no need to handle the throwable of this function in the returned composed * function by either wrapping it in an <em>unchecked</em> throwable or to declare it in the {@code throws} clause, * as it would be done in a non sneaky throwing function. * <p> * What sneaky throwing simply does, is to fake out the compiler and thus it bypasses the principle of * <em>checked</em> throwables. On the JVM (class file) level, all throwables, checked or not, can be thrown * regardless of the {@code throws} clause of methods, which is why this works at all. * <p> * However, when using this method to get a sneaky throwing function variant of this throwable function, the * following advantages, disadvantages and limitations will apply: * <p> * If the calling-code is to handle the sneakily thrown throwable, it is required to add it to the {@code throws} * clause of the method that applies the returned composed function. The compiler will not force the declaration in * the {@code throws} clause anymore. * <p> * If the calling-code already handles the sneakily thrown throwable, the compiler requires it to be added to the * {@code throws} clause of the method that applies the returned composed function. If not added, the compiler will * error that the caught throwable is never thrown in the corresponding {@code try} block. * <p> * If the returned composed function is directly surrounded by a {@code try}-{@code catch} block to catch the * sneakily thrown throwable from it, the compiler will error that the caught throwable is never thrown in the * corresponding {@code try} block. * <p> * In any case, if the throwable is not added to the to the {@code throws} clause of the method that applies the * returned composed function, the calling-code won't be able to catch the throwable by name. It will bubble and * probably be caught in some {@code catch} statement, catching a base type such as {@code try { ... } * catch(RuntimeException e) { ... }} or {@code try { ... } catch(Exception e) { ... }}, but perhaps this is * intended. * <p> * When the called code never throws the specific throwable that it declares, it should obviously be omitted. For * example: {@code new String(byteArr, "UTF-8") throws UnsupportedEncodingException}, but {@code UTF-8} is * guaranteed by the Java specification to be always present. Here, the {@code throws} declaration is a nuisance and * any solution to silence it with minimal boilerplate is welcome. The throwable should therefore be omitted in the * {@code throws} clause of the method that applies the returned composed function. * <p> * With all that mentioned, the following example will demonstrate this methods correct use: * <pre>{@code * // when called with illegal value ClassNotFoundException is thrown * public Class<?> sneakyThrowingFunctionalInterface(final String className) throws ClassNotFoundException { * return ThrowableFunction.of(Class::forName) // create the correct throwable functional interface * .sneakyThrow() // create a non-throwable variant which is able to sneaky throw (this method) * .apply(className); // apply non-throwable variant -> may sneaky throw a throwable * } * * // call the the method which surround the sneaky throwing functional interface * public void callingMethod() { * try { * final Class<?> clazz = sneakyThrowingFunctionalInterface("some illegal class name"); * // ... do something with clazz ... * } catch(ClassNotFoundException e) { * // ... do something with e ... * } * } * }</pre> * In conclusion, this somewhat contentious ability should be used carefully, of course, with the advantages, * disadvantages and limitations described above kept in mind. * * @return A composed {@link IntToCharFunction} that applies this function to its input and sneakily throws the * thrown {@link Throwable} from it, unless it is of type {@link RuntimeException} or {@link Error}. * @implNote If thrown {@link Throwable} is of type {@link RuntimeException} or {@link Error}, it is thrown as-is * and thus not sneakily thrown. */ @Nonnull default IntToCharFunction sneakyThrow() { return (value) -> { try { return this.applyAsCharThrows(value); } catch (RuntimeException | Error e) { throw e; } catch (Throwable throwable) { throw ThrowableUtils.sneakyThrow(throwable); } }; } }
apache-2.0
oMMu/Ommu-Core
views/zone_country/admin_add.php
562
<?php /** * Ommu Zone Countries (ommu-zone-country) * @var $this ZonecountryController * @var $model OmmuZoneCountry * @var $form CActiveForm * * @author Putra Sudaryanto <putra@sudaryanto.id> * @contact (+62)856-299-4114 * @copyright Copyright (c) 2015 Ommu Platform (www.ommu.co) * @link https://github.com/ommu/mod-core * */ $this->breadcrumbs=array( 'Ommu Zone Countries'=>array('manage'), 'Create', ); ?> <div class="form"> <?php echo $this->renderPartial('/zone_country/_form', array('model'=>$model)); ?> </div>
apache-2.0
jmrozanec/white-bkg-classification
scripts/dl-histograms/04-architecture-06b.py
2177
#TFLearn bug regarding image loading: https://github.com/tflearn/tflearn/issues/180 #Monochromes img-magick: https://poizan.dk/blog/2014/02/28/monochrome-images-in-imagemagick/ #How to persist a model: https://github.com/tflearn/tflearn/blob/master/examples/basics/weights_persistence.py from __future__ import division, print_function, absolute_import import tflearn from tflearn.data_utils import shuffle, to_categorical from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.conv import conv_2d, max_pool_2d from tflearn.layers.normalization import local_response_normalization, batch_normalization from tflearn.layers.estimator import regression from tflearn.data_utils import image_preloader from tflearn.layers.merge_ops import merge train_file = '../../images/sampling/dataset-splits/train-cv-5.txt' test_file = '../../images/sampling/dataset-splits/test-cv-5.txt' channels=1 width=64 height=50 X, Y = image_preloader(train_file, image_shape=(height, width), mode='file', categorical_labels=True, normalize=True) testX, testY = image_preloader(test_file, image_shape=(height, width), mode='file', categorical_labels=True, normalize=True) network = input_data(shape=[None, width, height], name='input') network = tflearn.layers.core.reshape(network, [-1, width, height, 1], name='Reshape') network1 = batch_normalization(conv_2d(network, 64, 1, activation='relu', regularizer="L2")) network2 = batch_normalization(conv_2d(network, 64, 3, activation='relu', regularizer="L2")) network = merge([network1, network2],'concat') #network = batch_normalization(conv_2d(network, 64, 1, activation='relu', regularizer="L2")) network = fully_connected(network, 64, activation='tanh') network = dropout(network, 0.8) network = fully_connected(network, 2, activation='softmax') # Build neural network and train network = regression(network, optimizer='adam', learning_rate=0.001, loss='categorical_crossentropy', name='target') model = tflearn.DNN(network, tensorboard_verbose=0) model.fit(X, Y, n_epoch=5, validation_set=(testX, testY), snapshot_step=10, snapshot_epoch=False, show_metric=True, run_id='white-bkg-6') #epoch=4 => 98%
apache-2.0
j-coll/opencga
opencga-core/src/main/java/org/opencb/opencga/core/models/clinical/Interpretation.java
5265
/* * Copyright 2015-2020 OpenCB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opencb.opencga.core.models.clinical; import org.opencb.biodata.models.clinical.interpretation.*; import org.opencb.opencga.core.models.IPrivateStudyUid; import java.util.List; import java.util.Map; public class Interpretation extends org.opencb.biodata.models.clinical.interpretation.Interpretation implements IPrivateStudyUid { // Private fields private long studyUid; private long uid; private InterpretationInternal internal; public Interpretation() { super(); } public Interpretation(String id, String description, String clinicalAnalysisId, Analyst analyst, InterpretationMethod method, String creationDate, List<ClinicalVariant> primaryFindings, List<ClinicalVariant> secondaryFindings, List<Comment> comments, Map<String, Object> attributes) { super(id, "", description, clinicalAnalysisId, analyst, method, primaryFindings, secondaryFindings, comments, null, creationDate, 0, attributes); } public Interpretation(org.opencb.biodata.models.clinical.interpretation.Interpretation interpretation) { this(interpretation.getId(), interpretation.getDescription(), interpretation.getClinicalAnalysisId(), interpretation.getAnalyst(), interpretation.getMethod(), interpretation.getCreationDate(), interpretation.getPrimaryFindings(), interpretation.getSecondaryFindings(), interpretation.getComments(), interpretation.getAttributes()); } // public Interpretation(org.opencb.biodata.models.clinical.interpretation.Interpretation interpretation) { // this(interpretation.getId(), "", interpretation.getDescription(), interpretation.getClinicalAnalysisId(), // interpretation.getAnalyst(), interpretation.getMethod(),interpretation.getPrimaryFindings(), // interpretation.getSecondaryFindings(), interpretation.getComments(), interpretation.getStatus(), // interpretation.getCreationDate(), interpretation.getVersion(), interpretation.getAttributes()); // } // // public Interpretation(String id, String description, String clinicalAnalysisId, List<DiseasePanel> panels, Software software, // Analyst analyst, List<Software> dependencies, Map<String, Object> filters, String creationDate, // List<ClinicalVariant> primaryFindinds, List<ClinicalVariant> secondaryFindings, // List<ReportedLowCoverage> reportedLowCoverages, List<Comment> comments, Map<String, Object> attributes) { // super(id, "", description, clinicalAnalysisId, software, analyst, dependencies, filters, panels, primaryFindinds, secondaryFindings, // reportedLowCoverages, comments, InterpretationStatus.NOT_REVIEWED, creationDate, 1, attributes); // } // // public Interpretation(String uuid, String id, String description, String clinicalAnalysisId, List<DiseasePanel> panels, Software software, // Analyst analyst, List<Software> dependencies, Map<String, Object> filters, String creationDate, // List<ClinicalVariant> primaryFindinds, List<ClinicalVariant> secondaryFindings, // List<ReportedLowCoverage> reportedLowCoverages, List<Comment> comments, Map<String, Object> attributes, // InterpretationInternal internal) { // super(id, uuid, description, clinicalAnalysisId, software, analyst, dependencies, filters, panels, primaryFindinds, // secondaryFindings, reportedLowCoverages, comments, InterpretationStatus.NOT_REVIEWED, creationDate, 1, attributes); // this.internal = internal; // } @Override public String toString() { final StringBuilder sb = new StringBuilder("Interpretation{"); sb.append("studyUid=").append(studyUid); sb.append(", uid=").append(uid); sb.append(", internal=").append(internal); sb.append('}'); return sb.toString(); } @Override public long getStudyUid() { return studyUid; } @Override public Interpretation setStudyUid(long studyUid) { this.studyUid = studyUid; return this; } @Override public long getUid() { return uid; } @Override public Interpretation setUid(long uid) { this.uid = uid; return this; } public InterpretationInternal getInternal() { return internal; } public Interpretation setInternal(InterpretationInternal internal) { this.internal = internal; return this; } }
apache-2.0
polats/gvr-unity-sdk
Samples/CardboardDesignLab/ustwo-cardboard-unity/Assets/Source/Monoscope/MonoscopicCamera.cs
1031
// Copyright 2014 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. using UnityEngine; using System.Collections; /// <summary> /// Used only for screenshots / video recording in editor /// </summary> public class MonoscopicCamera : MonoBehaviour { public Transform target; public Camera leftEye; public Camera rightEye; void LateUpdate(){ leftEye.enabled = false; rightEye.enabled = false; transform.position = target.position; transform.rotation = target.rotation; } }
apache-2.0
mazhilin/neusoft-knowledge-platform
neusoft-knowledge-service/src/main/java/com/neusoft/knowledge/sys/service/UserRoleService.java
918
package com.neusoft.knowledge.sys.service; import com.neusoft.knowledge.sys.entity.UserRoleEntity; import java.util.List; import java.util.Map; /** * @Title:UserRoleService. * @Content:com.neusoft.knowledge.service.modules.sys.service.UserRoleService * @Description: * @Author:Marklin * @Create-DateTime:2017-10-13 19:25 * @Update-DateTime:2017-10-13 19:25 * @Version:1.0version */ public interface UserRoleService { UserRoleEntity queryObject(String userId); List<UserRoleEntity> queryList(Map<String, Object> map); int queryTotal(Map<String, Object> map); void save(UserRoleEntity userRole); void update(UserRoleEntity userRole); void delete(String userId); void deleteBatch(String[] userIds); void saveOrUpdate(String userId, List<String> roleIdList); /** * 根据用户ID,获取角色ID列表 */ List<String> queryRoleIdList(String userId); }
apache-2.0
puntodesarrollo/taxislibertador
admin/metodoEditar.php
580
<?php $sesion = include $_SERVER['DOCUMENT_ROOT']."/admin/verificarSesion.php"; if($sesion===false){ header("location:/admin/login"); exit; } define ('SITE_ROOT', realpath(dirname(__FILE__))); //Variables album $ID = $_POST["ID"]; $texto1 = $_POST['txtEditorContent']; $texto2 = $_POST['txtEditorContent2']; //Se hace la conexion: include $_SERVER['DOCUMENT_ROOT']."/admin/conexion.php"; $resultado = $con->query("UPDATE about SET quienes='$texto1', history='$texto2' WHERE ID='$ID'"); //redireccionar a programas header("location:/admin/about.php"); ?>
apache-2.0
irudyak/ant-toolkit
dev/modules/native/general/src/main/java/com/anttoolkit/general/tasks/file/FileReadOnlyAttributeTask.java
1388
package com.anttoolkit.general.tasks.file; import java.io.*; import com.anttoolkit.general.tasks.GenericTask; import org.apache.tools.ant.*; public class FileReadOnlyAttributeTask extends GenericTask { private boolean readOnly = false; private String file = null; private String dir = null; public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; } public void setFile(String file) { this.file = file; } public void setDir(String dir) { this.dir = dir; } @Override public void doWork() throws BuildException { if (file != null) { setFileReadOnlyAttr(new File(getFileFullPath(file))); } if (dir != null) { setDirectoryFilesReadOnlyAttr(new File(getFileFullPath(dir))); } } protected void validate() { if (file == null && dir == null) { throw new BuildException("Either file or dir should be specified"); } } private void setFileReadOnlyAttr(File file) { if (file != null && !file.isDirectory()) { file.setWritable(!readOnly); } } private void setDirectoryFilesReadOnlyAttr(File dir) { if (!dir.isDirectory()) { throw new BuildException("Incorrect directory name specified: " + dir); } File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { setDirectoryFilesReadOnlyAttr(file); } else { setFileReadOnlyAttr(file); } } } }
apache-2.0
c340c340/mybatis-3.2.22
src/test/java/com/ibatis/dao/engine/impl/DaoContext.java
3620
/* * Copyright 2009-2012 The MyBatis Team * * 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.ibatis.dao.engine.impl; import com.ibatis.dao.client.Dao; import com.ibatis.dao.client.DaoException; import com.ibatis.dao.client.DaoTransaction; import com.ibatis.dao.engine.transaction.DaoTransactionManager; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class DaoContext { private String id; private StandardDaoManager daoManager; private DaoTransactionManager transactionManager; private ThreadLocal transaction = new ThreadLocal(); private ThreadLocal state = new ThreadLocal(); private Map typeDaoImplMap = new HashMap(); public DaoContext() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public StandardDaoManager getDaoManager() { return daoManager; } public void setDaoManager(StandardDaoManager daoManager) { this.daoManager = daoManager; } public DaoTransactionManager getTransactionManager() { return transactionManager; } public void setTransactionManager(DaoTransactionManager transactionManager) { this.transactionManager = transactionManager; } public void addDao(DaoImpl daoImpl) { if (typeDaoImplMap.containsKey(daoImpl.getDaoInterface())) { throw new DaoException("More than one implementation for '" + daoImpl.getDaoInterface() + "' was configured. " + "Only one implementation per context is allowed."); } typeDaoImplMap.put(daoImpl.getDaoInterface(), daoImpl); } public Dao getDao(Class iface) { DaoImpl impl = (DaoImpl) typeDaoImplMap.get(iface); if (impl == null) { throw new DaoException("There is no DAO implementation found for " + iface + " in this context."); } return impl.getProxy(); } public Iterator getDaoImpls() { return typeDaoImplMap.values().iterator(); } public DaoTransaction getTransaction() { startTransaction(); return (DaoTransaction) transaction.get(); } public void startTransaction() { if (state.get() != DaoTransactionState.ACTIVE) { DaoTransaction trans = transactionManager.startTransaction(); transaction.set(trans); state.set(DaoTransactionState.ACTIVE); daoManager.addContextInTransaction(this); } } public void commitTransaction() { DaoTransaction trans = (DaoTransaction) transaction.get(); if (state.get() == DaoTransactionState.ACTIVE) { transactionManager.commitTransaction(trans); state.set(DaoTransactionState.COMMITTED); } else { state.set(DaoTransactionState.INACTIVE); } } public void endTransaction() { DaoTransaction trans = (DaoTransaction) transaction.get(); if (state.get() == DaoTransactionState.ACTIVE) { try { transactionManager.rollbackTransaction(trans); } finally { state.set(DaoTransactionState.ROLLEDBACK); transaction.set(null); } } else { state.set(DaoTransactionState.INACTIVE); transaction.set(null); } } }
apache-2.0
charles-cooper/idylfin
src/org/apache/commons/math3/stat/clustering/package-info.java
886
/* * 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. */ /** * Clustering algorithms */ package org.apache.commons.math3.stat.clustering;
apache-2.0
staneee/MyBlog.NetCore
MyBlog.Infrastructure/Command/ICommandInvokerFactory.cs
430
namespace MyBlog { /// <summary> /// 命令工作工厂接口 /// </summary> public interface ICommandInvokerFactory { /// <summary> /// 命令处理 /// </summary> /// <typeparam name="TIn"></typeparam> /// <typeparam name="TOut"></typeparam> /// <param name="input"></param> /// <returns></returns> TOut Handle<TIn, TOut>(TIn input); } }
apache-2.0
scnakandala/derby
java/engine/org/apache/derby/jdbc/EmbedXAConnection.java
7023
/* Derby - Class org.apache.derby.jdbc.EmbedXAConnection 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.derby.jdbc; import org.apache.derby.impl.jdbc.Util; import org.apache.derby.iapi.jdbc.BrokeredConnectionControl; import org.apache.derby.iapi.jdbc.EngineConnection; import org.apache.derby.iapi.jdbc.ResourceAdapter; import org.apache.derby.iapi.reference.SQLState; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.PreparedStatement; import java.sql.CallableStatement; import javax.transaction.xa.XAResource; /** -- jdbc 2.0. extension -- */ import javax.sql.XAConnection; /** */ class EmbedXAConnection extends EmbedPooledConnection implements XAConnection { private EmbedXAResource xaRes; EmbedXAConnection(EmbeddedBaseDataSource ds, ResourceAdapter ra, String u, String p, boolean requestPassword) throws SQLException { super(ds, u, p, requestPassword); xaRes = new EmbedXAResource (this, ra); } /** @see BrokeredConnectionControl#isInGlobalTransaction() */ public boolean isInGlobalTransaction() { return isGlobal(); } /** * Check if this connection is part of a global XA transaction. * * @return {@code true} if the transaction is global, {@code false} if the * transaction is local */ private boolean isGlobal() { return xaRes.getCurrentXid () != null; } /* ** XAConnection methods */ public final synchronized XAResource getXAResource() throws SQLException { checkActive(); return xaRes; } /* ** BrokeredConnectionControl api */ /** Allow control over setting auto commit mode. */ public void checkAutoCommit(boolean autoCommit) throws SQLException { if (autoCommit && isGlobal()) throw Util.generateCsSQLException(SQLState.CANNOT_AUTOCOMMIT_XA); super.checkAutoCommit(autoCommit); } /** Are held cursors allowed. If the connection is attached to a global transaction then downgrade the result set holdabilty to CLOSE_CURSORS_AT_COMMIT if downgrade is true, otherwise throw an exception. If the connection is in a local transaction then the passed in holdabilty is returned. */ public int checkHoldCursors(int holdability, boolean downgrade) throws SQLException { if (holdability == ResultSet.HOLD_CURSORS_OVER_COMMIT) { if (isGlobal()) { if (!downgrade) throw Util.generateCsSQLException(SQLState.CANNOT_HOLD_CURSOR_XA); holdability = ResultSet.CLOSE_CURSORS_AT_COMMIT; } } return super.checkHoldCursors(holdability, downgrade); } /** Allow control over creating a Savepoint (JDBC 3.0) */ public void checkSavepoint() throws SQLException { if (isGlobal()) throw Util.generateCsSQLException(SQLState.CANNOT_ROLLBACK_XA); super.checkSavepoint(); } /** Allow control over calling rollback. */ public void checkRollback() throws SQLException { if (isGlobal()) throw Util.generateCsSQLException(SQLState.CANNOT_ROLLBACK_XA); super.checkRollback(); } /** Allow control over calling commit. */ public void checkCommit() throws SQLException { if (isGlobal()) throw Util.generateCsSQLException(SQLState.CANNOT_COMMIT_XA); super.checkCommit(); } /** * @see org.apache.derby.iapi.jdbc.BrokeredConnectionControl#checkClose() */ public void checkClose() throws SQLException { if (isGlobal()) { // It is always OK to close a connection associated with a global // XA transaction, even if it isn't idle, since we still can commit // or roll back the global transaction with the XAResource after // the connection has been closed. } else { super.checkClose(); } } public Connection getConnection() throws SQLException { Connection handle; // Is this just a local transaction? if (!isGlobal()) { handle = super.getConnection(); } else { if (currentConnectionHandle != null) { // this can only happen if someone called start(Xid), // getConnection, getConnection (and we are now the 2nd // getConnection call). // Cannot yank a global connection away like, I don't think... throw Util.generateCsSQLException( SQLState.CANNOT_CLOSE_ACTIVE_XA_CONNECTION); } handle = getNewCurrentConnectionHandle(); } currentConnectionHandle.syncState(); return handle; } /** Wrap and control a Statement */ public Statement wrapStatement(Statement s) throws SQLException { XAStatementControl sc = new XAStatementControl(this, s); return sc.applicationStatement; } /** Wrap and control a PreparedStatement */ public PreparedStatement wrapStatement(PreparedStatement ps, String sql, Object generatedKeys) throws SQLException { ps = super.wrapStatement(ps,sql,generatedKeys); XAStatementControl sc = new XAStatementControl(this, ps, sql, generatedKeys); return (PreparedStatement) sc.applicationStatement; } /** Wrap and control a PreparedStatement */ public CallableStatement wrapStatement(CallableStatement cs, String sql) throws SQLException { cs = super.wrapStatement(cs,sql); XAStatementControl sc = new XAStatementControl(this, cs, sql); return (CallableStatement) sc.applicationStatement; } /** Override getRealConnection to create a a local connection when we are not associated with an XA transaction. This can occur if the application has a Connection object (conn) and the following sequence occurs. conn = xac.getConnection(); xac.start(xid, ...) // do work with conn xac.end(xid, ...); // do local work with conn // need to create new connection here. */ public EngineConnection getRealConnection() throws SQLException { EngineConnection rc = super.getRealConnection(); if (rc != null) return rc; openRealConnection(); // a new Connection, set its state according to the application's Connection handle currentConnectionHandle.setState(true); return realConnection; } }
apache-2.0
codesmart-co/bit
connectors/fb_ads/settings.py
4163
# Facebook Ads Config File from packaging.version import Version from facebook_business.adobjects.adsinsights import AdsInsights as fbAdsInsights from superset import app config = app.config DB_PREFIX = '{}'.format( config.get('APP_DB_PREFIX', 'bit'), ) CONNECTOR_KEY = 'facebook' # rename to facebook_ads and migrate db tables CONNECTOR_INFO = { 'version': Version('1.5'), 'table_prefix': '{}_{}'.format( DB_PREFIX, CONNECTOR_KEY, ), 'app_id': config.get('FB_APP_ID', 'FB_APP_ID'), 'app_secret': config.get('FB_APP_SECRET', 'FB_APP_SECRET'), 'name': 'Facebook ADS', 'key': CONNECTOR_KEY, 'static_folder': '/static/bit/images/connectors', 'img_folder': 'img', 'docs_folder': 'docs', 'logo': 'logo.png', 'logo_pat': '<img style="padding:15px;width:100px;float:left;" src="{}"/>', 'description': 'Lorem Ipsum is simply dummy text of the printing and' ' typesetting industry. Lorem Ipsum has been the' ' industry\'s standard dummy text ever since the 1500s,' ' when an unknown printer took a galley of type and' ' scrambled it to make a type specimen book. It has' ' survived not only five <b>centuries</b>, but also the' ' leap into electronic typesetting, remaining essentially' ' unchanged. It was popularised in the 1960s with the' ' release of Letraset sheets containing Lorem Ipsum' ' passages, and more recently with desktop publishing' ' software like Aldus PageMaker including versions of' ' Lorem Ipsum.', 'sync_field': 'date', 'reports': { 'conversion_device': { 'name': 'Conversion Device', 'action_breakdowns': [ fbAdsInsights.ActionBreakdowns.action_device, fbAdsInsights.ActionBreakdowns.action_type ], }, 'age': { 'name': 'Age', 'breakdowns': [fbAdsInsights.Breakdowns.age], }, 'gender': { 'name': 'Gender', 'breakdowns': [fbAdsInsights.Breakdowns.gender], }, 'age_gender': { 'name': 'Age and Gender', 'breakdowns': [ fbAdsInsights.Breakdowns.age, fbAdsInsights.Breakdowns.gender ], }, 'country': { 'name': 'Country', 'breakdowns': [fbAdsInsights.Breakdowns.country], }, 'region': { 'name': 'Region', 'breakdowns': [fbAdsInsights.Breakdowns.region], }, 'dma_region': { 'name': 'DMA Region', 'breakdowns': [fbAdsInsights.Breakdowns.dma], }, 'impression_device': { 'name': 'Impression Device', 'breakdowns': [fbAdsInsights.Breakdowns.impression_device], }, 'platform': { 'name': 'Platform', 'breakdowns': [fbAdsInsights.Breakdowns.publisher_platform], }, 'platform_device': { 'name': 'Platform and Device', 'breakdowns': [ fbAdsInsights.Breakdowns.publisher_platform, fbAdsInsights.Breakdowns.impression_device ], }, 'placement': { 'name': 'Placement', 'breakdowns': [ fbAdsInsights.Breakdowns.publisher_platform, fbAdsInsights.Breakdowns.platform_position, fbAdsInsights.Breakdowns.device_platform ], }, 'placement_device': { 'name': 'Placement and Device', 'breakdowns': [ fbAdsInsights.Breakdowns.publisher_platform, fbAdsInsights.Breakdowns.platform_position, fbAdsInsights.Breakdowns.device_platform, fbAdsInsights.Breakdowns.impression_device ], }, 'product_id': { 'name': 'Product ID', 'breakdowns': [fbAdsInsights.Breakdowns.product_id], }, }, }
apache-2.0
jasdel/aws-sdk-go
service/identitystore/service.go
3540
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package identitystore import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/client/metadata" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/signer/v4" "github.com/aws/aws-sdk-go/private/protocol" "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) // IdentityStore provides the API operation methods for making requests to // AWS SSO Identity Store. See this package's package overview docs // for details on the service. // // IdentityStore methods are safe to use concurrently. It is not safe to // modify mutate any of the struct's properties though. type IdentityStore struct { *client.Client } // Used for custom client initialization logic var initClient func(*client.Client) // Used for custom request initialization logic var initRequest func(*request.Request) // Service information constants const ( ServiceName = "identitystore" // Name of service. EndpointsID = ServiceName // ID to lookup a service endpoint with. ServiceID = "identitystore" // ServiceID is a unique identifier of a specific service. ) // New creates a new instance of the IdentityStore client with a session. // If additional configuration is needed for the client instance use the optional // aws.Config parameter to add your extra config. // // Example: // mySession := session.Must(session.NewSession()) // // // Create a IdentityStore client from just a session. // svc := identitystore.New(mySession) // // // Create a IdentityStore client with additional configuration // svc := identitystore.New(mySession, aws.NewConfig().WithRegion("us-west-2")) func New(p client.ConfigProvider, cfgs ...*aws.Config) *IdentityStore { c := p.ClientConfig(EndpointsID, cfgs...) if c.SigningNameDerived || len(c.SigningName) == 0 { c.SigningName = "identitystore" } return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName) } // newClient creates, initializes and returns a new service client instance. func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *IdentityStore { svc := &IdentityStore{ Client: client.New( cfg, metadata.ClientInfo{ ServiceName: ServiceName, ServiceID: ServiceID, SigningName: signingName, SigningRegion: signingRegion, PartitionID: partitionID, Endpoint: endpoint, APIVersion: "2020-06-15", JSONVersion: "1.1", TargetPrefix: "AWSIdentityStore", }, handlers, ), } // Handlers svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler) svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) svc.Handlers.UnmarshalError.PushBackNamed( protocol.NewUnmarshalErrorHandler(jsonrpc.NewUnmarshalTypedError(exceptionFromCode)).NamedHandler(), ) // Run custom client initialization if present if initClient != nil { initClient(svc.Client) } return svc } // newRequest creates a new request for a IdentityStore operation and runs any // custom request initialization. func (c *IdentityStore) newRequest(op *request.Operation, params, data interface{}) *request.Request { req := c.NewRequest(op, params, data) // Run custom request initialization if present if initRequest != nil { initRequest(req) } return req }
apache-2.0
spinnaker/deck
packages/core/src/task/modal/TaskMonitorModal.tsx
3456
import type { FormikProps } from 'formik'; import { Form } from 'formik'; import React from 'react'; import { Modal } from 'react-bootstrap'; import type { Application } from '../../application'; import { ModalClose, SubmitButton } from '../../modal'; import { TaskMonitor } from '../monitor/TaskMonitor'; import { TaskMonitorWrapper } from '../monitor/TaskMonitorWrapper'; import type { IModalComponentProps } from '../../presentation'; import { LayoutProvider, ResponsiveFieldLayout, SpinFormik } from '../../presentation'; import type { ITaskCommand } from '../taskExecutor'; import { TaskExecutor } from '../taskExecutor'; interface ITaskMonitorModalProps<T> extends IModalComponentProps { application: Application; title: string; description: string; render: (props: FormikProps<T>) => React.ReactNode; mapValuesToTask: (values: T) => ITaskCommand; initialValues: T; } interface ITaskMonitorModalState { taskMonitor: TaskMonitor; isSubmitting: boolean; } export class TaskMonitorModal<T> extends React.Component<ITaskMonitorModalProps<T>, ITaskMonitorModalState> { constructor(props: ITaskMonitorModalProps<T>) { super(props); this.state = { taskMonitor: null, isSubmitting: false, }; } private close = (): void => { this.props.dismissModal(); }; private submitTask = (values: any) => { const { application, description } = this.props; const onClose = (result: any) => this.props.closeModal(result); const onDismiss = (result: any) => this.props.dismissModal(result); const modalInstance = TaskMonitor.modalInstanceEmulation(onClose, onDismiss); const taskMonitor = new TaskMonitor({ application, modalInstance, title: description, onTaskComplete: () => application.serverGroups.refresh(), }); const task = this.props.mapValuesToTask(values); task.description = this.props.description; const submitMethod = () => { const promise = TaskExecutor.executeTask(task); const done = () => this.setState({ isSubmitting: false }); promise.then(done, done); return promise; }; taskMonitor.submit(submitMethod); this.setState({ taskMonitor, isSubmitting: true }); }; public render() { const { isSubmitting } = this.state; return ( <div> <TaskMonitorWrapper monitor={this.state.taskMonitor} /> <SpinFormik<T> initialValues={this.props.initialValues} onSubmit={this.submitTask} render={(formik) => ( <Form className="form-horizontal"> <ModalClose dismiss={this.close} /> <Modal.Header> <Modal.Title>{this.props.title}</Modal.Title> </Modal.Header> <Modal.Body className="entity-tag-editor-modal"> <LayoutProvider value={ResponsiveFieldLayout}>{this.props.render(formik)}</LayoutProvider> </Modal.Body> <Modal.Footer> <button className="btn btn-default" disabled={isSubmitting} onClick={this.close} type="button"> Cancel </button> <SubmitButton isDisabled={!formik.isValid || isSubmitting} submitting={isSubmitting} isFormSubmit={true} label="Submit" /> </Modal.Footer> </Form> )} /> </div> ); } }
apache-2.0
Chirojeugd-Vlaanderen/gap
tools/Chiro.LoginService/Chiro.Ad.DirectoryInterface/IDirectoryAccess.cs
3239
/* * Copyright 2016 Chirojeugd-Vlaanderen vzw. See the NOTICE file at the * top-level directory of this distribution, and at * https://gapwiki.chiro.be/copyright * * 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 Chiro.Ad.Domain; namespace Chiro.Ad.DirectoryInterface { /// <summary> /// Interface voor Active Directory of gelijkaardige service. /// </summary> public interface IDirectoryAccess { /// <summary> /// Reset het wachtwoord van de gegeven <paramref name="login"/>. /// </summary> /// <param name="login"></param> /// <param name="wachtwoord">Te gebruiken wachtwoord.</param> void PasswordReset(Chirologin login, string wachtwoord); /// <summary> /// Activeert de gegeven <paramref name="login"/>. /// </summary> /// <param name="login"></param> void GebruikerActiveren(Chirologin login); /// <summary> /// Zoekt de login van een bestaande Chirogebruiker op. /// </summary> /// <param name="ldapRoot"></param> /// <param name="adNr"></param> /// <returns></returns> Chirologin GebruikerZoeken(string ldapRoot, int adNr); /// <summary> /// Zoekt de login van een bestaande Chirogebruiker op. /// </summary> /// <param name="ldapRoot"></param> /// <param name="voornaam"></param> /// <param name="familienaam"></param> /// <returns></returns> Chirologin GebruikerZoeken(string ldapRoot, string voornaam, string familienaam); /// <summary> /// Bewaart de login van een nieuwe gebruiker. /// </summary> /// <param name="login"></param> /// <param name="gebruikerOu">OU waarin de gebruiker gemaakt moet worden.</param> void NieuweGebruikerBewaren(Chirologin login, string gebruikerOu); /// <summary> /// Voegt gegeven <paramref name="gebruiker" /> toe aan de security groep /// <paramref name="groep" />. /// </summary> /// <param name="gebruiker">Gebruiker toe te voegen aan <paramref name="groep"/>.</param> /// <param name="groep">Groep waaraan <paramref name="gebruiker"/> toegevoegd moet worden.</param> /// <param name="groepOu">OU van de security group.</param> void GebruikerToevoegenAanGroep(Chirologin gebruiker, string groep, string groepOu); /// <summary> /// Zoekt de login van een bestaande Chirogebruiker. /// </summary> /// <param name="ldaproot"></param> /// <param name="username"></param> /// <returns></returns> Chirologin GebruikerZoeken(string ldaproot, string username); } }
apache-2.0
RainZhai/rainzhai.github.com
raincss/js/jquery.dialog.js
16213
/** * dailog 1.3.1 * Anthor: zhaiyu * Date: 2013.1.21 * lastUpdate : 2016.05.19 */ (function ($) { /** * @description dialog对象声明 * @constructor * @param {Object} 参数对象 * @example var div = new $.dialog({ * width: 540, * height: 300, * top:'20%', * content:$(".c_testwrap"), * titleText:"hello dialog", * dialogStyle:{"border":"8px solid #ededed"}, * titleStyle:{"background":"#F5F5F5"}, * btnsWrapStyle:{'text-align':'right'}, * buttonsClass:["hs rounds gb btn bluebtn ml","hs rounds ggrey bgrey_2 btn greybtn ml"], * buttons:"OKCancel", * beforeClose:function(e){ log(e.data.name);log(e.data.type);}, * afterClose:function(e){ log(e.data.name);} * }); * */ window.dialog = $.dialog = function(obj) { this.obj = obj; $.extend(this,{ // 弹出框宽度 "width":540, // 弹出框高度 "height":300, // 离顶部的距离 "top":"20%", // 离左边的距离 "left":"50%", // 是否可以拖拽 "draggable":false, //头部是否显示 "header":true, //关闭是否显示 "showClose":false, // 弹出框内显示的内容 "content":null, // 关闭图标的句柄 "closeHandleClass":"c_close", // 弹出层句柄 "dialogHandleClass":"c_dialogwrap", // 弹出层文本 "titleText":"提示框", // 遮罩背景色 "bgColor":"#fff", //关闭样式 "closeStyle":{}, //关闭class "closeClass":"", // 弹出框样式 "dialogStyle":{}, // 弹出框class "dialogClass":"", // 头部样式 "headStyle":{"background":"#F5F5F5"}, // 头部class "headClass":"", // 内容样式 "contentStyle":{}, // 内容class "contentClass":"", // 按钮外层样式 "btnsWrapStyle":{"text-align":"right"}, // 按钮外层class "btnsWrapClass":"", // 按钮组style "buttonsStyle":[ {} ], // 按钮组class "buttonsClass":[ "hs rounds gb button blueBtn marginLeft" ], // 关闭回调 "closeCallback":function() {}, // 常用按钮OK,OKCancel,YesNo,YesNoCancel "buttons":null, // 自定义按钮组 "buttonsArray":[], // 按钮的回调 "buttonsCallback":{}, // 按钮的属性 "buttonsAttr":[], //按钮显示前的回调 "beforeShow":function() {}, //按钮显示后的回调 "afterShow":function() {}, //按钮关闭前的回调 "beforeClose":function() {}, //按钮关闭后的回调 "afterClose":function() {}, //上传是否显示 "upload":false, //自动适应 "responsive": true }, this.obj || {}); this.randomStr = Math.round(Math.random() * 1e6 + 1) + "", this.contentObj = this.content, this.closeClass = this.closeHandleClass + this.randomStr, this.dialogHandleClass = this.dialogHandleClass + this.randomStr, this.contentwrapid = "contentwrap" + this.randomStr, this.html = null; }; dialog.prototype = { "handle":null, "inited":false, /**@method 对象初始化*/ "init":function() { var _this = this; if(_this.content || (typeof _this.obj === "string" || _this.obj instanceof jQuery || "nodeName" in _this.obj)){ _this.initHtml(); _this.initBtns(); _this.initModule(); } return _this; }, /**@method 获取内容块id*/ "getContentWrapID":function() { return this.contentwrapid; }, /**@method 获取dialog id*/ "getDialogID":function() { return this.dialogHandleClass; }, /** @method 设置内容 * @param {Object} 参数对象 */ "setContent":function(obj) { var html = this.getHtml(); if (typeof obj === "string") { html.find(".c_contentWrap").empty().append(obj); } else if (this.contentObj instanceof jQuery) { html.find(".c_contentWrap").empty().append(obj.show()); } else if (obj && "nodeName" in obj) { html.find(".c_contentWrap").empty().append($(obj).show()); } return this; }, /** @method 设置内容 * @param {Object} 参数对象 */ "addContent":function(obj) { var html = this.getHtml(); if (typeof obj === "string") { html.find(".c_contentWrap").append(obj); } else if (this.contentObj instanceof jQuery) { html.find(".c_contentWrap").append(obj.show()); } else if (obj && "nodeName" in obj) { html.find(".c_contentWrap").append($(obj).show()); } this._setDialogHeight(html); return this; }, /** @method 获取button对象 * @public * @param {number} 索引 */ "getBtn":function(i) { if (i > -1 && this.jqbtns) { return this.jqbtns[i]; } return null; }, /** @method 设置高度 * @public * @param {number} 高度值 */ "setHeight":function(h) { if (typeof h === "number") { if (this.html) { this.html.find(".c_dialogBox").height(h); } } return this; }, /** @method 设置dialog持有者 * @public * @param {object} 对象 */ "setHandle":function(obj) { this.handle = obj; return this; }, /** @method 获取html对象 * @public */ "getHtml":function() { return this.html; }, /** @method 设置标题文本 * @public */ "setTitleText":function(txt) { this.getHtml().find(".c_titletext").text(txt); return this; }, /** @method 显示dialog * @private * @param {function} 回调函数 */ "_show":function(callback) { if ($("body").find("." + this.dialogHandleClass).length === 0) { $("body").append(this.getHtml().removeClass('vf')); } else { if (typeof callback === "function") { $("." + this.dialogHandleClass).removeClass('vf'); callback(); }else{ $("." + this.dialogHandleClass).removeClass('vf'); } } }, /** @method 显示dialog * @public * @param {number} 延迟时间 * @param {function} 回调函数 */ "show":function(s, callback) { if(!this.inited) {this.init();this.inited=true;} this.beforeShow(); if (s) { setTimeout(function() {this._show(callback);}, s); } else { this._show(callback); } this.afterShow(); return this; }, /** @method 关闭dialog * @public * @param {function} 回调函数 */ "close":function(e,callback) { this.beforeClose(e); if (typeof callback === "function") { $("." + this.dialogHandleClass).addClass('vf'); callback(); }else{ $("." + this.dialogHandleClass).addClass('vf'); } this.afterClose(e); this.hide = this.close; return this; }, /** @method 初始化上传控件 * @private */ "_initUpload":function() { var html = this.getHtml(); var uploadHtml = $('<div class="uploadBox margin">' + '<div class="hide c_picArea positionR">' + '<form enctype="multipart/form-data" method="post" action="#" id="upload-pic" target="iframe-post-form">' + '<input type="text" disabled="true" class="uploadFileName" id="txtFileName">' + '<span id="spanButtonPlaceHolder" class="valignMiddle"></span>' + '<label id="fsUploadProgress">正在上传...</label>' + "</form>" + '<span class="c_closeUploadBox closeUploadBox posa cursorPointer">x</span>' + "</div>" + '<a name="pic-area" class="c_lnPic" href="#">添加照片</a>' + "</div>"); html.find(".c_contentWrap").append(uploadHtml); uploadHtml.find(".c_lnPic").on("click", function() { _height = _height + 30; html.find(".c_dialogBox").css({ "width":_width, "height":_height, "top":this.top, "left":this.left }); uploadHtml.find(".c_picArea").removeClass("hide"); }); uploadHtml.find(".c_closeUploadBox").on("click", function() { _height = _height - 30; html.find(".c_dialogBox").css({ "width":_width, "height":_height, "top":this.top, "left":this.left }); uploadHtml.find(".c_picArea").addClass("hide"); }); return this; }, /** @method 初始化按钮 * @public */ "initBtns":function() { var _this = this; var _html = this.getHtml(); var btns = this.buttons; var buttonsWrap = _html.find(".c_btnWrap"); if (btns && typeof btns === "string") { var btnHandler = function(event) { _this.close(event); } var button = []; if (btns === "OK") button.push($("<a href='javascript:;' class='c_button rounds ggrey btn greybtn ib tdn ps tac ml'>确定</a>")); if (btns === "OKCancel") button.push($("<a href='javascript:;' class='c_button rounds ggrey btn greybtn ib tdn ps tac ml'>确定</a>").attr("btype", "ok"), $("<a href='javascript:;' class='c_button rounds ggrey btn greybtn ib tdn ps tac ml'>取消</a>").attr("btype", "canel")); if (btns === "YesNo") button.push($("<a href='javascript:;' class='c_button rounds ggrey btn greybtn ib tdn ps tac ml'>是</a>"), $("<a href='javascript:;' class='c_button rounds ggrey btn greybtn ib tdn ps tac ml'>否</a>")); if (btns === "YesNoCancel") button.push($("<a href='javascript:;' class='c_button rounds ggrey btn greybtn ib tdn ps tac ml'>是</a>"), $("<a href='javascript:;' class='c_button rounds ggrey btn greybtn ib tdn ps tac ml'>否</a>"), $("<a href='javascript:;' class='c_button rounds ggrey btn greybtn ib tdn ps tac ml'>取消</a>")); for (var i = 0; i < button.length; i++) { button[i].on("click", {"name":btns,"type":button[i].attr("btype")}, btnHandler); buttonsWrap.append(button[i]); } } else { // 遍历设置的按钮数组,将相应的按钮进行显示并绑定相应事件 var buttonsArray = this.buttonsArray; var buttonsCallback = this.buttonsCallback; var buttonDom = _html.find(".c_button"); function btnsHandler(e) { var _callback = buttonsArray[e.data.index]; if (typeof buttonsCallback[_callback] == "function") { buttonsCallback[_callback](e); } } this.jqbtns = []; // 按钮绑定事件 for (var j = 0; j < buttonsArray.length; j++) { var btnClass = this.buttonsClass[j] || ""; var btnStyle = this.buttonsStyle[j] || {}; var btnAttr = this.buttonsAttr[j] || {}; var buttons = $("<a href='javascript:void(0);' class='c_button ib tdn " + btnClass + "'>" + buttonsArray[j] + "</a>").css(btnStyle).attr(btnAttr); buttons.on("click", { "index":j }, btnsHandler); buttonsWrap.append(buttons); this.jqbtns.push(buttons); } } buttonsWrap.append('<div class="touchWrap posa fullw fullh"></div>'); return this; }, /** @method 初始化html * @public */ "initHtml":function() { if (!this.html) { if (this.header) { var closehtml = ""; if (this.showClose) { closehtml = '<span class="' + this.closeClass + ' close block posa oh tac">x</span>'; } this.html = $('<div id="' + this.dialogHandleClass + '" class="' + this.dialogHandleClass + ' dialogWrap tal posf vf">' + '<div class="dialogWrapIE o posa c_bgColor"></div>' + '<div class="c_dialogBox dialogBox posa"> ' + '<div class="c_dialogTitle p"><span class="c_titletext bottom">' + this.titleText + "</span>" + closehtml + "</div>" + '<div class="c_contentWrap pl pr"></div>' + '<p class="c_btnWrap m posr"> </p>' + "</div></div>"); } else { this.html = $('<div class="' + this.dialogHandleClass + ' dialogWrap tal posf vf">' + '<div class="dialogWrapIE o posa c_bgColor"></div>' + '<div class="c_dialogBox dialogBox posa"> ' + '<div id="' + this.contentwrapid + '" class="c_contentWrap p"></div><p class="c_btnWrap m posr"> </p></div></div>'); } } if (this.obj && (typeof this.obj === "string" || this.obj instanceof jQuery || "nodeName" in this.obj)) { this.getHtml().find("." + this.closeClass).hide(); this.getHtml().find(".c_contentWrap").append(this.obj); } else { this.setContent(this.contentObj); } return this; }, /** @method 初始化各个模块功能 * @public */ "initModule":function() { var _this = this; var html = this.getHtml(); // 控制框是否可以拖拽 if (_this.draggable) { html.find(".c_dialogBox").draggable({ "cursor":"move", "handle":".c_dialogTitle", "scroll":false, "containment":"html" }); } // 设置上传控制 if (_this.upload) { _this._initUpload(); } //按钮绑定事件 html.find("." + _this.closeClass).on("click", {"name":"closebtn","type":"close"}, function(e) { _this.close(e,_this.closeCallback); }); $("body").append(html); _this._setDialogHeight(html); _this._initUI(); return _this; }, /** @method 初始化UI * @private */ "_initUI":function() { var html = this.getHtml(); // 设置样式 html.find(".c_bgColor").height($(document).height()).css({"background-color":this.bgColor}); html.find("." + this.closeClass).css(this.closeStyle).addClass(this.headClass); if (this.dialogStyle) html.find(".c_dialogBox").css(this.dialogStyle); if (this.dialogClass) html.find(".c_dialogBox").addClass(this.dialogClass); html.find(".c_dialogTitle").css(this.headStyle).addClass(this.headClass); html.find(".c_contentWrap").css(this.contentStyle).addClass(this.contentClass); html.find(".c_btnWrap").css(this.btnsWrapStyle).addClass(this.btnsWrapClass); }, /** @method 设置dialog高度 * @private */ "_setDialogHeight":function(obj) { // 获取dialog宽度和高度 var _width = $("body").width() / 5 + 150; var _height = obj.find(".c_contentWrap").outerHeight(true) + obj.find(".c_dialogTitle").outerHeight(true) + obj.find(".c_btnWrap").outerHeight(true); // 计算弹出层的大小和位置 if (this.width > 0 && this.height > 0) { if(this.responsive){ obj.find(".c_dialogBox").css({ "width": this.width, "height": _height, "top": this.top, "left": this.left }); }else{ obj.find(".c_dialogBox").css({ "width":this.width, "height":this.height, "top":this.top, "left":this.left }); } } else { obj.find(".c_dialogBox").css({ "width":_width, "height":_height, "top":this.top, "left":this.left }); } return this; } }; })(jQuery);
apache-2.0
Murphy-Lin/zhongqi
src/com/sinodata/evaluate/BaseActivity.java
2896
package com.sinodata.evaluate; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Window; import com.sinodata.evaluate.activities.ManageActivity; import com.sinodata.evaluate.utils.WifiConnect; public abstract class BaseActivity extends FragmentActivity{ public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); ((MyApplication)getApplication()).addActivity(this); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("您还未连接WIFI,请先连接!").setPositiveButton("去搜搜附近的WIFI", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Intent intent = new Intent(BaseActivity.this,ManageActivity.class); intent.setAction("wifi"); startActivity(intent); dialog.dismiss(); //finish(); } }).setCancelable(false); AlertDialog dialog = builder.create(); boolean iscon = WifiConnect.checkNetworkConnection(this); if(getClass().getSimpleName().equals("ManageActivity")||getClass().getSimpleName().equals("SplashActivity")){ if(dialog!=null){ dialog.dismiss(); } }else if(!iscon){ dialog.show(); } /* * 隐藏运行Android 4.0以上系统的平板的屏幕下方的状态栏 */ // try // { // String ProcID = "79"; // if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) ProcID = "42"; // ICS // // 需要root 权限 // Process proc = Runtime.getRuntime().exec(new String[] { "su", "-c", "service call activity " + ProcID + " s16 com.android.systemui" }); // WAS // proc.waitFor(); // } // catch (Exception e) // { // e.printStackTrace(); // } } public abstract void initView(); public abstract void initEvent(); @Override protected void onDestroy() { ((MyApplication)getApplication()).removeActivity(this); /* * 恢复运行Android 4.0以上系统的平板的屏幕下方的状态栏 */ // try // { // Process proc = Runtime.getRuntime().exec(new String[] { "am", "startservice", "-n", "com.android.systemui/.SystemUIService" }); // proc.waitFor(); // } // catch (Exception e) // { // e.printStackTrace(); // } super.onDestroy(); } }
apache-2.0
norrs/geocalendar
geocalendar/geocal/migrations/0001_initial.py
1658
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'CalendarEntry' db.create_table('geocal_calendarentry', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('title', self.gf('django.db.models.fields.CharField')(max_length=100)), ('description', self.gf('django.db.models.fields.TextField')(blank=True)), ('entry_date', self.gf('django.db.models.fields.DateField')()), ('keyword', self.gf('django.db.models.fields.CharField')(max_length=30)), ('picture', self.gf('filebrowser.fields.FileBrowseField')(max_length=500)), )) db.send_create_signal('geocal', ['CalendarEntry']) def backwards(self, orm): # Deleting model 'CalendarEntry' db.delete_table('geocal_calendarentry') models = { 'geocal.calendarentry': { 'Meta': {'object_name': 'CalendarEntry'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'entry_date': ('django.db.models.fields.DateField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'keyword': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'picture': ('filebrowser.fields.FileBrowseField', [], {'max_length': '500'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['geocal']
apache-2.0
futuresimple/android-db-commons
library/src/main/java/com/getbase/android/db/loaders/ComposedCancellableFunction.java
578
package com.getbase.android.db.loaders; import android.support.v4.os.CancellationSignal; class ComposedCancellableFunction<TIn, T, TOut> implements CancellableFunction<TIn, TOut> { private final CancellableFunction<TIn, T> mFirst; private final CancellableFunction<T, TOut> mThen; ComposedCancellableFunction(CancellableFunction<TIn, T> first, CancellableFunction<T, TOut> then) { mFirst = first; mThen = then; } @Override public final TOut apply(TIn input, CancellationSignal signal) { return mThen.apply(mFirst.apply(input, signal), signal); } }
apache-2.0
haoch/kylin
jdbc/src/main/java/org/apache/kylin/jdbc/KylinPreparedStatement.java
4837
/* * 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.kylin.jdbc; import java.io.InputStream; import java.io.Reader; import java.sql.NClob; import java.sql.RowId; import java.sql.SQLException; import java.sql.SQLXML; import java.util.ArrayList; import java.util.List; import org.apache.calcite.avatica.AvaticaConnection; import org.apache.calcite.avatica.AvaticaPreparedStatement; import org.apache.calcite.avatica.Meta.Signature; import org.apache.calcite.avatica.Meta.StatementHandle; public class KylinPreparedStatement extends AvaticaPreparedStatement { protected KylinPreparedStatement(AvaticaConnection connection, StatementHandle h, Signature signature, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { super(connection, h, signature, resultSetType, resultSetConcurrency, resultSetHoldability); if (this.handle.signature == null) this.handle.signature = signature; } protected List<Object> getParameterValues2() { List<Object> values = new ArrayList<>(slots.length); for (int i = 0; i < slots.length; i++) { values.add(slots[i].value); } return values; } // ============================================================================ public void setRowId(int parameterIndex, RowId x) throws SQLException { getSite(parameterIndex).setRowId(x); } public void setNString(int parameterIndex, String value) throws SQLException { getSite(parameterIndex).setNString(value); } public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { getSite(parameterIndex).setNCharacterStream(value, length); } public void setNClob(int parameterIndex, NClob value) throws SQLException { getSite(parameterIndex).setNClob(value); } public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { getSite(parameterIndex).setClob(reader, length); } public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { getSite(parameterIndex).setBlob(inputStream, length); } public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { getSite(parameterIndex).setNClob(reader, length); } public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { getSite(parameterIndex).setSQLXML(xmlObject); } public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { getSite(parameterIndex).setAsciiStream(x, length); } public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { getSite(parameterIndex).setBinaryStream(x, length); } public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { getSite(parameterIndex).setCharacterStream(reader, length); } public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { getSite(parameterIndex).setAsciiStream(x); } public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { getSite(parameterIndex).setBinaryStream(x); } public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { getSite(parameterIndex).setCharacterStream(reader); } public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { getSite(parameterIndex).setNCharacterStream(value); } public void setClob(int parameterIndex, Reader reader) throws SQLException { getSite(parameterIndex).setClob(reader); } public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { getSite(parameterIndex).setBlob(inputStream); } public void setNClob(int parameterIndex, Reader reader) throws SQLException { getSite(parameterIndex).setNClob(reader); } }
apache-2.0
gosu-lang/gosu-lang
gosu-lab/src/main/java/editor/search/AbstractSearcher.java
1996
package editor.search; import editor.FileTree; import editor.FileTreeUtil; import editor.NodeKind; import editor.util.IProgressCallback; import java.util.Collections; import java.util.List; import java.util.function.Predicate; /** */ public abstract class AbstractSearcher { public abstract boolean search( FileTree tree, SearchTree results ); public boolean searchTree( FileTree tree, SearchTree results, Predicate<FileTree> filter, IProgressCallback progress ) { return searchTrees( Collections.singletonList( tree ), results, filter, progress ); } public boolean searchTrees( List<FileTree> trees, SearchTree results, Predicate<FileTree> filter, IProgressCallback progress ) { if( progress != null && progress.isAbort() ) { return false; } boolean bFound = false; for( FileTree tree: trees ) { if( tree.isFile() && filter.test( tree ) ) { if( progress != null ) { progress.incrementProgress( tree.getName() ); } bFound = bFound | search( tree, results ); } else if( !tree.isLeaf() ) { if( searchTrees( tree.getChildren(), results, filter, progress ) ) { bFound = true; } } } return bFound; } protected SearchTree getOrMakePath( FileTree tree, SearchTree results ) { if( tree.getParent() != null ) { results = getOrMakePath( tree.getParent(), results ); } for( SearchTree child: results.getChildren() ) { SearchTree.SearchTreeNode node = child.getNode(); if( node != null && node.getFile() == tree ) { return child; } } SearchTree.SearchTreeNode node = new SearchTree.SearchTreeNode( tree, null ); SearchTree searchTree = new SearchTree( NodeKind.Directory, node ); results.addViaModel( searchTree ); return searchTree; } protected boolean isExcluded( FileTree tree ) { return !FileTreeUtil.isSupportedTextFile( tree ); } }
apache-2.0
webos21/xi
java/jcl/vmclasses/java/lang/reflect/VMConstructor.java
6032
/* java.lang.reflect.VMConstructor - VM interface for reflection of Java constructors Copyright (C) 1998, 2001, 2004, 2005 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package java.lang.reflect; import java.lang.annotation.Annotation; import java.util.Arrays; final class VMConstructor { int slot; Class clazz; Constructor cons; Class[] parameterTypes; public Class getDeclaringClass() { return clazz; } /** * Return the raw modifiers for this constructor. In particular this will * include the synthetic and varargs bits. * * @return the constructor's modifiers */ native int getModifiersInternal(); /** * Get the parameter list for this constructor, in declaration order. If the * constructor takes no parameters, returns a 0-length array (not null). * * @return a list of the types of the constructor's parameters */ Class[] getParameterTypes() { return parameterTypes; } /** * Get the exception types this constructor says it throws, in no particular * order. If the constructor has no throws clause, returns a 0-length array * (not null). * * @return a list of the types in the constructor's throws clause */ native Class[] getExceptionTypes(); native Object construct(Object[] args) throws InstantiationException, IllegalAccessException, InvocationTargetException; /** * Return the String in the Signature attribute for this constructor. If * there is no Signature attribute, return null. */ native String getSignature(); /** * <p> * Return an array of arrays representing the annotations on each of the * constructor's parameters. The outer array is aligned against the * parameters of the constructors and is thus equal in length to the number * of parameters (thus having a length zero if there are none). Each array * element in the outer array contains an inner array which holds the * annotations. This array has a length of zero if the parameter has no * annotations. * </p> * <p> * The returned annotations are serialized. Changing the annotations has no * affect on the return value of future calls to this method. * </p> * * @return an array of arrays which represents the annotations used on the * parameters of this constructor. The order of the array elements * matches the declaration order of the parameters. * @since 1.5 */ native Annotation[][] getParameterAnnotations(); /** * Compare two objects to see if they are semantically equivalent. Two * Constructors are semantically equivalent if they have the same declaring * class and the same parameter list. This ignores different exception * clauses, but since you can't create a Method except through the VM, this * is just the == relation. * * @param o * the object to compare to * @return <code>true</code> if they are equal; <code>false</code> if not. */ public boolean equals(Object o) { if (!(o instanceof Constructor)) return false; Constructor that = (Constructor) o; if (clazz != that.getDeclaringClass()) return false; if (!Arrays.equals(getParameterTypes(), that.getParameterTypes())) return false; return true; } /** * Returns the element's annotation for the specified annotation type, or * <code>null</code> if no such annotation exists. * * @param annotationClass * the type of annotation to look for. * @return this element's annotation for the specified type, or * <code>null</code> if no such annotation exists. * @throws NullPointerException * if the annotation class is <code>null</code>. */ public Annotation getAnnotation(Class annoClass) { Annotation[] annos = getDeclaredAnnotations(); for (int i = 0; i < annos.length; i++) if (annos[i].annotationType() == annoClass) return annos[i]; return null; } /** * Returns all annotations directly defined by the element. If there are no * annotations directly associated with the element, then a zero-length * array will be returned. The returned array may be modified by the client * code, but this will have no effect on the annotation content of this * class, and hence no effect on the return value of this method for future * callers. * * @return the annotations directly defined by the element. * @since 1.5 */ native Annotation[] getDeclaredAnnotations(); }
apache-2.0
F5Networks/k8s-bigip-ctlr
pkg/agent/as3/as3Manager_test.go
10610
/*- * Copyright (c) 2016-2021, F5 Networks, 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 as3 import ( "encoding/json" . "github.com/F5Networks/k8s-bigip-ctlr/pkg/resource" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) type mockAS3Manager struct { *AS3Manager } func newMockAS3Manager(params *Params) *mockAS3Manager { return &mockAS3Manager{ NewAS3Manager(params), } } func mockGetEndPoints(string, string) []Member { return []Member{{Address: "1.1.1.1", Port: 80, SvcPort: 80}, {Address: "2.2.2.2", Port: 80, SvcPort: 80}} } func (m *mockAS3Manager) shutdown() error { return nil } var _ = Describe("AS3Manager Tests", func() { var mockMgr *mockAS3Manager BeforeEach(func() { mockMgr = newMockAS3Manager(&Params{ As3Version: "3.30.0", As3Release: "3.30.0-5", As3SchemaVersion: "3.30.0", }) }) AfterEach(func() { mockMgr.shutdown() }) Describe("Validating AS3 ConfigMap with AS3Manager", func() { It("AS3 declaration with Invalid JSON", func() { data := readConfigFile(configPath + "as3config_invalid_JSON.json") _, ok := getAS3ObjectFromTemplate(as3Template(data)) Expect(ok).To(Equal(false), "AS3 Template is not a valid JSON.") }) It("AS3 declaration with all Tenants, Applications and Pools", func() { data := readConfigFile(configPath + "as3config_valid_1.json") _, ok := getAS3ObjectFromTemplate(as3Template(data)) Expect(ok).To(Equal(true), "AS3 Template parsed succesfully.") }) It("AS3 declaration without Pools", func() { data := readConfigFile(configPath + "as3config_without_pools.json") _, ok := getAS3ObjectFromTemplate(as3Template(data)) Expect(ok).To(Equal(true), "AS3 Template parsed succesfully [No Pools].") }) It("AS3 declaration without Applications", func() { data := readConfigFile(configPath + "as3config_without_apps.json") _, ok := getAS3ObjectFromTemplate(as3Template(data)) Expect(ok).To(Equal(true), "AS3 Template parsed succesfully [No Applications].") }) It("AS3 declaration without Tenants", func() { data := readConfigFile(configPath + "as3config_without_tenants.json") _, ok := getAS3ObjectFromTemplate(as3Template(data)) Expect(ok).To(Equal(false), "AS3 Template parsed succesfully, [No Tenants].") }) It("AS3 template without ADC declaration", func() { data := readConfigFile(configPath + "as3config_without_adc.json") _, ok := getAS3ObjectFromTemplate(as3Template(data)) Expect(ok).To(Equal(false), "AS3 Template without ADC declaration should not be processed.") }) }) Describe("Validate Generated Unified Declaration", func() { It("Unified Declaration only with User Defined ConfigMaps", func() { cmcfg1 := readConfigFile(configPath + "as3config_valid_1.json") cmcfg2 := readConfigFile(configPath + "as3config_valid_2.json") unified := readConfigFile(configPath + "as3config_multi_cm_unified.json") mockMgr.ResourceRequest.AgentCfgmaps = append( mockMgr.ResourceRequest.AgentCfgmaps, &AgentCfgMap{ GetEndpoints: mockGetEndPoints, Name: "cfgmap1", Namespace: "default", Data: cmcfg1, Label: map[string]string{ AS3Label: TrueLabel, F5TypeLabel: VSLabel, }, }, &AgentCfgMap{ GetEndpoints: mockGetEndPoints, Name: "cfgmap2", Namespace: "default", Data: cmcfg2, Label: map[string]string{ AS3Label: TrueLabel, F5TypeLabel: VSLabel, }, }, ) as3config := &AS3Config{} as3config.configmaps, _ = mockMgr.prepareResourceAS3ConfigMaps() result := mockMgr.getUnifiedDeclaration(as3config) Expect(string(result)).To(MatchJSON(unified), "Failed to Create JSON with correct configuration") }) It("Unified Declaration only with Openshift Route", func() { var routeAdc map[string]interface{} routeCfg := readConfigFile(configPath + "as3_route_declaration.json") route := readConfigFile(configPath + "as3_route.json") err := json.Unmarshal([]byte(route), &routeAdc) Expect(err).To(BeNil(), "Original Config should be json") var tempAS3Config AS3Config tempAS3Config.resourceConfig = routeAdc result := mockMgr.getUnifiedDeclaration(&tempAS3Config) Expect(string(result)).To(MatchJSON(routeCfg), "Failed to Create JSON with correct configuration") }) It("Unified Declaration with User Defined ConfigMap and Openshift Route", func() { var routeAdc map[string]interface{} unifiedConfig := readConfigFile(configPath + "as3_route_cfgmap_declaration.json") cmCfg := readConfigFile(configPath + "as3config_valid_1.json") mockMgr.ResourceRequest.AgentCfgmaps = append( mockMgr.ResourceRequest.AgentCfgmaps, &AgentCfgMap{ GetEndpoints: mockGetEndPoints, Name: "cfgmap", Namespace: "default", Data: cmCfg, Label: map[string]string{ AS3Label: TrueLabel, F5TypeLabel: VSLabel, }, }, ) as3config := &AS3Config{} as3config.configmaps, _ = mockMgr.prepareResourceAS3ConfigMaps() routeCfg := readConfigFile(configPath + "as3_route.json") err := json.Unmarshal([]byte(routeCfg), &routeAdc) Expect(err).To(BeNil(), "Route Config should be json") as3config.resourceConfig = routeAdc result := mockMgr.getUnifiedDeclaration(as3config) Expect(string(result)).To(MatchJSON(unifiedConfig), "Failed to Create JSON with correct configuration") ok := DeepEqualJSON(as3Declaration(unifiedConfig), result) Expect(ok).To(BeTrue()) }) It("Validate staging of Configmap", func() { cfgmap := &AgentCfgMap{ Label: map[string]string{ AS3Label: FalseLabel, F5TypeLabel: VSLabel, }, } label, valid := mockMgr.isValidConfigmap(cfgmap) Expect(label).To(Equal(StagingAS3Label), "Wrong Label") Expect(valid).To(BeTrue()) }) }) Describe("Validate Labels of Configmaps", func() { It("Validate non f5type Configmap", func() { cfgmap := &AgentCfgMap{ Label: map[string]string{ "app": "some-app", }, } label, valid := mockMgr.isValidConfigmap(cfgmap) Expect(label).To(Equal(""), "Wrong Label") Expect(valid).To(BeFalse()) }) It("Validate non f5type Configmap", func() { cfgmap := &AgentCfgMap{ Label: map[string]string{ "f5type": "virtual-serverssssss", }, } label, valid := mockMgr.isValidConfigmap(cfgmap) Expect(label).To(Equal(""), "Wrong Label") Expect(valid).To(BeFalse()) }) It("Validate staging of Configmap", func() { cfgmap := &AgentCfgMap{ Label: map[string]string{ AS3Label: FalseLabel, F5TypeLabel: VSLabel, }, } label, valid := mockMgr.isValidConfigmap(cfgmap) Expect(label).To(Equal(StagingAS3Label), "Wrong Label") Expect(valid).To(BeTrue()) }) It("Validate Override configmap labels", func() { cfgmap := &AgentCfgMap{ Label: map[string]string{ OverrideAS3Label: FalseLabel, F5TypeLabel: VSLabel, }, } label, valid := mockMgr.isValidConfigmap(cfgmap) Expect(label).To(Equal(OverrideAS3Label), "Wrong Label") Expect(valid).To(BeTrue()) Expect(cfgmap.Operation).To(Equal(OprTypeDelete)) }) }) Describe("Validate Override Configmap", func() { It("Override CIS generated config with Override Configmap", func() { var routeAdc map[string]interface{} unifiedConfig := readConfigFile(configPath + "as3_route_declaration_overridden.json") ovrdCmCfg := readConfigFile(configPath + "as3config_override_cfgmap.json") mockMgr.ResourceRequest.AgentCfgmaps = append( mockMgr.ResourceRequest.AgentCfgmaps, &AgentCfgMap{ GetEndpoints: mockGetEndPoints, Name: "override_cfgmap", Namespace: "default", Data: ovrdCmCfg, Label: map[string]string{ OverrideAS3Label: TrueLabel, F5TypeLabel: VSLabel, }, }, ) as3config := &AS3Config{} _, as3config.overrideConfigmapData = mockMgr.prepareResourceAS3ConfigMaps() routeCfg := readConfigFile(configPath + "as3_route.json") err := json.Unmarshal([]byte(routeCfg), &routeAdc) Expect(err).To(BeNil(), "Route Config should be json") as3config.resourceConfig = routeAdc result := mockMgr.getUnifiedDeclaration(as3config) Expect(string(result)).To(MatchJSON(unifiedConfig), "Failed to Create JSON with correct configuration") }) It("Validate Override configmap with wrong name", func() { mockMgr.OverriderCfgMapName = "default/ovCfgmap" cfgmap := &AgentCfgMap{ Label: map[string]string{ OverrideAS3Label: TrueLabel, F5TypeLabel: VSLabel, }, Namespace: "default", Name: "wrongname", } label, valid := mockMgr.isValidConfigmap(cfgmap) Expect(label).To(Equal(""), "Wrong Label") Expect(valid).To(BeFalse()) }) It("Validate Override configmap with wrong namespace", func() { mockMgr.OverriderCfgMapName = "default/ovCfgmap" cfgmap := &AgentCfgMap{ Label: map[string]string{ OverrideAS3Label: TrueLabel, F5TypeLabel: VSLabel, }, Namespace: "wrongnamespace", Name: "ovCfgmap", } label, valid := mockMgr.isValidConfigmap(cfgmap) Expect(label).To(Equal(""), "Wrong Label") Expect(valid).To(BeFalse()) }) }) Describe("TLS Profile", func() { It("Default Cipher Group", func() { mockMgr.enableTLS = "1.3" sharedApp := as3Application{ "virtualServer": &as3Service{}, } prof := CustomProfile{ Name: "profile", Cert: "Cert Hash", Key: "Key Hash", } ok := mockMgr.createUpdateTLSServer(prof, "virtualServer", sharedApp) Expect(ok).To(BeTrue(), "Failed to create TLS Server Profile") Expect(sharedApp["virtualServer_tls_server"]).NotTo(BeNil(), "Failed to create TLS Server Profile") Expect(sharedApp["virtualServer"].(*as3Service).ServerTLS).To(Equal("virtualServer_tls_server"), "Failed to set TLS Server Profile") Expect(sharedApp["virtualServer_tls_server"].(*as3TLSServer).CipherGroup.BigIP).To(Equal("/Common/f5-default"), "Failed to set Default Cipher group for TLS Server Profile") }) }) })
apache-2.0
gongmingqm10/TrainTimer
app/src/main/java/net/gongmingqm10/traintimer/ui/fragment/DatePickerFragment.java
1137
package net.gongmingqm10.traintimer.ui.fragment; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import java.util.Calendar; public class DatePickerFragment extends DialogFragment { private DatePickerDialog.OnDateSetListener listener; @Override public void onAttach(Activity activity) { super.onAttach(activity); try { listener = (DatePickerDialog.OnDateSetListener) activity; } catch (ClassCastException exception) { throw new ClassCastException(activity.toString() + " must implement OnDateSetListener"); } } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); return new DatePickerDialog(getActivity(), listener, year, month, day); } }
apache-2.0
UXAspects/UXAspects
src/components/menu/menu-tabbable-item/menu-tabbable-item.directive.ts
2642
import { FocusableOption, FocusOrigin } from '@angular/cdk/a11y'; import { Directive, ElementRef, HostListener, Input, OnDestroy, OnInit, Renderer2 } from '@angular/core'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { FocusIndicator, FocusIndicatorService } from '../../../directives/accessibility/index'; import { MenuItemType } from '../menu-item/menu-item-type.enum'; import { MenuComponent } from '../menu/menu.component'; @Directive({ selector: '[uxMenuTabbableItem]', }) export class MenuTabbableItemDirective implements OnInit, OnDestroy, FocusableOption { /** Define if this item is disabled or not */ @Input() disabled: boolean = false; /** Indicate the type of the menu item */ readonly type: MenuItemType = MenuItemType.Default; /** Store the focus indicator instance */ private _focusIndicator: FocusIndicator; /** Automatically unsubscribe when directive is destroyed */ private _onDestroy$ = new Subject<void>(); constructor( private readonly _menu: MenuComponent, private readonly _elementRef: ElementRef<HTMLElement>, private readonly _focusIndicatorService: FocusIndicatorService, private readonly _renderer: Renderer2 ) { } ngOnInit(): void { // register this item in the MenuComponent this._menu._addItem(this); // we only want to show the focus indicator whenever the keyboard is used this._focusIndicator = this._focusIndicatorService.monitor(this._elementRef.nativeElement); // subscribe to active item changes this._menu._activeItem$.pipe(takeUntil(this._onDestroy$)) .subscribe(item => this.setTabIndex(item === this)); } ngOnDestroy(): void { this._onDestroy$.next(); this._onDestroy$.complete(); this._focusIndicator.destroy(); } /** Focus this item with a given origin */ focus(origin: FocusOrigin): void { this._focusIndicator.focus(origin); } /** This function is built into the CDK manager to allow jumping to items based on text content */ getLabel(): string { return this._elementRef.nativeElement.textContent.trim(); } /** Forward any keyboard events to the MenuComponent for accessibility */ @HostListener('keydown', ['$event']) _onKeydown(event: KeyboardEvent): void { this._menu._onKeydown(event); } /** Update the tab index on this item */ private setTabIndex(isTabbable: boolean): void { this._renderer.setAttribute(this._elementRef.nativeElement, 'tabindex', isTabbable ? '0' : '-1'); } }
apache-2.0
Netflix/conductor
cassandra-persistence/src/main/java/com/netflix/conductor/cassandra/util/Constants.java
2317
/* * Copyright 2022 Netflix, Inc. * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.cassandra.util; public interface Constants { String DAO_NAME = "cassandra"; String TABLE_WORKFLOWS = "workflows"; String TABLE_TASK_LOOKUP = "task_lookup"; String TABLE_TASK_DEF_LIMIT = "task_def_limit"; String TABLE_WORKFLOW_DEFS = "workflow_definitions"; String TABLE_WORKFLOW_DEFS_INDEX = "workflow_defs_index"; String TABLE_TASK_DEFS = "task_definitions"; String TABLE_EVENT_HANDLERS = "event_handlers"; String TABLE_EVENT_EXECUTIONS = "event_executions"; String WORKFLOW_ID_KEY = "workflow_id"; String SHARD_ID_KEY = "shard_id"; String TASK_ID_KEY = "task_id"; String ENTITY_KEY = "entity"; String PAYLOAD_KEY = "payload"; String TOTAL_TASKS_KEY = "total_tasks"; String TOTAL_PARTITIONS_KEY = "total_partitions"; String TASK_DEF_NAME_KEY = "task_def_name"; String WORKFLOW_DEF_NAME_KEY = "workflow_def_name"; String WORKFLOW_VERSION_KEY = "version"; String WORKFLOW_DEFINITION_KEY = "workflow_definition"; String WORKFLOW_DEF_INDEX_KEY = "workflow_def_version_index"; String WORKFLOW_DEF_INDEX_VALUE = "workflow_def_index_value"; String WORKFLOW_DEF_NAME_VERSION_KEY = "workflow_def_name_version"; String TASK_DEFS_KEY = "task_defs"; String TASK_DEFINITION_KEY = "task_definition"; String HANDLERS_KEY = "handlers"; String EVENT_HANDLER_NAME_KEY = "event_handler_name"; String EVENT_HANDLER_KEY = "event_handler"; String MESSAGE_ID_KEY = "message_id"; String EVENT_EXECUTION_ID_KEY = "event_execution_id"; String ENTITY_TYPE_WORKFLOW = "workflow"; String ENTITY_TYPE_TASK = "task"; int DEFAULT_SHARD_ID = 1; int DEFAULT_TOTAL_PARTITIONS = 1; }
apache-2.0
MarcinSzyszka/MobileSecondHand
AndroidStudio_Android/MobileSeconndHand/app/src/main/java/marcin_szyszka/mobileseconndhand/models/TokenModel.java
150
package marcin_szyszka.mobileseconndhand.models; /** * Created by marcianno on 2016-03-01. */ public class TokenModel { public String Token; }
apache-2.0
tkao1000/pinot
pinot-core/src/main/java/com/linkedin/pinot/core/segment/memory/PinotByteBuffer.java
11468
/** * Copyright (C) 2014-2015 LinkedIn Corp. (pinot-core@linkedin.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.pinot.core.segment.memory; import com.google.common.base.Preconditions; import com.linkedin.pinot.common.segment.ReadMode; import com.linkedin.pinot.common.utils.MmapUtils; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PinotByteBuffer extends PinotDataBuffer { private static final Logger LOGGER = LoggerFactory.getLogger(PinotByteBuffer.class); private ByteBuffer buffer; private RandomAccessFile raf = null; /** * Fully load the file in to the in-memory buffer * @param file file containing index data * @param readMode mmap vs heap mode for the buffer * @param openMode read or read_write mode for the index * @param context context for buffer allocation. Use mainly for resource tracking * @return in-memory buffer containing data */ public static PinotDataBuffer fromFile(File file, ReadMode readMode, FileChannel.MapMode openMode, String context) throws IOException { return PinotByteBuffer.fromFile(file, 0, file.length(), readMode, openMode, context); } /** * Loads a portion of file in memory. This will load data from [startPosition, startPosition + length). * @param file file to load * @param startPosition (inclusive) start startPosition to the load the data from in the file * @param length size of the data from * @param readMode mmap vs heap * @param openMode read vs read/write * @param context context for buffer allocation. Use mainly for resource tracking * @return in-memory buffer containing data * @throws IOException */ public static PinotDataBuffer fromFile(File file, long startPosition, long length, ReadMode readMode, FileChannel.MapMode openMode, String context) throws IOException { if (readMode == ReadMode.heap) { return PinotByteBuffer.loadFromFile(file, startPosition, length, context); } else if (readMode == ReadMode.mmap) { return PinotByteBuffer.mapFromFile(file, startPosition, length, openMode, context); } else { throw new RuntimeException("Unknown readmode: " + readMode.name() + ", file: " + file); } } static PinotDataBuffer mapFromFile(File file, long start, long length, FileChannel.MapMode openMode, String context) throws IOException { // file may not exist if it's opened for writing Preconditions.checkNotNull(file); Preconditions.checkArgument(start >= 0); Preconditions.checkArgument(length >= 0 && length < Integer.MAX_VALUE, "Mapping files larger than 2GB is not supported, file: " + file.toString() + ", context: " + context); Preconditions.checkNotNull(context); if (openMode == FileChannel.MapMode.READ_ONLY) { if (!file.exists()) { throw new IllegalArgumentException("File: " + file + " must exist to open in read-only mode"); } if (length > (file.length() - start)) { throw new IllegalArgumentException( String.format("Mapping limits exceed file size, start: %d, length: %d, file size: %d", start, length, file.length() )); } } String rafOpenMode = openMode == FileChannel.MapMode.READ_ONLY ? "r" : "rw"; RandomAccessFile raf = new RandomAccessFile(file, rafOpenMode); ByteBuffer bb = MmapUtils.mmapFile(raf, openMode, start, length, file, context); PinotByteBuffer pbb = new PinotByteBuffer(bb, true /*owner*/); pbb.raf = raf; return pbb; } static PinotDataBuffer loadFromFile(File file, long startPosition, long length, String context) throws IOException { Preconditions.checkArgument(length >= 0 && length < Integer.MAX_VALUE); Preconditions.checkNotNull(file); Preconditions.checkArgument(startPosition >= 0); Preconditions.checkNotNull(context); Preconditions.checkState(file.exists(), "File: {} does not exist", file); Preconditions.checkState(file.isFile(), "File: {} is not a regular file", file); PinotByteBuffer buffer = allocateDirect((int)length, file.toString() + "-" + context); buffer.readFrom(file, startPosition, length); return buffer; } public static PinotByteBuffer allocateDirect(long size, String context) { Preconditions.checkArgument(size >= 0 && size < Integer.MAX_VALUE); Preconditions.checkNotNull(context); ByteBuffer bb = MmapUtils.allocateDirectByteBuffer( (int)size, null, context); return new PinotByteBuffer(bb, true/*owner*/); } // package-private PinotByteBuffer(ByteBuffer buffer, boolean ownership) { this.buffer = buffer; this.owner = ownership; } @Override public byte getByte(long index) { throw new UnsupportedOperationException("Long index is not supported"); } @Override public byte getByte(int index) { return buffer.get(index); } @Override public void putByte(long index, byte val) { throw new UnsupportedOperationException("Long index is not supported"); } @Override public void putByte(int index, byte value) { buffer.put(index, value); } @Override public void putChar(long index, char c) { throw new UnsupportedOperationException("Long index is not supported"); } @Override public char getChar(long index) { throw new UnsupportedOperationException("Long index is not supported"); } @Override public char getChar(int index) { return buffer.getChar(index); } @Override public void putChar(int index, char value) { buffer.putChar(index, value); } @Override public short getShort(int index) { return buffer.getShort(index); } @Override public short getShort(long index) { throw new UnsupportedOperationException("Long index is not supported"); } @Override public void putShort(int index, short value) { buffer.putShort(index, value); } @Override public void putShort(long index, short value) { throw new UnsupportedOperationException("Long index is not supported"); } @Override public int getInt(int index) { return buffer.getInt(index); } @Override public int getInt(long index) { throw new UnsupportedOperationException("Long index is not supported"); } @Override public void putInt(int index, int value) { buffer.putInt(index, value); } @Override public void putInt(long index, int value) { throw new UnsupportedOperationException("Long index is not supported"); } @Override public void putLong(long index, long l1) { throw new UnsupportedOperationException("Long index is not supported"); } @Override public long getLong(long index) { throw new UnsupportedOperationException("Long index is not supported"); } @Override public void putLong(int index, long value) { buffer.putLong(index, value); } @Override public long getLong(int index) { return buffer.getLong(index); } @Override public void putFloat(long index, float v) { throw new UnsupportedOperationException("Long index is not supported"); } @Override public void putFloat(int index, float value) { buffer.putFloat(index, value); } @Override public float getFloat(int index) { return buffer.getFloat(index); } @Override public float getFloat(long index) { throw new UnsupportedOperationException("Long index is not supported"); } @Override public double getDouble(int index) { return buffer.getDouble(index); } @Override public double getDouble(long l) { throw new UnsupportedOperationException("Long index is not supported"); } @Override public void putDouble(int index, double value) { buffer.putDouble(index, value); } @Override public void putDouble(long index, double value) { throw new UnsupportedOperationException("Long index is not supported"); } @Override public PinotDataBuffer view(long start, long end) { Preconditions.checkArgument(start >= 0 && start <= buffer.limit(), "View start position is not valid, start: {}, end: {}, buffer limit: {}", start, end, buffer.limit()); Preconditions.checkArgument(end >= start && end <= buffer.limit(), "View end position is not valid, start: {}, end: {}, buffer limit: {}", start, end, buffer.limit()); ByteBuffer bb = this.buffer.duplicate(); bb.position((int)start); bb.limit((int)end); return new PinotByteBuffer(bb.slice(), false); } @Override public void copyTo(long srcOffset, byte[] destArray, int destOffset, int size) { ByteBuffer srcBB = buffer.duplicate(); srcBB.position((int)srcOffset); srcBB.get(destArray, destOffset, size); } @Override public int readFrom(byte[] src, long destOffset) { return readFrom(src, 0, destOffset, src.length); } @Override public int readFrom(byte[] src, int srcOffset, long destOffset, int length) { ByteBuffer dup = buffer.duplicate(); dup.position((int)destOffset); dup.put(src, srcOffset, length); return length; } @Override public int readFrom(ByteBuffer sourceBuffer, int srcOffset, long destOffset, int length) { ByteBuffer srcDup = sourceBuffer.duplicate(); ByteBuffer localDup = buffer.duplicate(); srcDup.position(srcOffset); srcDup.limit(srcOffset + length); localDup.put(srcDup); return length; } @Override public void readFrom(File dataFile) throws IOException { readFrom(dataFile, 0, dataFile.length()); } @Override protected void readFrom(File file, long startPosition, long length) throws IOException { try (RandomAccessFile raf = new RandomAccessFile(file, "r") ) { raf.getChannel().position(startPosition); ByteBuffer dup = buffer.duplicate(); dup.position(0); dup.limit((int) length); raf.getChannel().read(dup, startPosition); } } @Override public long size() { return buffer.capacity(); } @Override public long address() { return 0; } @Override public ByteBuffer toDirectByteBuffer(long bufferOffset, int size) { ByteBuffer bb = buffer.duplicate(); bb.position((int)bufferOffset); bb.limit((int)bufferOffset + size); return bb.slice(); } @Override protected long start() { return buffer.clear().position(); } @Override public PinotDataBuffer duplicate() { PinotByteBuffer dup = new PinotByteBuffer(this.buffer.duplicate(), false); return dup; } @Override public void close() { if (!owner || buffer == null) { return; } MmapUtils.unloadByteBuffer(buffer); if (raf != null) { try { raf.close(); } catch (IOException e) { LOGGER.error("Failed to close file: {}. Continuing with errors", raf.toString(), e); } } buffer = null; raf = null; } }
apache-2.0
Samuel789/MediPi
MediPiPatient/MediPi/src/main/java/org/medipi/devices/drivers/domain/DeviceTimestampUpdateInterface.java
987
/* Copyright 2016 Richard Robinson @ NHS Digital <rrobinson@nhs.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.medipi.devices.drivers.domain; import javafx.scene.Node; /** * Interface to allow the DeviceTimestampchecker to call the individual time * reload guide for a device when the timestamp is assessed to need resetting * * @author rick@robinsonhq.com */ public interface DeviceTimestampUpdateInterface { public Node getDeviceTimestampUpdateMessageBoxContent(); }
apache-2.0
summerDp/dpCms
src/main/java/org/summer/dp/cms/support/persistence/ReduceJsonDataParam.java
455
package org.summer.dp.cms.support.persistence; import java.util.ArrayList; import java.util.List; /** * @category 这个类用于保存前端传过来减少Hibernate发送SQL * @author Administrator * */ public class ReduceJsonDataParam { private List<String> rjdParams = new ArrayList<String>(3); public List<String> getRjdParams() { return rjdParams; } public void setRjdParams(List<String> rjdParams) { this.rjdParams = rjdParams; } }
apache-2.0
Thellmann/callimachus
webapp/scripts/vbox.js
814
// vbox.js (function($){ $(document).ready(function() { vbox(select(document, ".vbox")); }); $(document).bind("DOMNodeInserted", handle); $(window).resize(function(){vbox($('.vbox'))}); function select(node, selector) { var set = $(node).find(selector).andSelf(); set = set.add($(node).parents(selector)); return set.filter(selector); } function handle(event) { vbox(select(event.target, ".vbox")); } function vbox(element) { var children = element.children().filter(function() { var pos = $(this).css('position'); return pos != 'absolute' && pos != 'fixed' && pos != 'relative'; }); children.css("margin-bottom", "0.15em"); children.filter(':not(:input)').css("display", "table"); children.filter(':input').css("display", "block"); } })(window.jQuery);
apache-2.0
huahuajjh/yueyouyuebei
src/TravelAgent.Web/TravelAgent.Web/member/UpdatePassword.aspx.designer.cs
847
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:2.0.50727.3053 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace TravelAgent.Web.member { public partial class UpdatePassword { /// <summary> /// Master 属性。 /// </summary> /// <remarks> /// 自动生成的属性。 /// </remarks> public new TravelAgent.Web.member.Member Master { get { return ((TravelAgent.Web.member.Member)(base.Master)); } } } }
apache-2.0
jaschenk/jeffaschenk-commons
src/main/java/jeffaschenk/commons/standards/statecodes/StateCodes_SA.java
2492
package jeffaschenk.commons.standards.statecodes; import jeffaschenk.commons.standards.CountryCode; /** * Official ISO-3166 State/Province Codes * <p/> * Country: Saudi Arabia * * @author jeffaschenk@gmail.com * Date: May 19, 2010 * Time: 12:12:11 PM */ @SuppressWarnings("unused") public enum StateCodes_SA { /** * State Code Enumerator */ SA_06("Hail", "SA-06", "Region", "17981", CountryCode.SAUDI_ARABIA), SA_14("Aseer", "SA-14", "Region", "17984", CountryCode.SAUDI_ARABIA), SA_08("Al Hudud Ash Shamaliyah", "SA-08", "Region", "17985", CountryCode.SAUDI_ARABIA), SA_11("Baha", "SA-11", "Region", "17980", CountryCode.SAUDI_ARABIA), SA_12("Al Jawf", "SA-12", "Region", "17982", CountryCode.SAUDI_ARABIA), SA_03("Al Madinah", "SA-03", "Region", "17979", CountryCode.SAUDI_ARABIA), SA_05("Al Qasim", "SA-05", "Region", "17988", CountryCode.SAUDI_ARABIA), SA_01("Riyadh", "SA-01", "Region", "17978", CountryCode.SAUDI_ARABIA), SA_04("Ash Sharqiyah", "SA-04", "Region", "17989", CountryCode.SAUDI_ARABIA), SA_09("Jizan", "SA-09", "Region", "17986", CountryCode.SAUDI_ARABIA), SA_02("Makkah", "SA-02", "Region", "17987", CountryCode.SAUDI_ARABIA), SA_10("Najran", "SA-10", "Region", "17983", CountryCode.SAUDI_ARABIA), SA_07("Tabuk", "SA-07", "Region", "17977", CountryCode.SAUDI_ARABIA); // ************************************* // Common Enum Structure for all // States of the World private final String stateProvinceName; private final String stateCode; private final String stateProvinceType; private final String stateNumericCode; private final CountryCode countryCode; StateCodes_SA(String stateProvinceName, String stateCode, String stateProvinceType, String stateNumericCode, CountryCode countryCode) { this.stateProvinceName = stateProvinceName; this.stateCode = stateCode; this.stateProvinceType = stateProvinceType; this.stateNumericCode = stateNumericCode; this.countryCode = countryCode; } public String stateProvinceName() { return this.stateProvinceName; } public String stateCode() { return this.stateCode; } public String stateProvinceType() { return this.stateProvinceType; } public String stateNumericCode() { return this.stateNumericCode; } public CountryCode countryCode() { return this.countryCode; } }
apache-2.0
scottdangelo/unity-sdk
Scripts/Utilities/FrameRateCounter.cs
1546
/** * Copyright 2015 IBM Corp. 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. * */ using UnityEngine; using UnityEngine.UI; namespace IBM.Watson.DeveloperCloud.Utilities { /// <summary> /// Displays the frame rate of the application. /// </summary> public class FrameRateCounter : MonoBehaviour { const float FPS_INTERVAL = 0.5f; const string DISPLAY = "{0} FPS"; private int m_FpsAccumulator = 0; private float m_FpsNextPeriod = 0; private int m_CurrentFps; [SerializeField] private Text m_Text; private void Start() { m_FpsNextPeriod = Time.realtimeSinceStartup + FPS_INTERVAL; } private void Update() { // measure average frames per second m_FpsAccumulator++; if (Time.realtimeSinceStartup > m_FpsNextPeriod) { m_CurrentFps = (int)(m_FpsAccumulator / FPS_INTERVAL); m_FpsAccumulator = 0; m_FpsNextPeriod += FPS_INTERVAL; m_Text.text = string.Format(DISPLAY, m_CurrentFps); } } } }
apache-2.0
apache/incubator-freemarker
src/main/java/freemarker/template/MapKeyValuePairIterator.java
2357
/* * 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 freemarker.template; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import freemarker.template.TemplateHashModelEx2.KeyValuePair; import freemarker.template.TemplateHashModelEx2.KeyValuePairIterator; /** * Implementation of {@link KeyValuePairIterator} for a {@link TemplateHashModelEx2} that wraps or otherwise uses a * {@link Map} internally. * * @since 2.3.25 */ public class MapKeyValuePairIterator implements KeyValuePairIterator { private final Iterator<Entry<?, ?>> entrySetIterator; private final ObjectWrapper objectWrapper; @SuppressWarnings({ "rawtypes", "unchecked" }) public <K, V> MapKeyValuePairIterator(Map<?, ?> map, ObjectWrapper objectWrapper) { entrySetIterator = ((Map) map).entrySet().iterator(); this.objectWrapper = objectWrapper; } public boolean hasNext() { return entrySetIterator.hasNext(); } public KeyValuePair next() { final Entry<?, ?> entry = entrySetIterator.next(); return new KeyValuePair() { public TemplateModel getKey() throws TemplateModelException { return wrap(entry.getKey()); } public TemplateModel getValue() throws TemplateModelException { return wrap(entry.getValue()); } }; } private TemplateModel wrap(Object obj) throws TemplateModelException { return (obj instanceof TemplateModel) ? (TemplateModel) obj : objectWrapper.wrap(obj); } }
apache-2.0
jdebrabant/parallel_arules
src/util/laur/dm/ar/Itemset.java
21095
/* Itemset.java (P)1999-2001 Laurentiu Cristofor */ /* laur.dm.ar - A Java package for association rule mining Copyright (C) 2002 Laurentiu Cristofor This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA The laur.dm.ar package was written by Laurentiu Cristofor (laur@cs.umb.edu). */ package laur.dm.ar; import java.util.ArrayList; /** An itemset is an ordered list of integers that identify items coupled with a double value representing the support of the itemset as a percentage. @version 1.0 @author Laurentiu Cristofor */ public class Itemset implements java.io.Serializable, CriteriaComparable { /** * Specifies sorting should be performed according to itemset size. */ public static final int BY_SIZE = 0; /** * Specifies sorting should be performed according to itemset support. */ public static final int BY_SUPPORT = 1; private static final int SIZE_INCR = 7; /** * The capacity of the itemset. * * @serial */ private int capacity; /** * The number of items in the itemset. * * @serial */ private int size; /** * The itemset. * * @serial */ private int[] set; /** * The support of the itemset. * * @serial */ private double support; /** * The weight of the itemset. * * @serial */ private long weight; /** * The mark of the itemset. Can be used to mark the itemset for * various purposes * * @serial */ private boolean mark; /** * Create a new empty itemset of specified capacity. * * @param c the capacity of the itemset * @exception IllegalArgumentException <code>c</code> is negative or zero */ public Itemset(int c) { if (c < 1) throw new IllegalArgumentException("initial capacity must be a positive value"); capacity = c; set = new int[capacity]; size = 0; support = 0; weight = 0; mark = false; } /** * Creates a new empty itemset. */ public Itemset() { this(SIZE_INCR); } /** * Create a new itemset by copying a given one. * * @param itemset the itemset to be copied * @exception IllegalArgumentException <code>itemset</code> is null */ public Itemset(Itemset itemset) { if (itemset == null) throw new IllegalArgumentException("null itemset"); capacity = itemset.capacity; set = new int[capacity]; size = itemset.size; for (int i = 0; i < size; i++) set[i] = itemset.set[i]; support = itemset.support; weight = itemset.weight; mark = itemset.mark; } /** * Return support of itemset. */ public double getSupport() { return support; } /** * Set the support of the itemset. * * @param newSupport the support of the itemset * @exception IllegalArgumentException <code>newSupport</code> is < 0 * or > 100 */ public void setSupport(double newSupport) { if (newSupport < 0 || newSupport > 1) throw new IllegalArgumentException("support must be between 0 and 1"); support = newSupport; } /** * Return weight of itemset. */ public long getWeight() { return weight; } /** * Set the weight of the itemset. * * @param newWeight the weight of the itemset * @exception IllegalArgumentException <code>newWeight</code> is < 0 */ public void setWeight(long newWeight) { if (newWeight < 0) throw new IllegalArgumentException("weight must be >= 0"); weight = newWeight; } /** * Increment the weight of the itemset. */ public void incrementWeight() { weight++; } /** * Return size of itemset. * * @return size of itemset */ public int size() { return size; } /** * Return i-th item in itemset. The count starts from 0. * * @param i the index of the item to get * @exception IndexOutOfBoundsException <code>i</code> is an invalid index * @return the <code>i</code>-th item */ public int get(int i) { if (i < 0 || i >= size) throw new IndexOutOfBoundsException("invalid index"); return set[i]; } /** * Add a new item to the itemset. * * @param item the item to be added * @exception IllegalArgumentException <code>item</code> is <= 0 * @return true if item was added, false if it wasn't added (was * already there!) */ public boolean add(int item) { if (item <= 0) throw new IllegalArgumentException("item must be a positive value"); if (size == 0) set[0] = item; else { // look for place to insert item int index; for (index = 0; index < size && item > set[index]; index++) ; // if item was already in itemset then return if (index < size && item == set[index]) return false; // if set is full then allocate new array if (size == capacity) { capacity = size + SIZE_INCR; int[] a = new int[capacity]; int i; for (i = 0; i < index; i++) a[i] = set[i]; // insert new item a[i] = item; for ( ; i < size; i++) a[i + 1] = set[i]; set = a; } // otherwise make place and insert new item else { int i; for (i = size; i > index; i--) set[i] = set[i - 1]; set[i] = item; } } // update size size++; return true; } /** * Removes a given item from the itemset. * * @param item the item to remove * @exception IllegalArgumentException <code>item</code> is <= 0 * @return true if item was removed, false if it wasn't removed (was * not found in itemset!) */ public boolean remove(int item) { if (item <= 0) throw new IllegalArgumentException("item must be a positive value"); int index; for (index = 0; index < size && item != set[index] ; index++) ; if (item == set[index]) { for (++index; index < size; index++) set[index - 1] = set[index]; size--; return true; } else return false; } /** * Removes last item (which has the greatest value) from the itemset. * * @return true if item was removed, false if it wasn't removed (the * itemset was empty) */ public boolean removeLast() { if (size > 0) { size--; return true; } else return false; } /** * Compare two Itemset objects on one of several criteria. * * @param is the Itemset object with which we want to compare this * object * @param criteria the criteria on which we want to compare, can * be one of SIZE or SUPPORT. * @exception IllegalArgumentException <code>obj</code> is not * an Itemset or criteria is invalid * @return a negative value if this object is smaller than * <code>is</code>, 0 if they are equal, and a positive value if this * object is greater. */ public int compareTo(Object obj, int criteria) { if (!(obj instanceof Itemset)) throw new IllegalArgumentException("not an itemset"); Itemset is = (Itemset)obj; double diff; if (criteria == BY_SIZE) return size() - is.size(); else if (criteria == BY_SUPPORT) diff = support - is.support; else throw new IllegalArgumentException("invalid criteria"); if (diff < 0) return -1; else if (diff > 0) return 1; else return 0; } /** * Checks equality with another object. * * @param o the object against which we test for equality * @return true if object is equal to our itemset, false otherwise */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Itemset)) return false; Itemset itemset = (Itemset)o; if (size != itemset.size()) return false; for (int i = 0; i < size; i++) if (set[i] != itemset.set[i]) return false; return true; } /** * Checks inclusion in a given itemset. * * @param itemset the itemset against which we test for inclusion * @exception IllegalArgumentException <code>itemset</code> is null */ public boolean isIncludedIn(Itemset itemset) { if (itemset == null) throw new IllegalArgumentException("null itemset"); if (itemset.size() < size) return false; int i, j; for (i = 0, j = 0; i < size && j < itemset.size() && set[i] >= itemset.set[j]; j++) if (set[i] == itemset.set[j]) i++; if (i == size) return true; else return false; } /** * Return true if this itemset has items in common * with <code>itemset</code>. * * @param itemset the itemset with which we compare * @exception IllegalArgumentException <code>itemset</code> is null * @return true if <code>itemset</code> contains items of this * itemset, false otherwise. */ public boolean intersects(Itemset itemset) { if (itemset == null) throw new IllegalArgumentException("null itemset"); Itemset result = new Itemset(capacity); int i = 0; int j = 0; for ( ; i < size && j < itemset.size; ) { // if elements are equal, return true if (set[i] == itemset.set[j]) return true; // if the element in this Itemset is bigger then // we need to move to the next item in itemset. else if (set[i] > itemset.set[j]) j++; // the element in this Itemset does not appear // in itemset so we need to add it to result else i++; } return false; } /** * Return a new Itemset that contains only those items from * <code>is1</code> that do not appear in <code>is2</code>. * * @param is1 the itemset from which we want to subtract * @param is2 the itemset whose items we want to subtract * @exception IllegalArgumentException <code>is1</code> or * <code>is2</code> is null * @return an Itemset containing only those items of * <code>is1</code> that do not appear in <code>is2</code>. */ public static synchronized Itemset subtraction(Itemset is1, Itemset is2) { if (is1 == null || is2 == null) throw new IllegalArgumentException("null itemset"); Itemset result = new Itemset(is1.size); int i = 0; int j = 0; for ( ; i < is1.size && j < is2.size; ) { // if elements are equal, move to next ones if (is1.set[i] == is2.set[j]) { i++; j++; } // if the element in is1 is bigger then // we need to move to the next item in is2. else if (is1.set[i] > is2.set[j]) j++; // the element in is1 does not appear // in is2 so we need to add it to result else result.set[result.size++] = is1.set[i++]; } // copy any remaining items from is1 while (i < is1.size) result.set[result.size++] = is1.set[i++]; // NOTE: the size of the resulting itemset // has been automatically updated return result; } /** * Return a new Itemset that contains all those items that appear * in <code>is1</code> and in <code>is2</code>. * * @param is1 the first itemset participating to the union * @param is2 the second itemset participating to the union * @exception IllegalArgumentException <code>is1</code> or * <code>is2</code> is null * @return an Itemset containing all those items that appear * in <code>is1</code> and in <code>is2</code>. */ public static synchronized Itemset union(Itemset is1, Itemset is2) { if (is1 == null || is2 == null) throw new IllegalArgumentException("null itemset"); Itemset result = new Itemset(is1.size + is2.size); int i = 0; int j = 0; for ( ; i < is1.size && j < is2.size; ) { // if elements are equal, copy then move to next ones if (is1.set[i] == is2.set[j]) { result.set[result.size++] = is1.set[i++]; j++; } // if the element in is1 is bigger then // we need to copy from is2 and then move to the next item. else if (is1.set[i] > is2.set[j]) result.set[result.size++] = is2.set[j++]; // else we need to copy from is1 else result.set[result.size++] = is1.set[i++]; } // copy any remaining items from is1 while (i < is1.size) result.set[result.size++] = is1.set[i++]; // copy any remaining items from is2 while (j < is2.size) result.set[result.size++] = is2.set[j++]; // NOTE: the size of the resulting itemset // has been automatically updated return result; } /** * Check whether two itemsets can be combined. Two itemsets can be * combined if they differ only in the last item. * * @param itemset itemset with which to combine * @exception IllegalArgumentException <code>itemset</code> is null * @return true if the itemsets can be combined, false otherwise */ public boolean canCombineWith(Itemset itemset) { if (itemset == null) throw new IllegalArgumentException("null itemset"); if (size != itemset.size) return false; if (size == 0) return false; for (int i = 0; i < size - 1; i++) if (set[i] != itemset.set[i]) return false; return true; } /** * Combine two itemsets into a new one that will contain all the * items in the first itemset plus the last item in the second * itemset. * * @param itemset itemset with which to combine * @exception IllegalArgumentException <code>itemset</code> is null * @return an itemset that combines the two itemsets as described * above */ public Itemset combineWith(Itemset itemset) { if (itemset == null) throw new IllegalArgumentException("null itemset"); Itemset is = new Itemset(this); is.support = 0; is.weight = 0; is.add(itemset.set[itemset.size - 1]); return is; } /** * Mark the itemset. * * @return true if itemset was already marked, false otherwise */ public boolean mark() { boolean old_mark = mark; mark = true; return old_mark; } /** * Unmark the itemset. * * @return true if itemset was marked, false otherwise */ public boolean unmark() { boolean old_mark = mark; mark = false; return old_mark; } /** * Return itemset mark. * * @return true if itemset is marked, false otherwise */ public boolean isMarked() { return mark; } /** * Return a String representation of the Itemset. * * @return String representation of Itemset */ public String toString() { String s = ""; for (int i = 0; i < size; i++) s += set[i] + " "; //s += "(" + support + ")"; return s; } /** * Remove all non-maximal itemsets from the vector v * * @param v the collection of itemsets */ public static synchronized void pruneNonMaximal(ArrayList v) { int i, j; int size = v.size(); for (i = 0; i < size; i++) { // see if anything is included in itemset at index i for (j = i + 1; j < size; j++) if (((Itemset)v.get(j)).isIncludedIn((Itemset)v.get(i))) { // replace this element with last, delete last, // and don't advance index v.set(j, v.get(v.size() - 1)); v.remove(--size); j--; } // see if itemset at index i is included in another itemset for (j = i + 1; j < size; j++) if (((Itemset)v.get(i)).isIncludedIn((Itemset)v.get(j))) { // replace this element with last, delete last, // and don't advance index v.set(i, v.get(v.size() - 1)); v.remove(--size); i--; break; } } } /** * Remove all duplicate itemsets from the vector v * * @param v the collection of itemsets */ public static synchronized void pruneDuplicates(ArrayList v) { int i, j; int size = v.size(); for (i = 0; i < size; i++) { // see if anything is equal to itemset at index i for (j = i + 1; j < size; j++) if (((Itemset)v.get(j)).equals((Itemset)v.get(i))) { // replace this element with last, delete last, // and don't advance index v.set(j, v.get(v.size() - 1)); v.remove(--size); j--; } } } /** * sample usage and testing */ public static void main(String[] args) { Itemset is1 = new Itemset(); Itemset is2 = new Itemset(); is1.add(7); is1.add(3); is1.add(15); is1.add(5); is1.add(12); is1.add(12); System.out.println("is1: " + is1); is2.add(12); is2.add(15); is2.add(7); is2.add(5); is2.add(3); is2.add(8); System.out.println("is2: " + is2); System.out.println("do is1 and is2 share items: " + is1.intersects(is2)); System.out.println("do is2 and is1 share items: " + is2.intersects(is1)); Itemset is3 = Itemset.subtraction(is1, is2); System.out.println("is3 <= subtracting is2 from is1:" + is3); System.out.println("do is1 and is3 share items: " + is1.intersects(is3)); System.out.println("do is3 and is1 share items: " + is3.intersects(is1)); is3 = Itemset.subtraction(is2, is1); System.out.println("is3 <= subtracting is1 from is2:" + is3); System.out.println("do is1 and is3 share items: " + is1.intersects(is3)); System.out.println("do is3 and is1 share items: " + is3.intersects(is1)); System.out.println("do is3 and is2 share items: " + is3.intersects(is2)); System.out.println("do is2 and is3 share items: " + is2.intersects(is3)); is1.add(17); System.out.println("is1: " + is1); System.out.println("is2: " + is2); System.out.println("adding is2 to is1:" + Itemset.union(is1, is2)); System.out.println("adding is1 to is2:" + Itemset.union(is2, is1)); System.out.println("is1: " + is1); System.out.println("is2: " + is2); System.out.println("is1 equal to is2: " + is1.equals(is2)); System.out.println("is1 included in is2: " + is1.isIncludedIn(is2)); System.out.println("is2 included in is1: " + is2.isIncludedIn(is1)); is1.add(8); System.out.println("is1: " + is1); System.out.println("is1 equal to is2: " + is1.equals(is2)); System.out.println("is1 included in is2: " + is1.isIncludedIn(is2)); System.out.println("is2 included in is1: " + is2.isIncludedIn(is1)); is1.add(1); System.out.println("is1: " + is1); System.out.println("is1 equal to is2: " + is1.equals(is2)); System.out.println("is1 included in is2: " + is1.isIncludedIn(is2)); System.out.println("is2 included in is1: " + is2.isIncludedIn(is1)); is1.add(50); System.out.println("is1: " + is1); System.out.println("is1 equal to is2: " + is1.equals(is2)); System.out.println("is1 included in is2: " + is1.isIncludedIn(is2)); System.out.println("is2 included in is1: " + is2.isIncludedIn(is1)); is1.add(100); System.out.println("is1: " + is1); System.out.println("is1 equal to is2: " + is1.equals(is2)); System.out.println("is1 included in is2: " + is1.isIncludedIn(is2)); System.out.println("is2 included in is1: " + is2.isIncludedIn(is1)); System.out.println("adding 70 to is2: " + is2.add(70)); System.out.println("adding 70 to is2: " + is2.add(70)); System.out.println("is2: " + is2); System.out.println("is1 equal to is2: " + is1.equals(is2)); System.out.println("is1 included in is2: " + is1.isIncludedIn(is2)); System.out.println("is2 included in is1: " + is2.isIncludedIn(is1)); System.out.println("removing 1 from is1: " + is1.remove(1)); System.out.println("removing 1 from is1: " + is1.remove(1)); System.out.println("is1: " + is1); System.out.println("removing 50 from is1: " + is1.remove(50)); System.out.println("is1: " + is1); System.out.println("removing 70 from is2: " + is2.remove(70)); System.out.println("is2: " + is2); System.out.print("going through items of is1:"); for (int i = 0; i < is1.size(); i++) System.out.print(" " + is1.get(i)); System.out.println(""); System.out.print("going through items of is2:"); for (int i = 0; i < is2.size(); i++) System.out.print(" " + is2.get(i)); System.out.println(""); while (is2.removeLast()) ; System.out.println("is2: " + is2); System.out.println("mark is1, previous state: " + is1.mark()); System.out.println("mark is1, previous state: " + is1.mark()); System.out.println("is1 mark state: " + is1.isMarked()); System.out.println("unmark is1, previous state: " + is1.unmark()); System.out.println("unmark is1, previous state: " + is1.unmark()); } }
apache-2.0
ov3rflow/eFaps-Kernel
src/main/java/org/efaps/admin/datamodel/ui/EnumUI.java
1714
/* * Copyright 2003 - 2013 The eFaps Team * * 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. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package org.efaps.admin.datamodel.ui; import java.io.Serializable; import org.efaps.util.EFapsException; /** * TODO comment! * * @author The eFaps Team * @version $Id$ */ public class EnumUI implements IUIProvider, Serializable { /** * */ private static final long serialVersionUID = 1L; /** * {@inheritDoc} */ @Override public Object getValue(final UIValue _uiValue) throws EFapsException { return _uiValue.getDbValue(); } /** * {@inheritDoc} */ @Override public String validateValue(final UIValue _uiValue) throws EFapsException { return null; } /** * {@inheritDoc} */ @Override public Object transformObject(final UIValue _uiValue, final Object _object) throws EFapsException { if (_object instanceof Serializable) { _uiValue.setDbValue((Serializable) _object); } return _object; } }
apache-2.0
EtherTyper/react-lang
lib/elements/patternElements.js
5448
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require("react"); var _react2 = _interopRequireDefault(_react); var _ = require(".."); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return _sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Patterns = function Patterns() { var Super = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Object; return function (_Super) { _inherits(BasicElements, _Super); function BasicElements() { _classCallCheck(this, BasicElements); return _possibleConstructorReturn(this, (BasicElements.__proto__ || Object.getPrototypeOf(BasicElements)).apply(this, arguments)); } _createClass(BasicElements, null, [{ key: "pattern", value: function pattern(element, props, children) { return (0, _.generateAST)(_react2.default.createElement("node", props)); } }, { key: "assignmentProperty", value: function assignmentProperty(element, props, children) { var _children$filter = children.filter(function (child) { return child.type !== 'Decorator'; }), _children$filter2 = _slicedToArray(_children$filter, 2), key = _children$filter2[0], value = _children$filter2[1]; return _extends({}, (0, _.generateAST)(_react2.default.createElement("objectProperty", props)), { value: value }); } }, { key: "objectPattern", value: function objectPattern(element, props, children) { var properties = children; return _extends({}, (0, _.generateAST)(_react2.default.createElement("pattern", { type: "ObjectPattern" })), { properties: properties }); } }, { key: "arrayPattern", value: function arrayPattern(element, props, children) { var elements = children.map(function (child) { return child.type === 'NullLiteral' ? null : child; }); return _extends({}, (0, _.generateAST)(_react2.default.createElement("pattern", { type: "ArrayPattern" })), { elements: elements }); } }, { key: "restElement", value: function restElement(element, props, children) { var _children = _slicedToArray(children, 1), argument = _children[0]; return _extends({}, (0, _.generateAST)(_react2.default.createElement("pattern", { type: "RestElement" })), { argument: argument }); } }, { key: "assignmentPattern", value: function assignmentPattern(element, props, children) { var _children2 = _slicedToArray(children, 2), left = _children2[0], right = _children2[1]; return _extends({}, (0, _.generateAST)(_react2.default.createElement("pattern", { type: "AssignmentPattern" })), { left: left, right: right }); } }]); return BasicElements; }(Super); }; exports.default = Patterns;
apache-2.0
SES-fortiss/SmartGridCoSimulation
core/cim15/src/CIM15/IEC61968/PaymentMetering/Receipt.java
18452
/** */ package CIM15.IEC61968.PaymentMetering; import CIM15.IEC61970.Core.IdentifiedObject; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.util.BasicInternalEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Receipt</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link CIM15.IEC61968.PaymentMetering.Receipt#getVendorShift <em>Vendor Shift</em>}</li> * <li>{@link CIM15.IEC61968.PaymentMetering.Receipt#isIsBankable <em>Is Bankable</em>}</li> * <li>{@link CIM15.IEC61968.PaymentMetering.Receipt#getLine <em>Line</em>}</li> * <li>{@link CIM15.IEC61968.PaymentMetering.Receipt#getCashierShift <em>Cashier Shift</em>}</li> * <li>{@link CIM15.IEC61968.PaymentMetering.Receipt#getTenders <em>Tenders</em>}</li> * <li>{@link CIM15.IEC61968.PaymentMetering.Receipt#getTransactions <em>Transactions</em>}</li> * </ul> * </p> * * @generated */ public class Receipt extends IdentifiedObject { /** * The cached value of the '{@link #getVendorShift() <em>Vendor Shift</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getVendorShift() * @generated * @ordered */ protected VendorShift vendorShift; /** * The default value of the '{@link #isIsBankable() <em>Is Bankable</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isIsBankable() * @generated * @ordered */ protected static final boolean IS_BANKABLE_EDEFAULT = false; /** * The cached value of the '{@link #isIsBankable() <em>Is Bankable</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isIsBankable() * @generated * @ordered */ protected boolean isBankable = IS_BANKABLE_EDEFAULT; /** * This is true if the Is Bankable attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean isBankableESet; /** * The cached value of the '{@link #getLine() <em>Line</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLine() * @generated * @ordered */ protected LineDetail line; /** * The cached value of the '{@link #getCashierShift() <em>Cashier Shift</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCashierShift() * @generated * @ordered */ protected CashierShift cashierShift; /** * The cached value of the '{@link #getTenders() <em>Tenders</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTenders() * @generated * @ordered */ protected EList<Tender> tenders; /** * The cached value of the '{@link #getTransactions() <em>Transactions</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTransactions() * @generated * @ordered */ protected EList<Transaction> transactions; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Receipt() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return PaymentMeteringPackage.Literals.RECEIPT; } /** * Returns the value of the '<em><b>Vendor Shift</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61968.PaymentMetering.VendorShift#getReceipts <em>Receipts</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Vendor Shift</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Vendor Shift</em>' reference. * @see #setVendorShift(VendorShift) * @see CIM15.IEC61968.PaymentMetering.VendorShift#getReceipts * @generated */ public VendorShift getVendorShift() { if (vendorShift != null && vendorShift.eIsProxy()) { InternalEObject oldVendorShift = (InternalEObject)vendorShift; vendorShift = (VendorShift)eResolveProxy(oldVendorShift); if (vendorShift != oldVendorShift) { } } return vendorShift; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public VendorShift basicGetVendorShift() { return vendorShift; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetVendorShift(VendorShift newVendorShift, NotificationChain msgs) { VendorShift oldVendorShift = vendorShift; vendorShift = newVendorShift; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61968.PaymentMetering.Receipt#getVendorShift <em>Vendor Shift</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Vendor Shift</em>' reference. * @see #getVendorShift() * @generated */ public void setVendorShift(VendorShift newVendorShift) { if (newVendorShift != vendorShift) { NotificationChain msgs = null; if (vendorShift != null) msgs = ((InternalEObject)vendorShift).eInverseRemove(this, PaymentMeteringPackage.VENDOR_SHIFT__RECEIPTS, VendorShift.class, msgs); if (newVendorShift != null) msgs = ((InternalEObject)newVendorShift).eInverseAdd(this, PaymentMeteringPackage.VENDOR_SHIFT__RECEIPTS, VendorShift.class, msgs); msgs = basicSetVendorShift(newVendorShift, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>Is Bankable</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Is Bankable</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Is Bankable</em>' attribute. * @see #isSetIsBankable() * @see #unsetIsBankable() * @see #setIsBankable(boolean) * @generated */ public boolean isIsBankable() { return isBankable; } /** * Sets the value of the '{@link CIM15.IEC61968.PaymentMetering.Receipt#isIsBankable <em>Is Bankable</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Is Bankable</em>' attribute. * @see #isSetIsBankable() * @see #unsetIsBankable() * @see #isIsBankable() * @generated */ public void setIsBankable(boolean newIsBankable) { isBankable = newIsBankable; isBankableESet = true; } /** * Unsets the value of the '{@link CIM15.IEC61968.PaymentMetering.Receipt#isIsBankable <em>Is Bankable</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetIsBankable() * @see #isIsBankable() * @see #setIsBankable(boolean) * @generated */ public void unsetIsBankable() { isBankable = IS_BANKABLE_EDEFAULT; isBankableESet = false; } /** * Returns whether the value of the '{@link CIM15.IEC61968.PaymentMetering.Receipt#isIsBankable <em>Is Bankable</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Is Bankable</em>' attribute is set. * @see #unsetIsBankable() * @see #isIsBankable() * @see #setIsBankable(boolean) * @generated */ public boolean isSetIsBankable() { return isBankableESet; } /** * Returns the value of the '<em><b>Line</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Line</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Line</em>' containment reference. * @see #setLine(LineDetail) * @generated */ public LineDetail getLine() { return line; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetLine(LineDetail newLine, NotificationChain msgs) { LineDetail oldLine = line; line = newLine; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61968.PaymentMetering.Receipt#getLine <em>Line</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Line</em>' containment reference. * @see #getLine() * @generated */ public void setLine(LineDetail newLine) { if (newLine != line) { NotificationChain msgs = null; if (line != null) msgs = ((InternalEObject)line).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - PaymentMeteringPackage.RECEIPT__LINE, null, msgs); if (newLine != null) msgs = ((InternalEObject)newLine).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - PaymentMeteringPackage.RECEIPT__LINE, null, msgs); msgs = basicSetLine(newLine, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>Cashier Shift</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61968.PaymentMetering.CashierShift#getReceipts <em>Receipts</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Cashier Shift</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Cashier Shift</em>' reference. * @see #setCashierShift(CashierShift) * @see CIM15.IEC61968.PaymentMetering.CashierShift#getReceipts * @generated */ public CashierShift getCashierShift() { if (cashierShift != null && cashierShift.eIsProxy()) { InternalEObject oldCashierShift = (InternalEObject)cashierShift; cashierShift = (CashierShift)eResolveProxy(oldCashierShift); if (cashierShift != oldCashierShift) { } } return cashierShift; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CashierShift basicGetCashierShift() { return cashierShift; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetCashierShift(CashierShift newCashierShift, NotificationChain msgs) { CashierShift oldCashierShift = cashierShift; cashierShift = newCashierShift; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61968.PaymentMetering.Receipt#getCashierShift <em>Cashier Shift</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Cashier Shift</em>' reference. * @see #getCashierShift() * @generated */ public void setCashierShift(CashierShift newCashierShift) { if (newCashierShift != cashierShift) { NotificationChain msgs = null; if (cashierShift != null) msgs = ((InternalEObject)cashierShift).eInverseRemove(this, PaymentMeteringPackage.CASHIER_SHIFT__RECEIPTS, CashierShift.class, msgs); if (newCashierShift != null) msgs = ((InternalEObject)newCashierShift).eInverseAdd(this, PaymentMeteringPackage.CASHIER_SHIFT__RECEIPTS, CashierShift.class, msgs); msgs = basicSetCashierShift(newCashierShift, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>Tenders</b></em>' reference list. * The list contents are of type {@link CIM15.IEC61968.PaymentMetering.Tender}. * It is bidirectional and its opposite is '{@link CIM15.IEC61968.PaymentMetering.Tender#getReceipt <em>Receipt</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Tenders</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Tenders</em>' reference list. * @see CIM15.IEC61968.PaymentMetering.Tender#getReceipt * @generated */ public EList<Tender> getTenders() { if (tenders == null) { tenders = new BasicInternalEList<Tender>(Tender.class); } return tenders; } /** * Returns the value of the '<em><b>Transactions</b></em>' reference list. * The list contents are of type {@link CIM15.IEC61968.PaymentMetering.Transaction}. * It is bidirectional and its opposite is '{@link CIM15.IEC61968.PaymentMetering.Transaction#getReceipt <em>Receipt</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Transactions</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Transactions</em>' reference list. * @see CIM15.IEC61968.PaymentMetering.Transaction#getReceipt * @generated */ public EList<Transaction> getTransactions() { if (transactions == null) { transactions = new BasicInternalEList<Transaction>(Transaction.class); } return transactions; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case PaymentMeteringPackage.RECEIPT__VENDOR_SHIFT: if (vendorShift != null) msgs = ((InternalEObject)vendorShift).eInverseRemove(this, PaymentMeteringPackage.VENDOR_SHIFT__RECEIPTS, VendorShift.class, msgs); return basicSetVendorShift((VendorShift)otherEnd, msgs); case PaymentMeteringPackage.RECEIPT__CASHIER_SHIFT: if (cashierShift != null) msgs = ((InternalEObject)cashierShift).eInverseRemove(this, PaymentMeteringPackage.CASHIER_SHIFT__RECEIPTS, CashierShift.class, msgs); return basicSetCashierShift((CashierShift)otherEnd, msgs); case PaymentMeteringPackage.RECEIPT__TENDERS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getTenders()).basicAdd(otherEnd, msgs); case PaymentMeteringPackage.RECEIPT__TRANSACTIONS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getTransactions()).basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case PaymentMeteringPackage.RECEIPT__VENDOR_SHIFT: return basicSetVendorShift(null, msgs); case PaymentMeteringPackage.RECEIPT__LINE: return basicSetLine(null, msgs); case PaymentMeteringPackage.RECEIPT__CASHIER_SHIFT: return basicSetCashierShift(null, msgs); case PaymentMeteringPackage.RECEIPT__TENDERS: return ((InternalEList<?>)getTenders()).basicRemove(otherEnd, msgs); case PaymentMeteringPackage.RECEIPT__TRANSACTIONS: return ((InternalEList<?>)getTransactions()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case PaymentMeteringPackage.RECEIPT__VENDOR_SHIFT: if (resolve) return getVendorShift(); return basicGetVendorShift(); case PaymentMeteringPackage.RECEIPT__IS_BANKABLE: return isIsBankable(); case PaymentMeteringPackage.RECEIPT__LINE: return getLine(); case PaymentMeteringPackage.RECEIPT__CASHIER_SHIFT: if (resolve) return getCashierShift(); return basicGetCashierShift(); case PaymentMeteringPackage.RECEIPT__TENDERS: return getTenders(); case PaymentMeteringPackage.RECEIPT__TRANSACTIONS: return getTransactions(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case PaymentMeteringPackage.RECEIPT__VENDOR_SHIFT: setVendorShift((VendorShift)newValue); return; case PaymentMeteringPackage.RECEIPT__IS_BANKABLE: setIsBankable((Boolean)newValue); return; case PaymentMeteringPackage.RECEIPT__LINE: setLine((LineDetail)newValue); return; case PaymentMeteringPackage.RECEIPT__CASHIER_SHIFT: setCashierShift((CashierShift)newValue); return; case PaymentMeteringPackage.RECEIPT__TENDERS: getTenders().clear(); getTenders().addAll((Collection<? extends Tender>)newValue); return; case PaymentMeteringPackage.RECEIPT__TRANSACTIONS: getTransactions().clear(); getTransactions().addAll((Collection<? extends Transaction>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case PaymentMeteringPackage.RECEIPT__VENDOR_SHIFT: setVendorShift((VendorShift)null); return; case PaymentMeteringPackage.RECEIPT__IS_BANKABLE: unsetIsBankable(); return; case PaymentMeteringPackage.RECEIPT__LINE: setLine((LineDetail)null); return; case PaymentMeteringPackage.RECEIPT__CASHIER_SHIFT: setCashierShift((CashierShift)null); return; case PaymentMeteringPackage.RECEIPT__TENDERS: getTenders().clear(); return; case PaymentMeteringPackage.RECEIPT__TRANSACTIONS: getTransactions().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case PaymentMeteringPackage.RECEIPT__VENDOR_SHIFT: return vendorShift != null; case PaymentMeteringPackage.RECEIPT__IS_BANKABLE: return isSetIsBankable(); case PaymentMeteringPackage.RECEIPT__LINE: return line != null; case PaymentMeteringPackage.RECEIPT__CASHIER_SHIFT: return cashierShift != null; case PaymentMeteringPackage.RECEIPT__TENDERS: return tenders != null && !tenders.isEmpty(); case PaymentMeteringPackage.RECEIPT__TRANSACTIONS: return transactions != null && !transactions.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (isBankable: "); if (isBankableESet) result.append(isBankable); else result.append("<unset>"); result.append(')'); return result.toString(); } } // Receipt
apache-2.0
basho/spark-riak-connector
connector/src/main/scala/com/basho/riak/spark/query/TSDataQueryingIterator.scala
3609
/** * Copyright (c) 2015-2016 Basho Technologies, Inc. * * This file is provided 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.basho.riak.spark.query import com.basho.riak.client.core.query.timeseries.Row import org.apache.spark.Logging import com.basho.riak.client.core.query.timeseries.ColumnDescription class TSDataQueryingIterator(query: QueryTS) extends Iterator[Row] with Logging { private var _iterator: Option[Iterator[Row]] = None private val subqueries = query.queryData.iterator private var columns: Option[Seq[ColumnDescription]] = None /** * @return result always corresponds to the latest data returned by next() if there were no subsequent call [[hasNext]] * or there is no outstanding data except following cases: * * - when [[next()]] and [[hasNext]] methods haven't been called yet, then data will be fetched implicitly * and corresponding ColumnDefs will be returned. * - when [[hasNext]] has been called and there is a next [[Row]], columnDefs for the next [[Row]] will be returned then, */ def columnDefs: Seq[ColumnDescription] = { if (_iterator.isEmpty && columns.isEmpty) { /** * if it is a newly created data iterator it has no outstanding data from the previous fetch(prefetch) * and it is safe to do a prefetch and use column defs returned by it */ prefetch() } columns match { case None => Seq() case Some(cds) => cds } } protected[this] def prefetch() = { while( subqueries.hasNext && !isPrefetchedDataAvailable) { val nextSubQuery = subqueries.next logTrace(s"Prefetching chunk of data: ts-query(token=$nextSubQuery)") val r = query.nextChunk(nextSubQuery) r match { case (cds, rows) => if (isTraceEnabled()) { logTrace(s"ts-query($nextSubQuery) returns:\n columns: ${r._1}\n data:\n\t ${r._2}") } else { logDebug(s"ts-query($nextSubQuery) returns:\n data.size: ${r._2.size}") } if (cds != null && cds.nonEmpty) { columns = Some(cds) } else if (columns.isEmpty) { // We have to initialize columns here, to make a difference and use it as indikator columns = Some(Seq()) } _iterator = Some(rows.iterator) case _ => _iterator = None logWarning(s"ts-query(token=$nextSubQuery) returns: NOTHING") } } } private def isPrefetchedDataAvailable: Boolean = !(_iterator.isEmpty || (_iterator.isDefined && !_iterator.get.hasNext)) override def hasNext: Boolean = { if (!isPrefetchedDataAvailable) { prefetch() } _iterator match { case Some(it) => it.hasNext case None => false } } override def next(): Row = { if (!hasNext) { throw new NoSuchElementException("next on empty iterator") } _iterator.get.next } } object TSDataQueryingIterator { def apply[R](query: QueryTS): TSDataQueryingIterator = new TSDataQueryingIterator(query) }
apache-2.0
ViDA-NYU/ache
ache/src/main/java/achecrawler/link/BipartiteGraphRepository.java
16839
package achecrawler.link; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import achecrawler.link.frontier.Visitor; import achecrawler.util.parser.BackLinkNeighborhood; import achecrawler.util.parser.LinkNeighborhood; import achecrawler.util.persistence.PersistentHashtable; import achecrawler.util.persistence.PersistentHashtable.DB; import achecrawler.util.persistence.Tuple; public class BipartiteGraphRepository { private static final Logger logger = LoggerFactory.getLogger(BipartiteGraphRepository.class); private final int pagesToCommit = 100; private int uncommittedCount = 0; private PersistentHashtable<String> url2id; private PersistentHashtable<String> authID; private PersistentHashtable<String> authGraph; private PersistentHashtable<String> hubGraph; private PersistentHashtable<String> hubID; private final String separator = "###"; private String urlIdDirectory = "data_backlinks/url"; private String authIdDirectory = "data_backlinks/auth_id"; private String authGraphDirectory = "data_backlinks/auth_graph"; private String hubIdDirectory = "data_backlinks/hub_id"; private String hubGraphDirectory = "data_backlinks/hub_graph"; public BipartiteGraphRepository(String dataPath, DB persistentHashTableBackend) { int cacheSize = 10000; this.url2id = new PersistentHashtable<>(dataPath + "/" + urlIdDirectory, cacheSize, String.class, persistentHashTableBackend); this.authID = new PersistentHashtable<>(dataPath + "/" + authIdDirectory, cacheSize, String.class, persistentHashTableBackend); this.authGraph = new PersistentHashtable<>(dataPath + "/" + authGraphDirectory, cacheSize, String.class, persistentHashTableBackend); this.hubID = new PersistentHashtable<>(dataPath + "/" + hubIdDirectory, cacheSize, String.class, persistentHashTableBackend); this.hubGraph = new PersistentHashtable<>(dataPath + "/" + hubGraphDirectory, cacheSize, String.class, persistentHashTableBackend); } public Tuple<String>[] getAuthGraph() throws Exception { return authGraph.getTableAsArray(); } public Tuple<String>[] getHubGraph() throws Exception { return hubGraph.getTableAsArray(); } public String getID(String url) { return url2id.get(url); } public String getHubURL(String id) throws IOException { String url = hubID.get(id); if (url != null) { String[] fields = url.split(":::"); url = fields[0]; } return url; } public String getAuthURL(String id) { String url = authID.get(id); if (url != null) { String[] fields = url.split(":::"); url = fields[0]; } return url; } public String[] getOutlinks(String id) { String links = hubGraph.get(id); if (links != null) { return links.split("###"); } else { return null; } } public String[] getBacklinks(String id) { String links = authGraph.get(id); if (links != null) { return links.split("###"); } else { return null; } } /** * DEPRECATED: may cause OutOfMemoryError on large crawls. * * @return */ @Deprecated public LinkNeighborhood[] getLNs() throws Exception { Tuple<String>[] tuples = authID.getTableAsArray(); LinkNeighborhood[] lns = new LinkNeighborhood[tuples.length]; for (int i = 0; i < lns.length; i++) { String strln = tuples[i].getValue(); if (strln != null) { lns[i] = parseString(strln); } } return lns; } public void visitLNs(Visitor<LinkNeighborhood> visitor) throws Exception { authID.visitTuples((Tuple<String> tuple) -> { String strln = tuple.getValue(); try { visitor.visit(parseString(strln)); } catch (MalformedURLException e) { logger.warn("Failed to parse URL: " + strln); } }); } /** * DEPRECATED: may cause OutOfMemoryError on large crawls. * * @return */ @Deprecated public LinkNeighborhood[] getBacklinkLN() throws Exception { Tuple<String>[] tuples = hubID.getTableAsArray(); LinkNeighborhood[] lns = new LinkNeighborhood[tuples.length]; for (int i = 0; i < lns.length; i++) { String strln = tuples[i].getValue(); if (strln != null) { String[] fields = strln.split(":::"); lns[i] = new LinkNeighborhood(new URL(fields[0])); if (fields.length > 1) { String title = fields[1]; if (title != null) { StringTokenizer tokenizer = new StringTokenizer(title, " "); List<String> anchorTemp = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { anchorTemp.add(tokenizer.nextToken()); } String[] aroundArray = new String[anchorTemp.size()]; anchorTemp.toArray(aroundArray); lns[i].setAround(aroundArray); } } } } return lns; } public LinkNeighborhood getBacklinkLN(URL url) throws MalformedURLException { LinkNeighborhood ln = null; String urlId = url2id.get(url.toString()); if (urlId != null) { String strln = hubID.get(urlId); if (strln != null) { String[] fields = strln.split(":::"); ln = new LinkNeighborhood(new URL(fields[0])); if (fields.length > 1) { String title = fields[1]; if (title != null) { StringTokenizer tokenizer = new StringTokenizer(title, " "); List<String> anchorTemp = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { anchorTemp.add(tokenizer.nextToken()); } String[] aroundArray = new String[anchorTemp.size()]; anchorTemp.toArray(aroundArray); ln.setAround(aroundArray); } } } } return ln; } public LinkNeighborhood getLN(URL url) throws MalformedURLException { LinkNeighborhood ln = null; String urlId = url2id.get(url.toString()); if (urlId != null) { String strln = authID.get(urlId); ln = parseString(strln); } return ln; } public LinkNeighborhood[] getOutlinks(URL url) throws IOException { String urlId = url2id.get(url.toString()); if (urlId == null) { return null; } else { String[] linkIds = hubGraph.get(urlId).split("###"); LinkNeighborhood[] lns = new LinkNeighborhood[linkIds.length]; for (int i = 0; i < lns.length; i++) { String strln = authID.get(linkIds[i]); if (strln != null) { String[] fields = strln.split(":::"); LinkNeighborhood ln = new LinkNeighborhood(new URL(fields[0])); lns[i] = ln; if (fields.length > 1) { ln.setAnchor(fields[1].split(" ")); if (fields.length > 2) { ln.setAround(fields[2].split(" ")); } } } } return lns; } } /** * This method retrieves the the backlinks of a given url. * * @param url * @return * @throws IOException */ public BackLinkNeighborhood[] getBacklinks(URL url) throws IOException { URL normalizedURL = new URL(url.getProtocol(), url.getHost(), "/"); String urlId = url2id.get(normalizedURL.toString()); if (urlId == null) { return null; } String strLinks = authGraph.get(urlId); if (strLinks == null) { return null; } else { List<BackLinkNeighborhood> tempBacklinks = new ArrayList<BackLinkNeighborhood>(); String[] backlinkIds = strLinks.split("###"); for (int i = 0; i < backlinkIds.length; i++) { String url_title = hubID.get(backlinkIds[i]); if (url_title != null) { BackLinkNeighborhood bln = new BackLinkNeighborhood(); String[] fields = url_title.split(":::"); bln.setLink(fields[0]); if (fields.length > 1) { bln.setTitle(fields[1]); } tempBacklinks.add(bln); } } BackLinkNeighborhood[] blns = new BackLinkNeighborhood[tempBacklinks.size()]; tempBacklinks.toArray(blns); return blns; } } public LinkNeighborhood[] getBacklinksLN(URL url) throws IOException { String urlId = url2id.get(url.toString()); if (urlId == null) { return null; } String strLinks = authGraph.get(urlId); if (strLinks == null) { return null; } else { List<LinkNeighborhood> tempLNs = new ArrayList<LinkNeighborhood>(); String[] linkIds = strLinks.split("###"); for (int i = 0; i < linkIds.length; i++) { String lnStr = authID.get(linkIds[i]); LinkNeighborhood ln = parseString(lnStr); if (ln != null) { tempLNs.add(ln); } } LinkNeighborhood[] lns = new LinkNeighborhood[tempLNs.size()]; tempLNs.toArray(lns); return lns; } } /** * Insert outlinks from hubs * * @param page */ public synchronized void insertOutlinks(URL url, LinkNeighborhood[] lns) { String urlId = getId(url.toString()); String strCurrentLinks = hubGraph.get(urlId); HashSet<String> currentLinks = parseRecordForwardLink(strCurrentLinks); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < lns.length; i++) { if (lns[i] != null) { String lnURL = lns[i].getLink().toString(); String id = getId(lnURL); if (!currentLinks.contains(id)) { String ln = authID.get(id); if (ln == null) { authID.put(id, lnURL + ":::" + lns[i].getAnchorString() + ":::" + lns[i].getAroundString()); } buffer.append(id); buffer.append(separator); currentLinks.add(id); } String strLinks = authGraph.get(id); HashSet<String> tempCurrentLinks = parseRecordBacklink(strLinks); if (!tempCurrentLinks.contains(urlId)) { if (tempCurrentLinks.size() == 0) { strLinks = urlId + separator; } else { strLinks = strLinks + urlId + separator; } String url_string = hubID.get(id); if (url_string == null) { hubID.put(id, lnURL + ":::"); } authGraph.put(id, strLinks); } } } if (strCurrentLinks == null) { strCurrentLinks = buffer.toString(); } else { strCurrentLinks = strCurrentLinks + buffer.toString(); } if (!strCurrentLinks.equals("")) { hubGraph.put(urlId, strCurrentLinks); } uncommittedCount++; if (uncommittedCount == pagesToCommit) { this.commit(); uncommittedCount = 0; } } /** * Insert backlinks from authorities * * @param page * @throws IOException */ public synchronized void insertBacklinks(URL url, BackLinkNeighborhood[] links) throws IOException { String urlId = getId(url.toString()); String strCurrentLinks = authGraph.get(urlId); HashSet<String> currentLinks = parseRecordBacklink(strCurrentLinks); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < links.length; i++) { String id = getId(links[i].getLink()); if (!currentLinks.contains(id)) { String url_string = hubID.get(id); if (url_string == null) { hubID.put(id, links[i].getLink() + ":::" + links[i].getTitle()); } buffer.append(id); buffer.append(separator); currentLinks.add(id); } String strLinks = hubGraph.get(id); HashSet<String> tempCurrentLinks = parseRecordForwardLink(strLinks); if (!tempCurrentLinks.contains(urlId)) { if (tempCurrentLinks.size() == 0) { strLinks = urlId + separator; } else { strLinks = strLinks + urlId + separator; } hubGraph.put(id, strLinks); } } if (strCurrentLinks == null) { strCurrentLinks = buffer.toString(); } else { strCurrentLinks = strCurrentLinks + buffer.toString(); } authGraph.put(urlId, strCurrentLinks); uncommittedCount++; if (uncommittedCount == pagesToCommit) { this.commit(); uncommittedCount = 0; } } private String getId(String url) { String id = url2id.get(url); if (id == null) { String maxId = url2id.get("MAX"); if (maxId == null) { maxId = "0"; } int newId = Integer.parseInt(maxId) + 1; id = newId + ""; url2id.put(url, id); url2id.put("MAX", id); } return id; } public synchronized void commit() { url2id.commit(); authGraph.commit(); authID.commit(); hubID.commit(); hubGraph.commit(); } public void close() { this.commit(); url2id.close(); authGraph.close(); authID.close(); hubID.close(); hubGraph.close(); } private HashSet<String> parseRecordBacklink(String strLinks) { HashSet<String> currentLinks = new HashSet<String>(); if (strLinks != null) { String[] links = strLinks.split("###"); for (int i = 0; i < links.length; i++) { currentLinks.add(links[i]); } } return currentLinks; } private HashSet<String> parseRecordForwardLink(String strLinks) { HashSet<String> currentLinks = new HashSet<String>(); if (strLinks != null) { String[] linkIds = strLinks.split("###"); for (int i = 0; i < linkIds.length; i++) { currentLinks.add(linkIds[i]); } } return currentLinks; } private LinkNeighborhood parseString(String lnStr) throws MalformedURLException { LinkNeighborhood ln = null; if (lnStr != null) { String[] fields = lnStr.split(":::"); ln = new LinkNeighborhood(new URL(fields[0])); if (fields.length > 1) { ln.setAnchor(fields[1].split(" ")); if (fields.length > 2) { ln.setAround(fields[2].split(" ")); } } } return ln; } }
apache-2.0
bskierys/Pine
pine/src/main/java/com/github/bskierys/pine/LogAction.java
278
package com.github.bskierys.pine; /** * Interface to make a additional action on output log message. */ public interface LogAction { /** * Invoked the same way as {@link Pine#log} is. */ void action(int priority, String tag, String message, Throwable t); }
apache-2.0
reshaping-the-future/better-together-api
api/src/main/java/ac/robinson/bettertogether/api/messaging/BroadcastMessage.java
4570
/* * Copyright (C) 2017 The Better Together Toolkit * * 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 ac.robinson.bettertogether.api.messaging; import android.util.Base64; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import androidx.annotation.Nullable; /** * BroadcastMessages are the objects sent between connected devices. To send a message, create an instance of this class, then * use the send and receive methods of plugin activity or fragment classes to handle message events. */ @SuppressWarnings({ "WeakerAccess", "unused" }) public class BroadcastMessage implements Serializable { public static final int TYPE_DEFAULT = 0; public static final int TYPE_ERROR = -1; private final static long serialVersionUID = 1; public static final Charset CHARSET = Charset.forName("UTF-8"); private final int mType; private final String mMessage; private int mIntExtra; private String mFrom; private boolean mIsSystemMessage; /** * A single message to be sent. * * @param type The type of message - a utility field to help with differentiating between different commands in your * plugin. For very simple plugins, it may be sufficient to just use {@link #TYPE_DEFAULT} and/or * {@link #TYPE_ERROR}. Use {@link #getType()} to retrieve this value when receiving a message. * @param message The content of the message itself. Use {@link #getMessage()} to retrieve this value when receiving a * message. */ public BroadcastMessage(int type, @Nullable String message) { mType = type; mMessage = message; } /** * Get the type of this BroadcastMessage, set when creating this object. * * @return The type of this message. */ public int getType() { return mType; } /** * Get the message content of this BroadcastMessage. * * @return The message (may be null). */ @Nullable public String getMessage() { return mMessage; } /** * Optionally, a BroadcastMessage may have an integer value as an extra to the message. * * @return The value of the extra, or 0 if not set. */ public int getIntExtra() { return mIntExtra; } /** * Set the optional integer extra value for this message. * * @param extra The value to set. */ public void setIntExtra(int extra) { mIntExtra = extra; } public String getFrom() { return mFrom; } public void setFrom(String from) { mFrom = from; } public void setSystemMessage() { mIsSystemMessage = true; } public boolean isSystemMessage() { return mIsSystemMessage; } public static BroadcastMessage fromString(String message) throws IOException, ClassNotFoundException { byte[] data = Base64.decode(message, Base64.DEFAULT); ObjectInputStream objectInputStream = new ObjectInputStream(new GZIPInputStream(new ByteArrayInputStream(data))); Object object = objectInputStream.readObject(); objectInputStream.close(); return (BroadcastMessage) object; } public static String toString(BroadcastMessage message) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(new GZIPOutputStream(byteArrayOutputStream)); objectOutputStream.writeObject(message); objectOutputStream.close(); return new String(Base64.encode(byteArrayOutputStream.toByteArray(), Base64.DEFAULT), BroadcastMessage.CHARSET); } public static List<String> splitEqually(String message, int size) { List<String> result = new ArrayList<>((message.length() + size - 1) / size); for (int start = 0, length = message.length(); start < length; start += size) { result.add(message.substring(start, Math.min(length, start + size))); } return result; } }
apache-2.0
ChattyCrow/chattycrow_ruby
test/contacts_test.rb
2634
require File.expand_path '../helper', __FILE__ # Unit test for contact methods class ContactsTest < MiniTest::Should::TestCase should 'Raise invalid argument when no contact list is present' do expect { ChattyCrow.add_contacts }.to_raise ArgumentError expect { ChattyCrow.remove_contacts }.to_raise ArgumentError expect { ChattyCrow.add_contacts(test_option: 'option') }.to_raise ArgumentError expect { ChattyCrow.remove_contacts(test_option: 'option') }.to_raise ArgumentError end should 'Return contact add list' do # Prepare response request = { status: 'OK', msg: 'Status message', stats: { success: 15, exists: 28, failed: 12 }, contacts: { exists: %w(franta1 franta5), failed: %w(franta2 franta3) } } # Fake URL contacts mock_contacts method: :post, body: request.to_json # Get contacts response = ChattyCrow.add_contacts('test1', 'test2') # Validate expect(response).to_be_kind_of ChattyCrow::Response::ContactsAdd expect(response.status).to_equal request[:status] expect(response.msg).to_equal request[:msg] # Statistics expect(response.success_count).to_equal request[:stats][:success] expect(response.exists_count).to_equal request[:stats][:exists] expect(response.failed_count).to_equal request[:stats][:failed] # Failed & Exists contacts expect(response.exists).to_include 'franta1' expect(response.exists).to_include 'franta5' expect(response.failed).to_include 'franta2' expect(response.failed).to_include 'franta3' # Remove mock clear_mock_url end should 'Return contact remove list' do # Prepare response request = { status: 'OK', msg: 'Status message', stats: { success: 15, failed: 12 }, contacts: { failed: %w(franta2 franta3) } } # Fake URL contacts mock_contacts method: :delete, status: %w(201 Created), body: request.to_json # Get contacts response = ChattyCrow.remove_contacts('test12', 'test15') # Validate expect(response).to_be_kind_of ChattyCrow::Response::ContactsRemove expect(response.status).to_equal request[:status] expect(response.msg).to_equal request[:msg] # Statistics expect(response.success_count).to_equal request[:stats][:success] expect(response.failed_count).to_equal request[:stats][:failed] # Failed & Exists contacts expect(response.failed).to_include 'franta2' expect(response.failed).to_include 'franta3' # Remove mock clear_mock_url end end
apache-2.0
mirkosertic/Bytecoder
core/src/main/java/de/mirkosertic/bytecoder/ssa/TypeRef.java
9117
/* * Copyright 2017 Mirko Sertic * * 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.mirkosertic.bytecoder.ssa; import de.mirkosertic.bytecoder.core.BytecodeArrayTypeRef; import de.mirkosertic.bytecoder.core.BytecodeObjectTypeRef; import de.mirkosertic.bytecoder.core.BytecodePrimitiveTypeRef; import de.mirkosertic.bytecoder.core.BytecodeTypeRef; public interface TypeRef { interface ArrayTypeRef extends TypeRef { BytecodeArrayTypeRef arrayType(); } interface ObjectTypeRef extends TypeRef { BytecodeObjectTypeRef objectType(); } Native resolve(); boolean isArray(); boolean isObject(); @Override String toString(); enum Native implements TypeRef { BYTE { @Override public Native eventuallyPromoteTo(final Native aOtherType) { switch (aOtherType) { case BYTE: return BYTE; case INT: return INT; default: throw new IllegalStateException("Don't know how to promote " + this + " to " + aOtherType); } } } ,SHORT { @Override public Native eventuallyPromoteTo(final Native aOtherType) { switch (aOtherType) { case SHORT: return SHORT; case INT: return INT; default: throw new IllegalStateException("Don't know how to promote " + this + " to " + aOtherType); } } },CHAR { @Override public Native eventuallyPromoteTo(final Native aOtherType) { switch (aOtherType) { case CHAR: return CHAR; case INT: return INT; default: throw new IllegalStateException("Don't know how to promote " + this + " to " + aOtherType); } } },BOOLEAN { @Override public Native eventuallyPromoteTo(final Native aOtherType) { switch (aOtherType) { case INT: return INT; case BOOLEAN: return BOOLEAN; default: throw new IllegalStateException("Don't know how to promote " + this + " to " + aOtherType); } } },INT { @Override public Native eventuallyPromoteTo(final Native aOtherType) { switch (aOtherType) { case INT: return INT; case BOOLEAN: return INT; case BYTE: return INT; case CHAR: return INT; case REFERENCE: return INT; case SHORT: return INT; case LONG: return LONG; default: throw new IllegalStateException("Don't know how to promote " + this + " to " + aOtherType); } } },LONG { @Override public Native eventuallyPromoteTo(final Native aOtherType) { switch (aOtherType) { case LONG: return LONG; default: throw new IllegalStateException("Don't know how to promote " + this + " to " + aOtherType); } } @Override public boolean isCategory2() { return true; } },FLOAT { @Override public Native eventuallyPromoteTo(final Native aOtherType) { switch (aOtherType) { case FLOAT: return FLOAT; default: throw new IllegalStateException("Don't know how to promote " + this + " to " + aOtherType); } } },DOUBLE { @Override public Native eventuallyPromoteTo(final Native aOtherType) { switch (aOtherType) { case DOUBLE: return DOUBLE; default: throw new IllegalStateException("Don't know how to promote " + this + " to " + aOtherType); } } @Override public boolean isCategory2() { return true; } },REFERENCE { @Override public Native eventuallyPromoteTo(final Native aOtherType) { switch (aOtherType) { case REFERENCE: return REFERENCE; default: throw new IllegalStateException("Don't know how to promote " + this + " to " + aOtherType); } } @Override public boolean isObject() { return true; } },VOID { @Override public Native eventuallyPromoteTo(final Native aOtherType) { switch (aOtherType) { case VOID: return VOID; default: throw new IllegalStateException("Don't know how to promote " + this + " to " + aOtherType); } } }; @Override public Native resolve() { return this; } @Override public boolean isArray() { return false; } @Override public boolean isObject() { return false; } public boolean isCategory2() { return false; } public abstract Native eventuallyPromoteTo(Native aOtherType); } static TypeRef toType(final BytecodeTypeRef aTypeRef) { if (aTypeRef.isVoid()) { return Native.VOID; } if (aTypeRef.isArray()) { return new ArrayTypeRef() { @Override public BytecodeArrayTypeRef arrayType() { return (BytecodeArrayTypeRef) aTypeRef; } @Override public boolean isArray() { return true; } @Override public Native resolve() { return Native.REFERENCE; } @Override public boolean isObject() { return true; } @Override public String toString() { return "array of " + arrayType().singleElementType(); } }; } if (aTypeRef.isPrimitive()) { final BytecodePrimitiveTypeRef thePrimitive = (BytecodePrimitiveTypeRef) aTypeRef; switch (thePrimitive) { case INT: return Native.INT; case LONG: return Native.LONG; case FLOAT: return Native.FLOAT; case DOUBLE: return Native.DOUBLE; case BYTE: return Native.BYTE; case VOID: return Native.VOID; case CHAR: return Native.CHAR; case SHORT: return Native.SHORT; case BOOLEAN: return Native.BOOLEAN; default: throw new IllegalStateException("Not supported : " + aTypeRef); } } return new ObjectTypeRef() { @Override public BytecodeObjectTypeRef objectType() { return (BytecodeObjectTypeRef) aTypeRef; } @Override public Native resolve() { return Native.REFERENCE; } @Override public boolean isArray() { return false; } @Override public boolean isObject() { return true; } @Override public String toString() { return "object of type " + aTypeRef.name(); } }; } }
apache-2.0
o-filippov/programming-for-testers
addressbook-selenium-tests/src/com/example/tests/ContactRemovalTests.java
760
package com.example.tests; import static org.testng.Assert.assertEquals; import java.util.List; import java.util.Random; import org.testng.annotations.Test; public class ContactRemovalTests extends TestBase { @Test public void deleteSomeContact() { app.navigateTo().mainPage(); // save state List<ContactData> oldList = app.getContactHelper().getContacts(); // actions Random rnd = new Random(); int index = rnd.nextInt(oldList.size()-1); // number of the contact to be removed app.getContactHelper().deleteContact(index); // save new state List<ContactData> newList = app.getContactHelper().getContacts(); // compare states oldList.remove(index); assertEquals(newList, oldList); } }
apache-2.0
wanlitao/IDCard
src/Reader/IDCard.Reader.Standard/StandardIDCardReader.cs
4472
using System; namespace IDCard.Reader.Standard { /// <summary> /// 身份证阅读(公安部一所) /// </summary> public class StandardIDCardReader : IDCardReader { protected const string DefaultBmpPhotoFileName = "zp.bmp"; private int? _port; #region 构造函数 public StandardIDCardReader() { } public StandardIDCardReader(int port) { if (port < 1 || port > 9999) throw new ArgumentOutOfRangeException(nameof(port), "port must between 1 and 9999"); _port = port; } #endregion #region Helper Functions /// <summary> /// 获取交互处理程序 /// </summary> /// <returns></returns> private IIDCardInteropHandler GetInteropHandler() { return _port.HasValue ? new StandardIDCardInteropHandler(_port.Value) : new StandardIDCardInteropHandler(); } /// <summary> /// 获取阅读交互处理程序 /// </summary> /// <returns></returns> private IIDCardInteropReadHandler GetInteropReadHandler() { return _port.HasValue ? new StandardIDCardInteropReadHandler(_port.Value) : new StandardIDCardInteropReadHandler(); } #endregion #region 读文字和相片信息 /// <summary> /// 读文字和相片信息 /// </summary> /// <param name="fileDirectory">文件输出目录</param> /// <returns></returns> protected override IDCardActionResult ReadBaseTextPhotoInfoInternal(string fileDirectory) { using (var interopHandler = GetInteropReadHandler()) { return interopHandler.ExecIDCardInteropReadAction( (port) => StandardIDCardInteropAction.ReadContentPath(fileDirectory, (int)StandardIDCardReadActiveType.TextAndWlt)); } } #endregion #region 读最新地址信息 /// <summary> /// 读最新地址信息 /// </summary> /// <param name="fileDirectory">文件输出目录</param> /// <returns></returns> protected override IDCardActionResult ReadNewAddressInfoInternal(string fileDirectory) { using (var interopHandler = GetInteropReadHandler()) { return interopHandler.ExecIDCardInteropReadAction( (port) => StandardIDCardInteropAction.ReadContentPath(fileDirectory, (int)StandardIDCardReadActiveType.NewAddress)); } } #endregion #region 内容解析 /// <summary> /// 解析文字信息 /// </summary> /// <param name="fileDirectory">文字信息所属目录</param> /// <returns></returns> protected override IDCardInfo ParseTextInfoInternal(string fileDirectory) { return ParseTextInfoInternal(fileDirectory, DefaultTextFileName); } /// <summary> /// 解析照片信息 /// </summary> /// <param name="fileDirectory">照片信息所属目录</param> /// <returns>BMP照片路径</returns> protected override IDCardActionResult ParsePhotoInfoInternal(string fileDirectory) { var photoFilePath = IOHelper.GetFilePath(fileDirectory, DefaultPhotoFileName); var interopHandler = GetInteropHandler(); return interopHandler.ExecIDCardInteropAction((port) => StandardIDCardInteropAction.GetPhoto(photoFilePath)); } /// <summary> /// 解析最新地址信息 /// </summary> /// <param name="fileDirectory">最新地址信息所属目录</param> /// <returns></returns> protected override string ParseNewAddressInfoInternal(string fileDirectory) { return ParseNewAddressInfoInternal(fileDirectory, DefaultNewAddressFileName); } #endregion #region 获取照片路径 /// <summary> /// 获取Bmp照片路径 /// </summary> /// <param name="fileDirectory">照片信息所属目录</param> /// <returns></returns> protected override string GetBmpPhotoPathInternal(string fileDirectory) { return IOHelper.GetFilePath(fileDirectory, DefaultBmpPhotoFileName); } #endregion } }
apache-2.0
mrniko/redisson
redisson/src/main/java/org/redisson/api/RRateLimiterAsync.java
6307
/** * Copyright (c) 2013-2020 Nikita Koksharov * * 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.redisson.api; import java.util.concurrent.TimeUnit; /** * Asynchronous interface for Redis based Rate Limiter object. * * @author Nikita Koksharov * */ public interface RRateLimiterAsync extends RExpirableAsync { /** * Initializes RateLimiter's state and stores config to Redis server. * * @param mode - rate mode * @param rate - rate * @param rateInterval - rate time interval * @param rateIntervalUnit - rate time interval unit * @return {@code true} if rate was set and {@code false} * otherwise */ RFuture<Boolean> trySetRateAsync(RateType mode, long rate, long rateInterval, RateIntervalUnit rateIntervalUnit); /** * Acquires a permit only if one is available at the * time of invocation. * * <p>Acquires a permit, if one is available and returns immediately, * with the value {@code true}, * reducing the number of available permits by one. * * <p>If no permit is available then this method will return * immediately with the value {@code false}. * * @return {@code true} if a permit was acquired and {@code false} * otherwise */ RFuture<Boolean> tryAcquireAsync(); /** * Acquires the given number of <code>permits</code> only if all are available at the * time of invocation. * * <p>Acquires a permits, if all are available and returns immediately, * with the value {@code true}, * reducing the number of available permits by given number of permits. * * <p>If no permits are available then this method will return * immediately with the value {@code false}. * * @param permits the number of permits to acquire * @return {@code true} if a permit was acquired and {@code false} * otherwise */ RFuture<Boolean> tryAcquireAsync(long permits); /** * Acquires a permit from this RateLimiter, blocking until one is available. * * <p>Acquires a permit, if one is available and returns immediately, * reducing the number of available permits by one. * * @return void */ RFuture<Void> acquireAsync(); /** * Acquires a specified <code>permits</code> from this RateLimiter, * blocking until one is available. * * <p>Acquires the given number of permits, if they are available * and returns immediately, reducing the number of available permits * by the given amount. * * @param permits the number of permits to acquire * @return void */ RFuture<Void> acquireAsync(long permits); /** * Acquires a permit from this RateLimiter, if one becomes available * within the given waiting time. * * <p>Acquires a permit, if one is available and returns immediately, * with the value {@code true}, * reducing the number of available permits by one. * * <p>If no permit is available then the current thread becomes * disabled for thread scheduling purposes and lies dormant until * specified waiting time elapses. * * <p>If a permit is acquired then the value {@code true} is returned. * * <p>If the specified waiting time elapses then the value {@code false} * is returned. If the time is less than or equal to zero, the method * will not wait at all. * * @param timeout the maximum time to wait for a permit * @param unit the time unit of the {@code timeout} argument * @return {@code true} if a permit was acquired and {@code false} * if the waiting time elapsed before a permit was acquired */ RFuture<Boolean> tryAcquireAsync(long timeout, TimeUnit unit); /** * Acquires the given number of <code>permits</code> only if all are available * within the given waiting time. * * <p>Acquires the given number of permits, if all are available and returns immediately, * with the value {@code true}, reducing the number of available permits by one. * * <p>If no permit is available then the current thread becomes * disabled for thread scheduling purposes and lies dormant until * the specified waiting time elapses. * * <p>If a permits is acquired then the value {@code true} is returned. * * <p>If the specified waiting time elapses then the value {@code false} * is returned. If the time is less than or equal to zero, the method * will not wait at all. * * @param permits amount * @param timeout the maximum time to wait for a permit * @param unit the time unit of the {@code timeout} argument * @return {@code true} if a permit was acquired and {@code false} * if the waiting time elapsed before a permit was acquired */ RFuture<Boolean> tryAcquireAsync(long permits, long timeout, TimeUnit unit); /** * Updates RateLimiter's state and stores config to Redis server. * * * @param mode - rate mode * @param rate - rate * @param rateInterval - rate time interval * @param rateIntervalUnit - rate time interval unit * @return {@code true} if rate was set and {@code false} * otherwise */ RFuture<Void> setRateAsync(RateType mode, long rate, long rateInterval, RateIntervalUnit rateIntervalUnit); /** * Returns current configuration of this RateLimiter object. * * @return config object */ RFuture<RateLimiterConfig> getConfigAsync(); /** * Returns amount of available permits. * * @return number of permits */ RFuture<Long> availablePermitsAsync(); }
apache-2.0
goodwinnk/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/documentation/AbstractExternalFilter.java
16550
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.documentation; import com.intellij.ide.BrowserUtil; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtilRt; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.psi.PsiElement; import com.intellij.util.io.HttpRequests; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.net.URL; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class AbstractExternalFilter { private static final Logger LOG = Logger.getInstance(AbstractExternalFilter.class); private static final Pattern ourClassDataStartPattern = Pattern.compile("START OF CLASS DATA", Pattern.CASE_INSENSITIVE); private static final Pattern ourClassDataEndPattern = Pattern.compile("SUMMARY ========", Pattern.CASE_INSENSITIVE); private static final Pattern ourNonClassDataEndPattern = Pattern.compile("<A (NAME|ID)=", Pattern.CASE_INSENSITIVE); @NonNls protected static final Pattern ourAnchorSuffix = Pattern.compile("#(.*)$"); protected static @NonNls final Pattern ourHtmlFileSuffix = Pattern.compile("/([^/]*[.][hH][tT][mM][lL]?)$"); private static @NonNls final Pattern ourAnnihilator = Pattern.compile("/[^/^.]*/[.][.]/"); private static @NonNls final String JAR_PROTOCOL = "jar:"; @NonNls private static final String HR = "<HR>"; @NonNls private static final String P = "<P>"; @NonNls private static final String DL = "<DL>"; @NonNls protected static final String H2 = "</H2>"; @NonNls protected static final String HTML_CLOSE = "</HTML>"; @NonNls protected static final String HTML = "<HTML>"; @NonNls private static final String BR = "<BR>"; @NonNls private static final String DT = "<DT>"; private static final Pattern CHARSET_META_PATTERN = Pattern.compile("<meta[^>]+\\s*charset=\"?([\\w\\-]*)\\s*\">", Pattern.CASE_INSENSITIVE); private static final String FIELD_SUMMARY = "<!-- =========== FIELD SUMMARY =========== -->"; private static final String CLASS_SUMMARY = "<div class=\"summary\">"; @NonNls private static final String GREATEST_END_SECTION = "<!-- ========= END OF CLASS DATA ========= -->"; protected static abstract class RefConvertor { @NotNull private final Pattern mySelector; public RefConvertor(@NotNull Pattern selector) { mySelector = selector; } protected abstract String convertReference(String root, String href); public CharSequence refFilter(final String root, @NotNull CharSequence read) { CharSequence toMatch = StringUtilRt.toUpperCase(read); StringBuilder ready = new StringBuilder(); int prev = 0; Matcher matcher = mySelector.matcher(toMatch); while (matcher.find()) { CharSequence before = read.subSequence(prev, matcher.start(1) - 1); // Before reference final CharSequence href = read.subSequence(matcher.start(1), matcher.end(1)); // The URL prev = matcher.end(1) + 1; ready.append(before); ready.append("\""); ready.append(ReadAction.compute(() -> convertReference(root, href.toString()))); ready.append("\""); } ready.append(read, prev, read.length()); return ready; } } protected static String doAnnihilate(String path) { int len = path.length(); do { path = ourAnnihilator.matcher(path).replaceAll("/"); } while (len > (len = path.length())); return path; } public CharSequence correctRefs(String root, CharSequence read) { CharSequence result = read; for (RefConvertor myReferenceConvertor : getRefConverters()) { result = myReferenceConvertor.refFilter(root, result); } return result; } protected abstract RefConvertor[] getRefConverters(); @Nullable @SuppressWarnings({"HardCodedStringLiteral"}) public String getExternalDocInfo(final String url) throws Exception { Application app = ApplicationManager.getApplication(); if (!app.isUnitTestMode() && app.isDispatchThread() || app.isWriteAccessAllowed()) { LOG.error("May block indefinitely: shouldn't be called from EDT or under write lock"); return null; } if (url == null || !MyJavadocFetcher.ourFree) { return null; } MyJavadocFetcher fetcher = new MyJavadocFetcher(url, new MyDocBuilder() { @Override public void buildFromStream(String url, Reader input, StringBuilder result) throws IOException { doBuildFromStream(url, input, result); } }); try { app.executeOnPooledThread(fetcher).get(); } catch (Exception e) { return null; } Exception exception = fetcher.myException; if (exception != null) { fetcher.myException = null; throw exception; } return correctDocText(url, fetcher.data); } @NotNull protected String correctDocText(@NotNull String url, @NotNull CharSequence data) { CharSequence docText = correctRefs(ourAnchorSuffix.matcher(url).replaceAll(""), data); if (LOG.isDebugEnabled()) { LOG.debug("Filtered JavaDoc: " + docText + "\n"); } return PlatformDocumentationUtil.fixupText(docText); } @Nullable public String getExternalDocInfoForElement(final String docURL, final PsiElement element) throws Exception { return getExternalDocInfo(docURL); } protected void doBuildFromStream(String url, Reader input, StringBuilder data) throws IOException { doBuildFromStream(url, input, data, true, true); } protected void doBuildFromStream(final String url, Reader input, final StringBuilder data, boolean searchForEncoding, boolean matchStart) throws IOException { ParseSettings settings = getParseSettings(url); @NonNls Pattern startSection = settings.startPattern; @NonNls Pattern endSection = settings.endPattern; boolean useDt = settings.useDt; data.append(HTML); URL baseUrl = VfsUtilCore.convertToURL(url); if (baseUrl != null) { data.append("<base href=\"").append(baseUrl).append("\">"); } data.append("<style type=\"text/css\">" + " ul.inheritance {\n" + " margin:0;\n" + " padding:0;\n" + " }\n" + " ul.inheritance li {\n" + " display:inline;\n" + " list-style-type:none;\n" + " }\n" + " ul.inheritance li ul.inheritance {\n" + " margin-left:15px;\n" + " padding-left:15px;\n" + " padding-top:1px;\n" + " }\n" + "</style>"); String read; String contentEncoding = null; @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") BufferedReader buf = new BufferedReader(input); do { read = buf.readLine(); if (read != null && searchForEncoding && read.contains("charset")) { String foundEncoding = parseContentEncoding(read); if (foundEncoding != null) { contentEncoding = foundEncoding; } } } while (read != null && matchStart && !startSection.matcher(StringUtil.toUpperCase(read)).find()); if (input instanceof MyReader && contentEncoding != null && !contentEncoding.equalsIgnoreCase(CharsetToolkit.UTF8) && !contentEncoding.equals(((MyReader)input).getEncoding())) { //restart page parsing with correct encoding try { data.setLength(0); doBuildFromStream(url, new MyReader(((MyReader)input).myInputStream, contentEncoding), data, false, true); } catch (ProcessCanceledException e) { return; } return; } if (read == null) { data.setLength(0); if (matchStart && !settings.forcePatternSearch && input instanceof MyReader) { try { final MyReader reader = contentEncoding != null ? new MyReader(((MyReader)input).myInputStream, contentEncoding) : new MyReader(((MyReader)input).myInputStream, ((MyReader)input).getEncoding()); doBuildFromStream(url, reader, data, false, false); } catch (ProcessCanceledException ignored) {} } return; } if (useDt) { boolean skip = false; do { if (StringUtil.toUpperCase(read).contains(H2) && !read.toUpperCase(Locale.ENGLISH).contains("H2")) { // read=class name in <H2> data.append(H2); skip = true; } else if (endSection.matcher(read).find() || StringUtil.indexOfIgnoreCase(read, GREATEST_END_SECTION, 0) != -1) { data.append(HTML_CLOSE); return; } else if (!skip) { appendLine(data, read); } } while (((read = buf.readLine()) != null) && !StringUtil.toUpperCase(read).trim().equals(DL) && !StringUtil.containsIgnoreCase(read, "<div class=\"description\"")); data.append(DL); StringBuilder classDetails = new StringBuilder(); while (((read = buf.readLine()) != null) && !StringUtil.toUpperCase(read).equals(HR) && !StringUtil.toUpperCase(read).equals(P)) { if (reachTheEnd(data, read, classDetails, endSection)) return; if (!skipBlockList(read)) { appendLine(classDetails, read); } } while (((read = buf.readLine()) != null) && !StringUtil.toUpperCase(read).equals(HR) && !StringUtil.toUpperCase(read).equals(P)) { if (reachTheEnd(data, read, classDetails, endSection)) return; if (!skipBlockList(read)) { appendLine(data, read.replaceAll(DT, DT + BR)); } } data.append(classDetails); data.append(P); } else { appendLine(data, read); } while (((read = buf.readLine()) != null) && !endSection.matcher(read).find() && StringUtil.indexOfIgnoreCase(read, GREATEST_END_SECTION, 0) == -1) { if (!skipBlockList(read)) { appendLine(data, read); } } data.append(HTML_CLOSE); } private static boolean skipBlockList(String read) { return StringUtil.toUpperCase(read).contains(HR) || StringUtil.containsIgnoreCase(read, "<ul class=\"blockList\">") || StringUtil.containsIgnoreCase(read, "<li class=\"blockList\">"); } @NotNull protected ParseSettings getParseSettings(@NotNull String url) { Pattern startSection = ourClassDataStartPattern; Pattern endSection = ourClassDataEndPattern; boolean anchorPresent = false; Matcher anchorMatcher = ourAnchorSuffix.matcher(url); if (anchorMatcher.find()) { anchorPresent = true; startSection = Pattern.compile("<a (name|id)=\"" + Pattern.quote(anchorMatcher.group(1)) + "\"", Pattern.CASE_INSENSITIVE); endSection = ourNonClassDataEndPattern; } return new ParseSettings(startSection, endSection, !anchorPresent, anchorPresent); } private static boolean reachTheEnd(StringBuilder data, String read, StringBuilder classDetails, Pattern endSection) { if (StringUtil.indexOfIgnoreCase(read, FIELD_SUMMARY, 0) != -1 || StringUtil.indexOfIgnoreCase(read, CLASS_SUMMARY, 0) != -1 || StringUtil.indexOfIgnoreCase(read, GREATEST_END_SECTION, 0) != -1 || endSection.matcher(read).find()) { data.append(classDetails); data.append(HTML_CLOSE); return true; } return false; } @Nullable static String parseContentEncoding(@NotNull String htmlLine) { if (!htmlLine.contains("charset")) { return null; } Matcher matcher = CHARSET_META_PATTERN.matcher(htmlLine); return matcher.find() ? matcher.group(1) : null; } private static void appendLine(StringBuilder buffer, final String read) { buffer.append(read); buffer.append("\n"); } private interface MyDocBuilder { void buildFromStream(String url, Reader input, StringBuilder result) throws IOException; } private static class MyJavadocFetcher implements Runnable { private static boolean ourFree = true; private final StringBuilder data = new StringBuilder(); private final String url; private final MyDocBuilder myBuilder; private Exception myException; MyJavadocFetcher(String url, MyDocBuilder builder) { this.url = url; myBuilder = builder; //noinspection AssignmentToStaticFieldFromInstanceMethod ourFree = false; } @Override public void run() { try { if (url == null) { return; } if (url.startsWith(JAR_PROTOCOL)) { VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(BrowserUtil.getDocURL(url)); if (file != null) { myBuilder.buildFromStream(url, new StringReader(VfsUtilCore.loadText(file)), data); } } else { URL parsedUrl = BrowserUtil.getURL(url); if (parsedUrl != null) { // gzip is disabled because in any case compressed JAR is downloaded HttpRequests.request(parsedUrl.toString()).gzip(false).connect(new HttpRequests.RequestProcessor<Void>() { @Override public Void process(@NotNull HttpRequests.Request request) throws IOException { byte[] bytes = request.readBytes(null); String contentEncoding = null; ByteArrayInputStream stream = new ByteArrayInputStream(bytes); try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { for (String htmlLine = reader.readLine(); htmlLine != null; htmlLine = reader.readLine()) { contentEncoding = parseContentEncoding(htmlLine); if (contentEncoding != null) { break; } } } finally { stream.reset(); } if (contentEncoding == null) { contentEncoding = request.getConnection().getContentEncoding(); } //noinspection IOResourceOpenedButNotSafelyClosed myBuilder.buildFromStream(url, contentEncoding != null ? new MyReader(stream, contentEncoding) : new MyReader(stream), data); return null; } }); } } } catch (ProcessCanceledException ignored) { } catch (IOException e) { myException = e; } finally { //noinspection AssignmentToStaticFieldFromInstanceMethod ourFree = true; } } } private static class MyReader extends InputStreamReader { private final ByteArrayInputStream myInputStream; MyReader(ByteArrayInputStream in) { super(in); in.reset(); myInputStream = in; } MyReader(ByteArrayInputStream in, String charsetName) throws UnsupportedEncodingException { super(in, charsetName); in.reset(); myInputStream = in; } } /** * Settings used for parsing of external documentation */ protected static class ParseSettings { /** * Pattern defining the start of target fragment */ @NotNull private final Pattern startPattern; /** * Pattern defining the end of target fragment */ @NotNull private final Pattern endPattern; /** * If {@code false}, and line matching start pattern is not found, whole document will be processed */ private final boolean forcePatternSearch; /** * Replace table data by &lt;dt&gt; */ private final boolean useDt; public ParseSettings(@NotNull Pattern startPattern, @NotNull Pattern endPattern, boolean useDt, boolean forcePatternSearch) { this.startPattern = startPattern; this.endPattern = endPattern; this.useDt = useDt; this.forcePatternSearch = forcePatternSearch; } } }
apache-2.0
trasa/aws-sdk-java
aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/model/transform/IdentityVerificationAttributesStaxUnmarshaller.java
3029
/* * Copyright 2010-2016 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.simpleemail.model.transform; import java.util.Map; import java.util.Map.Entry; import javax.xml.stream.events.XMLEvent; import com.amazonaws.services.simpleemail.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.MapEntry; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * IdentityVerificationAttributes StAX Unmarshaller */ public class IdentityVerificationAttributesStaxUnmarshaller implements Unmarshaller<IdentityVerificationAttributes, StaxUnmarshallerContext> { public IdentityVerificationAttributes unmarshall( StaxUnmarshallerContext context) throws Exception { IdentityVerificationAttributes identityVerificationAttributes = new IdentityVerificationAttributes(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return identityVerificationAttributes; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("VerificationStatus", targetDepth)) { identityVerificationAttributes .setVerificationStatus(StringStaxUnmarshaller .getInstance().unmarshall(context)); continue; } if (context.testExpression("VerificationToken", targetDepth)) { identityVerificationAttributes .setVerificationToken(StringStaxUnmarshaller .getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return identityVerificationAttributes; } } } } private static IdentityVerificationAttributesStaxUnmarshaller instance; public static IdentityVerificationAttributesStaxUnmarshaller getInstance() { if (instance == null) instance = new IdentityVerificationAttributesStaxUnmarshaller(); return instance; } }
apache-2.0
MarsZone/EGame
src/com/Model/User.ts
422
module Model{ export class User extends egret.EventDispatcher{ public constructor(){ super(); } public setData(name="",pw="",email="",started=false):void{ this.name=name; this.pw = pw; this.email=email; this.started=started; } name =""; pw=""; email=""; started:boolean=false; } }
apache-2.0
robv8r/FluentValidation
src/FluentValidation.Tests.Mvc6.dotnet/ExtensionTests.cs
2665
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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 latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion namespace FluentValidation.Tests.AspNetCore { using Xunit; using FluentValidation; using FluentValidation.AspNetCore; using Microsoft.AspNetCore.Mvc.ModelBinding; using FluentValidation.Results; public class ValidationResultExtensionTests { private ValidationResult result; public ValidationResultExtensionTests() { result = new ValidationResult(new[] { new ValidationFailure("foo", "A foo error occurred", "x"), new ValidationFailure("bar", "A bar error occurred", "y"), }); } [Fact] public void Should_persist_to_modelstate() { var modelstate = new ModelStateDictionary(); result.AddToModelState(modelstate, null); modelstate.IsValid.ShouldBeFalse(); modelstate["foo"].Errors[0].ErrorMessage.ShouldEqual("A foo error occurred"); modelstate["bar"].Errors[0].ErrorMessage.ShouldEqual("A bar error occurred"); // modelstate["foo"].AttemptedValue.ShouldEqual("x"); // modelstate["bar"].AttemptedValue.ShouldEqual("y"); } [Fact] public void Should_persist_modelstate_with_empty_prefix() { var modelstate = new ModelStateDictionary(); result.AddToModelState(modelstate, ""); modelstate["foo"].Errors[0].ErrorMessage.ShouldEqual("A foo error occurred"); } [Fact] public void Should_persist_to_modelstate_with_prefix() { var modelstate = new ModelStateDictionary(); result.AddToModelState(modelstate, "baz"); modelstate.IsValid.ShouldBeFalse(); modelstate["baz.foo"].Errors[0].ErrorMessage.ShouldEqual("A foo error occurred"); modelstate["baz.bar"].Errors[0].ErrorMessage.ShouldEqual("A bar error occurred"); } [Fact] public void Should_do_nothing_if_result_is_valid() { var modelState = new ModelStateDictionary(); new ValidationResult().AddToModelState(modelState, null); modelState.IsValid.ShouldBeTrue(); } } }
apache-2.0