code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
// Copyright 2015 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package client
import (
"context"
"encoding/json"
"errors"
"fmt"
"go.etcd.io/etcd/v3/pkg/pathutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const (
ErrorCodeKeyNotFound = 100
ErrorCodeTestFailed = 101
ErrorCodeNotFile = 102
ErrorCodeNotDir = 104
ErrorCodeNodeExist = 105
ErrorCodeRootROnly = 107
ErrorCodeDirNotEmpty = 108
ErrorCodeUnauthorized = 110
ErrorCodePrevValueRequired = 201
ErrorCodeTTLNaN = 202
ErrorCodeIndexNaN = 203
ErrorCodeInvalidField = 209
ErrorCodeInvalidForm = 210
ErrorCodeRaftInternal = 300
ErrorCodeLeaderElect = 301
ErrorCodeWatcherCleared = 400
ErrorCodeEventIndexCleared = 401
)
type Error struct {
Code int `json:"errorCode"`
Message string `json:"message"`
Cause string `json:"cause"`
Index uint64 `json:"index"`
}
func (e Error) Error() string {
return fmt.Sprintf("%v: %v (%v) [%v]", e.Code, e.Message, e.Cause, e.Index)
}
var (
ErrInvalidJSON = errors.New("client: response is invalid json. The endpoint is probably not valid etcd cluster endpoint")
ErrEmptyBody = errors.New("client: response body is empty")
)
// PrevExistType is used to define an existence condition when setting
// or deleting Nodes.
type PrevExistType string
const (
PrevIgnore = PrevExistType("")
PrevExist = PrevExistType("true")
PrevNoExist = PrevExistType("false")
)
var (
defaultV2KeysPrefix = "/v2/keys"
)
// NewKeysAPI builds a KeysAPI that interacts with etcd's key-value
// API over HTTP.
func NewKeysAPI(c Client) KeysAPI {
return NewKeysAPIWithPrefix(c, defaultV2KeysPrefix)
}
// NewKeysAPIWithPrefix acts like NewKeysAPI, but allows the caller
// to provide a custom base URL path. This should only be used in
// very rare cases.
func NewKeysAPIWithPrefix(c Client, p string) KeysAPI {
return &httpKeysAPI{
client: c,
prefix: p,
}
}
type KeysAPI interface {
// Get retrieves a set of Nodes from etcd
Get(ctx context.Context, key string, opts *GetOptions) (*Response, error)
// Set assigns a new value to a Node identified by a given key. The caller
// may define a set of conditions in the SetOptions. If SetOptions.Dir=true
// then value is ignored.
Set(ctx context.Context, key, value string, opts *SetOptions) (*Response, error)
// Delete removes a Node identified by the given key, optionally destroying
// all of its children as well. The caller may define a set of required
// conditions in an DeleteOptions object.
Delete(ctx context.Context, key string, opts *DeleteOptions) (*Response, error)
// Create is an alias for Set w/ PrevExist=false
Create(ctx context.Context, key, value string) (*Response, error)
// CreateInOrder is used to atomically create in-order keys within the given directory.
CreateInOrder(ctx context.Context, dir, value string, opts *CreateInOrderOptions) (*Response, error)
// Update is an alias for Set w/ PrevExist=true
Update(ctx context.Context, key, value string) (*Response, error)
// Watcher builds a new Watcher targeted at a specific Node identified
// by the given key. The Watcher may be configured at creation time
// through a WatcherOptions object. The returned Watcher is designed
// to emit events that happen to a Node, and optionally to its children.
Watcher(key string, opts *WatcherOptions) Watcher
}
type WatcherOptions struct {
// AfterIndex defines the index after-which the Watcher should
// start emitting events. For example, if a value of 5 is
// provided, the first event will have an index >= 6.
//
// Setting AfterIndex to 0 (default) means that the Watcher
// should start watching for events starting at the current
// index, whatever that may be.
AfterIndex uint64
// Recursive specifies whether or not the Watcher should emit
// events that occur in children of the given keyspace. If set
// to false (default), events will be limited to those that
// occur for the exact key.
Recursive bool
}
type CreateInOrderOptions struct {
// TTL defines a period of time after-which the Node should
// expire and no longer exist. Values <= 0 are ignored. Given
// that the zero-value is ignored, TTL cannot be used to set
// a TTL of 0.
TTL time.Duration
}
type SetOptions struct {
// PrevValue specifies what the current value of the Node must
// be in order for the Set operation to succeed.
//
// Leaving this field empty means that the caller wishes to
// ignore the current value of the Node. This cannot be used
// to compare the Node's current value to an empty string.
//
// PrevValue is ignored if Dir=true
PrevValue string
// PrevIndex indicates what the current ModifiedIndex of the
// Node must be in order for the Set operation to succeed.
//
// If PrevIndex is set to 0 (default), no comparison is made.
PrevIndex uint64
// PrevExist specifies whether the Node must currently exist
// (PrevExist) or not (PrevNoExist). If the caller does not
// care about existence, set PrevExist to PrevIgnore, or simply
// leave it unset.
PrevExist PrevExistType
// TTL defines a period of time after-which the Node should
// expire and no longer exist. Values <= 0 are ignored. Given
// that the zero-value is ignored, TTL cannot be used to set
// a TTL of 0.
TTL time.Duration
// Refresh set to true means a TTL value can be updated
// without firing a watch or changing the node value. A
// value must not be provided when refreshing a key.
Refresh bool
// Dir specifies whether or not this Node should be created as a directory.
Dir bool
// NoValueOnSuccess specifies whether the response contains the current value of the Node.
// If set, the response will only contain the current value when the request fails.
NoValueOnSuccess bool
}
type GetOptions struct {
// Recursive defines whether or not all children of the Node
// should be returned.
Recursive bool
// Sort instructs the server whether or not to sort the Nodes.
// If true, the Nodes are sorted alphabetically by key in
// ascending order (A to z). If false (default), the Nodes will
// not be sorted and the ordering used should not be considered
// predictable.
Sort bool
// Quorum specifies whether it gets the latest committed value that
// has been applied in quorum of members, which ensures external
// consistency (or linearizability).
Quorum bool
}
type DeleteOptions struct {
// PrevValue specifies what the current value of the Node must
// be in order for the Delete operation to succeed.
//
// Leaving this field empty means that the caller wishes to
// ignore the current value of the Node. This cannot be used
// to compare the Node's current value to an empty string.
PrevValue string
// PrevIndex indicates what the current ModifiedIndex of the
// Node must be in order for the Delete operation to succeed.
//
// If PrevIndex is set to 0 (default), no comparison is made.
PrevIndex uint64
// Recursive defines whether or not all children of the Node
// should be deleted. If set to true, all children of the Node
// identified by the given key will be deleted. If left unset
// or explicitly set to false, only a single Node will be
// deleted.
Recursive bool
// Dir specifies whether or not this Node should be removed as a directory.
Dir bool
}
type Watcher interface {
// Next blocks until an etcd event occurs, then returns a Response
// representing that event. The behavior of Next depends on the
// WatcherOptions used to construct the Watcher. Next is designed to
// be called repeatedly, each time blocking until a subsequent event
// is available.
//
// If the provided context is cancelled, Next will return a non-nil
// error. Any other failures encountered while waiting for the next
// event (connection issues, deserialization failures, etc) will
// also result in a non-nil error.
Next(context.Context) (*Response, error)
}
type Response struct {
// Action is the name of the operation that occurred. Possible values
// include get, set, delete, update, create, compareAndSwap,
// compareAndDelete and expire.
Action string `json:"action"`
// Node represents the state of the relevant etcd Node.
Node *Node `json:"node"`
// PrevNode represents the previous state of the Node. PrevNode is non-nil
// only if the Node existed before the action occurred and the action
// caused a change to the Node.
PrevNode *Node `json:"prevNode"`
// Index holds the cluster-level index at the time the Response was generated.
// This index is not tied to the Node(s) contained in this Response.
Index uint64 `json:"-"`
// ClusterID holds the cluster-level ID reported by the server. This
// should be different for different etcd clusters.
ClusterID string `json:"-"`
}
type Node struct {
// Key represents the unique location of this Node (e.g. "/foo/bar").
Key string `json:"key"`
// Dir reports whether node describes a directory.
Dir bool `json:"dir,omitempty"`
// Value is the current data stored on this Node. If this Node
// is a directory, Value will be empty.
Value string `json:"value"`
// Nodes holds the children of this Node, only if this Node is a directory.
// This slice of will be arbitrarily deep (children, grandchildren, great-
// grandchildren, etc.) if a recursive Get or Watch request were made.
Nodes Nodes `json:"nodes"`
// CreatedIndex is the etcd index at-which this Node was created.
CreatedIndex uint64 `json:"createdIndex"`
// ModifiedIndex is the etcd index at-which this Node was last modified.
ModifiedIndex uint64 `json:"modifiedIndex"`
// Expiration is the server side expiration time of the key.
Expiration *time.Time `json:"expiration,omitempty"`
// TTL is the time to live of the key in second.
TTL int64 `json:"ttl,omitempty"`
}
func (n *Node) String() string {
return fmt.Sprintf("{Key: %s, CreatedIndex: %d, ModifiedIndex: %d, TTL: %d}", n.Key, n.CreatedIndex, n.ModifiedIndex, n.TTL)
}
// TTLDuration returns the Node's TTL as a time.Duration object
func (n *Node) TTLDuration() time.Duration {
return time.Duration(n.TTL) * time.Second
}
type Nodes []*Node
// interfaces for sorting
func (ns Nodes) Len() int { return len(ns) }
func (ns Nodes) Less(i, j int) bool { return ns[i].Key < ns[j].Key }
func (ns Nodes) Swap(i, j int) { ns[i], ns[j] = ns[j], ns[i] }
type httpKeysAPI struct {
client httpClient
prefix string
}
func (k *httpKeysAPI) Set(ctx context.Context, key, val string, opts *SetOptions) (*Response, error) {
act := &setAction{
Prefix: k.prefix,
Key: key,
Value: val,
}
if opts != nil {
act.PrevValue = opts.PrevValue
act.PrevIndex = opts.PrevIndex
act.PrevExist = opts.PrevExist
act.TTL = opts.TTL
act.Refresh = opts.Refresh
act.Dir = opts.Dir
act.NoValueOnSuccess = opts.NoValueOnSuccess
}
doCtx := ctx
if act.PrevExist == PrevNoExist {
doCtx = context.WithValue(doCtx, &oneShotCtxValue, &oneShotCtxValue)
}
resp, body, err := k.client.Do(doCtx, act)
if err != nil {
return nil, err
}
return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
}
func (k *httpKeysAPI) Create(ctx context.Context, key, val string) (*Response, error) {
return k.Set(ctx, key, val, &SetOptions{PrevExist: PrevNoExist})
}
func (k *httpKeysAPI) CreateInOrder(ctx context.Context, dir, val string, opts *CreateInOrderOptions) (*Response, error) {
act := &createInOrderAction{
Prefix: k.prefix,
Dir: dir,
Value: val,
}
if opts != nil {
act.TTL = opts.TTL
}
resp, body, err := k.client.Do(ctx, act)
if err != nil {
return nil, err
}
return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
}
func (k *httpKeysAPI) Update(ctx context.Context, key, val string) (*Response, error) {
return k.Set(ctx, key, val, &SetOptions{PrevExist: PrevExist})
}
func (k *httpKeysAPI) Delete(ctx context.Context, key string, opts *DeleteOptions) (*Response, error) {
act := &deleteAction{
Prefix: k.prefix,
Key: key,
}
if opts != nil {
act.PrevValue = opts.PrevValue
act.PrevIndex = opts.PrevIndex
act.Dir = opts.Dir
act.Recursive = opts.Recursive
}
doCtx := context.WithValue(ctx, &oneShotCtxValue, &oneShotCtxValue)
resp, body, err := k.client.Do(doCtx, act)
if err != nil {
return nil, err
}
return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
}
func (k *httpKeysAPI) Get(ctx context.Context, key string, opts *GetOptions) (*Response, error) {
act := &getAction{
Prefix: k.prefix,
Key: key,
}
if opts != nil {
act.Recursive = opts.Recursive
act.Sorted = opts.Sort
act.Quorum = opts.Quorum
}
resp, body, err := k.client.Do(ctx, act)
if err != nil {
return nil, err
}
return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
}
func (k *httpKeysAPI) Watcher(key string, opts *WatcherOptions) Watcher {
act := waitAction{
Prefix: k.prefix,
Key: key,
}
if opts != nil {
act.Recursive = opts.Recursive
if opts.AfterIndex > 0 {
act.WaitIndex = opts.AfterIndex + 1
}
}
return &httpWatcher{
client: k.client,
nextWait: act,
}
}
type httpWatcher struct {
client httpClient
nextWait waitAction
}
func (hw *httpWatcher) Next(ctx context.Context) (*Response, error) {
for {
httpresp, body, err := hw.client.Do(ctx, &hw.nextWait)
if err != nil {
return nil, err
}
resp, err := unmarshalHTTPResponse(httpresp.StatusCode, httpresp.Header, body)
if err != nil {
if err == ErrEmptyBody {
continue
}
return nil, err
}
hw.nextWait.WaitIndex = resp.Node.ModifiedIndex + 1
return resp, nil
}
}
// v2KeysURL forms a URL representing the location of a key.
// The endpoint argument represents the base URL of an etcd
// server. The prefix is the path needed to route from the
// provided endpoint's path to the root of the keys API
// (typically "/v2/keys").
func v2KeysURL(ep url.URL, prefix, key string) *url.URL {
// We concatenate all parts together manually. We cannot use
// path.Join because it does not reserve trailing slash.
// We call CanonicalURLPath to further cleanup the path.
if prefix != "" && prefix[0] != '/' {
prefix = "/" + prefix
}
if key != "" && key[0] != '/' {
key = "/" + key
}
ep.Path = pathutil.CanonicalURLPath(ep.Path + prefix + key)
return &ep
}
type getAction struct {
Prefix string
Key string
Recursive bool
Sorted bool
Quorum bool
}
func (g *getAction) HTTPRequest(ep url.URL) *http.Request {
u := v2KeysURL(ep, g.Prefix, g.Key)
params := u.Query()
params.Set("recursive", strconv.FormatBool(g.Recursive))
params.Set("sorted", strconv.FormatBool(g.Sorted))
params.Set("quorum", strconv.FormatBool(g.Quorum))
u.RawQuery = params.Encode()
req, _ := http.NewRequest("GET", u.String(), nil)
return req
}
type waitAction struct {
Prefix string
Key string
WaitIndex uint64
Recursive bool
}
func (w *waitAction) HTTPRequest(ep url.URL) *http.Request {
u := v2KeysURL(ep, w.Prefix, w.Key)
params := u.Query()
params.Set("wait", "true")
params.Set("waitIndex", strconv.FormatUint(w.WaitIndex, 10))
params.Set("recursive", strconv.FormatBool(w.Recursive))
u.RawQuery = params.Encode()
req, _ := http.NewRequest("GET", u.String(), nil)
return req
}
type setAction struct {
Prefix string
Key string
Value string
PrevValue string
PrevIndex uint64
PrevExist PrevExistType
TTL time.Duration
Refresh bool
Dir bool
NoValueOnSuccess bool
}
func (a *setAction) HTTPRequest(ep url.URL) *http.Request {
u := v2KeysURL(ep, a.Prefix, a.Key)
params := u.Query()
form := url.Values{}
// we're either creating a directory or setting a key
if a.Dir {
params.Set("dir", strconv.FormatBool(a.Dir))
} else {
// These options are only valid for setting a key
if a.PrevValue != "" {
params.Set("prevValue", a.PrevValue)
}
form.Add("value", a.Value)
}
// Options which apply to both setting a key and creating a dir
if a.PrevIndex != 0 {
params.Set("prevIndex", strconv.FormatUint(a.PrevIndex, 10))
}
if a.PrevExist != PrevIgnore {
params.Set("prevExist", string(a.PrevExist))
}
if a.TTL > 0 {
form.Add("ttl", strconv.FormatUint(uint64(a.TTL.Seconds()), 10))
}
if a.Refresh {
form.Add("refresh", "true")
}
if a.NoValueOnSuccess {
params.Set("noValueOnSuccess", strconv.FormatBool(a.NoValueOnSuccess))
}
u.RawQuery = params.Encode()
body := strings.NewReader(form.Encode())
req, _ := http.NewRequest("PUT", u.String(), body)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return req
}
type deleteAction struct {
Prefix string
Key string
PrevValue string
PrevIndex uint64
Dir bool
Recursive bool
}
func (a *deleteAction) HTTPRequest(ep url.URL) *http.Request {
u := v2KeysURL(ep, a.Prefix, a.Key)
params := u.Query()
if a.PrevValue != "" {
params.Set("prevValue", a.PrevValue)
}
if a.PrevIndex != 0 {
params.Set("prevIndex", strconv.FormatUint(a.PrevIndex, 10))
}
if a.Dir {
params.Set("dir", "true")
}
if a.Recursive {
params.Set("recursive", "true")
}
u.RawQuery = params.Encode()
req, _ := http.NewRequest("DELETE", u.String(), nil)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return req
}
type createInOrderAction struct {
Prefix string
Dir string
Value string
TTL time.Duration
}
func (a *createInOrderAction) HTTPRequest(ep url.URL) *http.Request {
u := v2KeysURL(ep, a.Prefix, a.Dir)
form := url.Values{}
form.Add("value", a.Value)
if a.TTL > 0 {
form.Add("ttl", strconv.FormatUint(uint64(a.TTL.Seconds()), 10))
}
body := strings.NewReader(form.Encode())
req, _ := http.NewRequest("POST", u.String(), body)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return req
}
func unmarshalHTTPResponse(code int, header http.Header, body []byte) (res *Response, err error) {
switch code {
case http.StatusOK, http.StatusCreated:
if len(body) == 0 {
return nil, ErrEmptyBody
}
res, err = unmarshalSuccessfulKeysResponse(header, body)
default:
err = unmarshalFailedKeysResponse(body)
}
return res, err
}
var jsonIterator = caseSensitiveJsonIterator()
func unmarshalSuccessfulKeysResponse(header http.Header, body []byte) (*Response, error) {
var res Response
err := jsonIterator.Unmarshal(body, &res)
if err != nil {
return nil, ErrInvalidJSON
}
if header.Get("X-Etcd-Index") != "" {
res.Index, err = strconv.ParseUint(header.Get("X-Etcd-Index"), 10, 64)
if err != nil {
return nil, err
}
}
res.ClusterID = header.Get("X-Etcd-Cluster-ID")
return &res, nil
}
func unmarshalFailedKeysResponse(body []byte) error {
var etcdErr Error
if err := json.Unmarshal(body, &etcdErr); err != nil {
return ErrInvalidJSON
}
return etcdErr
}
|
cockroachdb/etcd
|
client/keys.go
|
GO
|
apache-2.0
| 19,366
|
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.datavec.api.records.reader.impl.csv;
import org.datavec.api.conf.Configuration;
import org.datavec.api.records.Record;
import org.datavec.api.records.SequenceRecord;
import org.datavec.api.records.metadata.RecordMetaData;
import org.datavec.api.records.metadata.RecordMetaDataLineInterval;
import org.datavec.api.records.reader.SequenceRecordReader;
import org.datavec.api.split.InputSplit;
import org.datavec.api.writable.Text;
import org.datavec.api.writable.Writable;
import org.nd4j.common.primitives.Triple;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.URI;
import java.util.*;
/**
* A CSV Sequence record reader where:<br>
* (a) all time series are in a single file<br>
* (b) each time series is of the same length (specified in constructor)<br>
* (c) no delimiter is used between time series<br>
*
* For example, with nLinesPerSequence=10, lines 0 to 9 are the first time series, 10 to 19 are the second, and so on.
*
* @author Alex Black
*/
public class CSVNLinesSequenceRecordReader extends CSVRecordReader implements SequenceRecordReader {
public static final String LINES_PER_SEQUENCE = NAME_SPACE + ".nlinespersequence";
private int nLinesPerSequence;
private String delimiter;
/**
* No-arg constructor with the default number of lines per sequence (10)
*/
public CSVNLinesSequenceRecordReader() {
this(10);
}
/**
* @param nLinesPerSequence Number of lines in each sequence, use default delemiter(,) between entries in the same line
*/
public CSVNLinesSequenceRecordReader(int nLinesPerSequence) {
this(nLinesPerSequence, 0, String.valueOf(CSVRecordReader.DEFAULT_DELIMITER));
}
/**
*
* @param nLinesPerSequence Number of lines in each sequences
* @param skipNumLines Number of lines to skip at the start of the file (only skipped once, not per sequence)
* @param delimiter Delimiter between entries in the same line, for example ","
*/
public CSVNLinesSequenceRecordReader(int nLinesPerSequence, int skipNumLines, String delimiter) {
super(skipNumLines);
this.delimiter = delimiter;
this.nLinesPerSequence = nLinesPerSequence;
}
@Override
public void initialize(Configuration conf, InputSplit split) throws IOException, InterruptedException {
super.initialize(conf, split);
this.nLinesPerSequence = conf.getInt(LINES_PER_SEQUENCE, nLinesPerSequence);
}
@Override
public List<List<Writable>> sequenceRecord() {
if (!super.hasNext()) {
throw new NoSuchElementException("No next element");
}
List<List<Writable>> sequence = new ArrayList<>();
int count = 0;
while (count++ < nLinesPerSequence && super.hasNext()) {
sequence.add(super.next());
}
return sequence;
}
@Override
public List<List<Writable>> sequenceRecord(URI uri, DataInputStream dataInputStream) throws IOException {
throw new UnsupportedOperationException("Reading CSV data from DataInputStream not yet implemented");
}
@Override
public SequenceRecord nextSequence() {
int lineBefore = lineIndex;
List<List<Writable>> record = sequenceRecord();
int lineAfter = lineIndex;
URI uri = (locations == null || locations.length < 1 ? null : locations[splitIndex]);
RecordMetaData meta = new RecordMetaDataLineInterval(lineBefore, lineAfter - 1, uri,
CSVNLinesSequenceRecordReader.class);
return new org.datavec.api.records.impl.SequenceRecord(record, meta);
}
@Override
public SequenceRecord loadSequenceFromMetaData(RecordMetaData recordMetaData) throws IOException {
return loadSequenceFromMetaData(Collections.singletonList(recordMetaData)).get(0);
}
@Override
public List<SequenceRecord> loadSequenceFromMetaData(List<RecordMetaData> recordMetaDatas) throws IOException {
//First: create a sorted list of the RecordMetaData
List<Triple<Integer, RecordMetaDataLineInterval, List<List<Writable>>>> list = new ArrayList<>();
Iterator<RecordMetaData> iter = recordMetaDatas.iterator();
int count = 0;
while (iter.hasNext()) {
RecordMetaData rmd = iter.next();
if (!(rmd instanceof RecordMetaDataLineInterval)) {
throw new IllegalArgumentException(
"Invalid metadata; expected RecordMetaDataLineInterval instance; got: " + rmd);
}
list.add(new Triple<>(count++, (RecordMetaDataLineInterval) rmd,
(List<List<Writable>>) new ArrayList<List<Writable>>()));
}
//Sort by starting line number:
Collections.sort(list, new Comparator<Triple<Integer, RecordMetaDataLineInterval, List<List<Writable>>>>() {
@Override
public int compare(Triple<Integer, RecordMetaDataLineInterval, List<List<Writable>>> o1,
Triple<Integer, RecordMetaDataLineInterval, List<List<Writable>>> o2) {
return Integer.compare(o1.getSecond().getLineNumberStart(), o2.getSecond().getLineNumberStart());
}
});
Iterator<String> lineIter = getIterator(0); //TODO handle multi file case...
int currentLineIdx = 0;
String line = lineIter.next();
while (currentLineIdx < skipNumLines) {
line = lineIter.next();
currentLineIdx++;
}
for (Triple<Integer, RecordMetaDataLineInterval, List<List<Writable>>> next : list) {
int nextStartLine = next.getSecond().getLineNumberStart();
int nextEndLine = next.getSecond().getLineNumberEnd();
while (currentLineIdx < nextStartLine && lineIter.hasNext()) {
line = lineIter.next();
currentLineIdx++;
}
while (currentLineIdx <= nextEndLine && (lineIter.hasNext() || currentLineIdx == nextEndLine)) {
String[] split = line.split(this.delimiter, -1);
List<Writable> writables = new ArrayList<>();
for (String s : split) {
writables.add(new Text(s));
}
next.getThird().add(writables);
currentLineIdx++;
if (lineIter.hasNext()) {
line = lineIter.next();
}
}
}
closeIfRequired(lineIter);
//Now, sort by the original order:
Collections.sort(list, new Comparator<Triple<Integer, RecordMetaDataLineInterval, List<List<Writable>>>>() {
@Override
public int compare(Triple<Integer, RecordMetaDataLineInterval, List<List<Writable>>> o1,
Triple<Integer, RecordMetaDataLineInterval, List<List<Writable>>> o2) {
return Integer.compare(o1.getFirst(), o2.getFirst());
}
});
//And return...
List<SequenceRecord> out = new ArrayList<>();
for (Triple<Integer, RecordMetaDataLineInterval, List<List<Writable>>> t : list) {
out.add(new org.datavec.api.records.impl.SequenceRecord(t.getThird(), t.getSecond()));
}
return out;
}
@Override
public Record loadFromMetaData(RecordMetaData recordMetaData) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public List<Record> loadFromMetaData(List<RecordMetaData> recordMetaDatas) {
throw new UnsupportedOperationException("Not supported");
}
}
|
deeplearning4j/deeplearning4j
|
datavec/datavec-api/src/main/java/org/datavec/api/records/reader/impl/csv/CSVNLinesSequenceRecordReader.java
|
Java
|
apache-2.0
| 8,431
|
package com.claudioliveira.receiver;
import com.claudioliveira.domain.DomainCollection;
import com.claudioliveira.domain.DomainEvent;
import com.claudioliveira.domain.SalesCodeGenerator;
import com.claudioliveira.infra.DateTimeMongoFormat;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.mongo.MongoClient;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* This handler is responsible to stores sales in database.
*
* @author Claudio Eduardo de Oliveira (claudioed.oliveira@gmail.com).
*/
public class RegisterSales extends AbstractVerticle {
private static final Logger LOGGER = LoggerFactory.getLogger(RegisterSales.class);
@Override
public void start() throws Exception {
final MongoClient mongoClient = MongoClient.createShared(vertx,
new JsonObject().put("magazine-manager", "magazine-manager"), "magazine-manager");
EventBus eb = vertx.eventBus();
eb.consumer(DomainEvent.NEW_SALE.event(), message ->
mongoClient.insert(DomainCollection.SALES.collection(), new JsonObject(message
.body().toString())
.put("creationAt", new JsonObject().put("$date", DateTimeMongoFormat.format(LocalDateTime.now())))
.put("code", new SalesCodeGenerator(LocalDateTime.now()).newCode()), result -> {
if (result.succeeded()) {
eb.publish(DomainEvent.UPDATE_DELIVERY_STOCK.event(), new JsonObject().put("saleId", result.result()));
eb.publish(DomainEvent.UPDATE_MAGAZINE_STOCK.event(), new JsonObject().put("saleId", result.result()));
} else {
LOGGER.error("Error on save sale!!!");
}
})
);
}
}
|
brunomillerps/magazine-manager
|
src/main/java/com/claudioliveira/receiver/RegisterSales.java
|
Java
|
apache-2.0
| 2,081
|
<!DOCTYPE html>
<html>
<head>
<base href="http://fushenghua.github.io/GetHosp">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>广东福康医院</title>
<meta name="viewport" content="width=device-width">
<meta name="description" content="GetHosp">
<link rel="canonical" href="http://fushenghua.github.io/GetHosphttp://fushenghua.github.io/GetHosp/%E5%85%B6%E4%BB%96/2016/05/03/%E5%B9%BF%E4%B8%9C%E7%A6%8F%E5%BA%B7%E5%8C%BB%E9%99%A2/">
<!-- Custom CSS -->
<link rel="stylesheet" href="http://fushenghua.github.io/GetHosp/css/main.css">
</head>
<body>
<header class="site-header">
<div class="wrap">
<a class="site-title" href="http://fushenghua.github.io/GetHosp/">GetHosp</a>
<nav class="site-nav">
<a href="#" class="menu-icon">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 18 15" enable-background="new 0 0 18 15" xml:space="preserve">
<path fill="#505050" d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0
h15.031C17.335,0,18,0.665,18,1.484L18,1.484z"/>
<path fill="#505050" d="M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0c0-0.82,0.665-1.484,1.484-1.484
h15.031C17.335,6.031,18,6.696,18,7.516L18,7.516z"/>
<path fill="#505050" d="M18,13.516C18,14.335,17.335,15,16.516,15H1.484C0.665,15,0,14.335,0,13.516l0,0
c0-0.82,0.665-1.484,1.484-1.484h15.031C17.335,12.031,18,12.696,18,13.516L18,13.516z"/>
</svg>
</a>
<div class="trigger">
<a class="page-link" href="http://fushenghua.github.io/GetHosp/about/">About</a>
</div>
</nav>
</div>
</header>
<div class="page-content">
<div class="wrap">
<div class="post">
<header class="post-header">
<h1>广东福康医院</h1>
<p class="meta">May 3, 2016</p>
</header>
<article class="post-content">
<p>广东福康医院</p>
<p>信息</p>
</article>
</div>
</div>
</div>
<footer class="site-footer">
<div class="wrap">
<h2 class="footer-heading">GetHosp</h2>
<div class="footer-col-1 column">
<ul>
<li>GetHosp</li>
<li><a href="mailto:fushenghua2012@gmail.com">fushenghua2012@gmail.com</a></li>
</ul>
</div>
<div class="footer-col-2 column">
<ul>
<li>
<a href="https://github.com/fushenghua">
<span class="icon github">
<svg version="1.1" class="github-icon-svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 16 16" enable-background="new 0 0 16 16" xml:space="preserve">
<path fill-rule="evenodd" clip-rule="evenodd" fill="#C2C2C2" d="M7.999,0.431c-4.285,0-7.76,3.474-7.76,7.761
c0,3.428,2.223,6.337,5.307,7.363c0.388,0.071,0.53-0.168,0.53-0.374c0-0.184-0.007-0.672-0.01-1.32
c-2.159,0.469-2.614-1.04-2.614-1.04c-0.353-0.896-0.862-1.135-0.862-1.135c-0.705-0.481,0.053-0.472,0.053-0.472
c0.779,0.055,1.189,0.8,1.189,0.8c0.692,1.186,1.816,0.843,2.258,0.645c0.071-0.502,0.271-0.843,0.493-1.037
C4.86,11.425,3.049,10.76,3.049,7.786c0-0.847,0.302-1.54,0.799-2.082C3.768,5.507,3.501,4.718,3.924,3.65
c0,0,0.652-0.209,2.134,0.796C6.677,4.273,7.34,4.187,8,4.184c0.659,0.003,1.323,0.089,1.943,0.261
c1.482-1.004,2.132-0.796,2.132-0.796c0.423,1.068,0.157,1.857,0.077,2.054c0.497,0.542,0.798,1.235,0.798,2.082
c0,2.981-1.814,3.637-3.543,3.829c0.279,0.24,0.527,0.713,0.527,1.437c0,1.037-0.01,1.874-0.01,2.129
c0,0.208,0.14,0.449,0.534,0.373c3.081-1.028,5.302-3.935,5.302-7.362C15.76,3.906,12.285,0.431,7.999,0.431z"/>
</svg>
</span>
<span class="username">fushenghua</span>
</a>
</li>
</ul>
</div>
<div class="footer-col-3 column">
<p class="text">GetHosp</p>
</div>
</div>
</footer>
</body>
</html>
|
fushenghua/GetHosp
|
_site/其他/2016/05/03/广东福康医院/index.html
|
HTML
|
apache-2.0
| 4,284
|
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Form</title>
</head>
<body>
<h1 align="center">Beer Selection Page</h1>
<form action="Selection" method="get">
<P>select Beer Characteristics<br/>
Color:<br/> <select name="color" size="1">
<option value="light">light</option>
<option value="amber">amber</option>
<option value="brown">brown</option>
<option value="dark">dark</option>
</select><br/>
<br/>
<p align="center"><input type="submit" value="click"></P>
</form>
</body>
</html>
|
BlueMapleTech/AppleGroup-Santhosh-Java-JSE-
|
Example4/WebContent/index.html
|
HTML
|
apache-2.0
| 505
|
/**
* Created by Bane.Shi.
* Copyright MoenSun
* User: Bane.Shi
* Blog: http://blog.fengxiaotx.com
* Date: 2017/2/4
* Time: 17:04
*/
'use strict';
import Datepicker from "./src/date/datepicker.vue";
module.exports = {
Datepicker
}
|
ms-vue2/ms-vue2-ui
|
src/packages/picker/index.js
|
JavaScript
|
apache-2.0
| 241
|
<?php
declare(strict_types=1);
namespace Edde\Api\Protocol\Event;
use Edde\Api\Protocol\IElement;
interface IEvent extends IElement {
}
|
edde-framework/edde-framework
|
src/Edde/Api/Protocol/Event/IEvent.php
|
PHP
|
apache-2.0
| 144
|
package com.firebase.ui.auth.viewmodel;
import android.app.Application;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RestrictTo;
import com.firebase.ui.auth.IdpResponse;
import com.firebase.ui.auth.data.model.Resource;
import com.google.firebase.auth.AuthResult;
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public abstract class SignInViewModelBase extends AuthViewModelBase<IdpResponse> {
protected SignInViewModelBase(Application application) {
super(application);
}
@Override
protected void setResult(Resource<IdpResponse> output) {
super.setResult(output);
}
public boolean canLinkAccounts() {
return getArguments().accountLinkingEnabled && getCurrentUser() != null;
}
@Nullable
public String getUidForAccountLinking() {
return canLinkAccounts() ? getCurrentUser().getUid() : null;
}
protected void handleSuccess(@NonNull IdpResponse response, @NonNull AuthResult result) {
setResult(Resource.forSuccess(response.withResult(result)));
}
}
|
SUPERCILEX/FirebaseUI-Android
|
auth/src/main/java/com/firebase/ui/auth/viewmodel/SignInViewModelBase.java
|
Java
|
apache-2.0
| 1,114
|
namespace AH.ModuleController.UI.HR.Forms
{
partial class frmDepartmentWisePayroll
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle25 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle26 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle27 = new System.Windows.Forms.DataGridViewCellStyle();
this.cboDepartment = new AtiqsControlLibrary.SmartComboBox();
this.btnShow = new System.Windows.Forms.Button();
this.cboMonth = new AtiqsControlLibrary.SmartComboBox();
this.dgvInfo = new AtiqsControlLibrary.SmartDataGridView();
this.smartLabel6 = new AtiqsControlLibrary.SmartLabel();
this.cboDepartmentGroup = new AtiqsControlLibrary.SmartComboBox();
this.smartLabel22 = new AtiqsControlLibrary.SmartLabel();
this.cboDepartmentType = new AtiqsControlLibrary.SmartComboBox();
this.smartLabel21 = new AtiqsControlLibrary.SmartLabel();
this.smartLabel4 = new AtiqsControlLibrary.SmartLabel();
this.smartLabel5 = new AtiqsControlLibrary.SmartLabel();
this.cboUnit = new AtiqsControlLibrary.SmartComboBox();
this.smartLabel7 = new AtiqsControlLibrary.SmartLabel();
this.cboYear = new AtiqsControlLibrary.SmartComboBox();
this.gbSelectOptions = new System.Windows.Forms.GroupBox();
this.rdoGrpDeptUnit = new AtiqsControlLibrary.SmartRadioButton();
this.rdoDeptGrp = new AtiqsControlLibrary.SmartRadioButton();
this.rdoAll = new AtiqsControlLibrary.SmartRadioButton();
this.pnlMain.SuspendLayout();
this.pnlTop.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dgvInfo)).BeginInit();
this.gbSelectOptions.SuspendLayout();
this.SuspendLayout();
//
// btnTopClose
//
this.btnTopClose.Location = new System.Drawing.Point(969, 3);
//
// frmLabel
//
this.frmLabel.Location = new System.Drawing.Point(638, 3);
this.frmLabel.Size = new System.Drawing.Size(307, 33);
this.frmLabel.Text = "Department Wise Payroll";
//
// pnlMain
//
this.pnlMain.BackColor = System.Drawing.Color.Lavender;
this.pnlMain.Controls.Add(this.gbSelectOptions);
this.pnlMain.Controls.Add(this.smartLabel6);
this.pnlMain.Controls.Add(this.cboDepartmentGroup);
this.pnlMain.Controls.Add(this.smartLabel22);
this.pnlMain.Controls.Add(this.cboDepartmentType);
this.pnlMain.Controls.Add(this.smartLabel21);
this.pnlMain.Controls.Add(this.smartLabel4);
this.pnlMain.Controls.Add(this.smartLabel5);
this.pnlMain.Controls.Add(this.cboUnit);
this.pnlMain.Controls.Add(this.smartLabel7);
this.pnlMain.Controls.Add(this.cboYear);
this.pnlMain.Controls.Add(this.dgvInfo);
this.pnlMain.Controls.Add(this.cboMonth);
this.pnlMain.Controls.Add(this.btnShow);
this.pnlMain.Controls.Add(this.cboDepartment);
this.pnlMain.Location = new System.Drawing.Point(0, 47);
this.pnlMain.Size = new System.Drawing.Size(1573, 770);
//
// pnlTop
//
this.pnlTop.Size = new System.Drawing.Size(1573, 51);
//
// btnEdit
//
this.btnEdit.Enabled = false;
this.btnEdit.Location = new System.Drawing.Point(300, 822);
this.btnEdit.Visible = false;
//
// btnSave
//
this.btnSave.Enabled = false;
this.btnSave.Location = new System.Drawing.Point(186, 822);
this.btnSave.Visible = false;
//
// btnDelete
//
this.btnDelete.Enabled = false;
this.btnDelete.Location = new System.Drawing.Point(414, 822);
this.btnDelete.Visible = false;
//
// btnNew
//
this.btnNew.Enabled = false;
this.btnNew.Location = new System.Drawing.Point(1340, 822);
this.btnNew.Visible = false;
this.btnNew.Click += new System.EventHandler(this.btnNew_Click);
//
// btnClose
//
this.btnClose.Location = new System.Drawing.Point(1454, 822);
//
// btnPrint
//
this.btnPrint.Enabled = false;
this.btnPrint.Location = new System.Drawing.Point(528, 822);
this.btnPrint.Visible = false;
this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
//
// groupBox1
//
this.groupBox1.Location = new System.Drawing.Point(0, 863);
this.groupBox1.Size = new System.Drawing.Size(1573, 23);
//
// cboDepartment
//
this.cboDepartment.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboDepartment.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cboDepartment.ForeColor = System.Drawing.Color.Blue;
this.cboDepartment.FormattingEnabled = true;
this.cboDepartment.Location = new System.Drawing.Point(925, 27);
this.cboDepartment.Name = "cboDepartment";
this.cboDepartment.Size = new System.Drawing.Size(187, 26);
this.cboDepartment.TabIndex = 2;
this.cboDepartment.SelectedIndexChanged += new System.EventHandler(this.cboDepartment_SelectedIndexChanged);
//
// btnShow
//
this.btnShow.BackColor = System.Drawing.Color.SeaGreen;
this.btnShow.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnShow.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnShow.ForeColor = System.Drawing.Color.White;
this.btnShow.Location = new System.Drawing.Point(1495, 24);
this.btnShow.Name = "btnShow";
this.btnShow.Size = new System.Drawing.Size(59, 29);
this.btnShow.TabIndex = 3;
this.btnShow.Text = "Show";
this.btnShow.UseVisualStyleBackColor = false;
this.btnShow.Click += new System.EventHandler(this.btnShow_Click);
//
// cboMonth
//
this.cboMonth.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboMonth.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cboMonth.ForeColor = System.Drawing.Color.Blue;
this.cboMonth.FormattingEnabled = true;
this.cboMonth.Location = new System.Drawing.Point(1384, 27);
this.cboMonth.Name = "cboMonth";
this.cboMonth.Size = new System.Drawing.Size(105, 26);
this.cboMonth.TabIndex = 1;
//
// dgvInfo
//
this.dgvInfo.AllowUserToAddRows = false;
this.dgvInfo.AllowUserToDeleteRows = false;
this.dgvInfo.AllowUserToOrderColumns = true;
this.dgvInfo.AllowUserToResizeColumns = false;
this.dgvInfo.AllowUserToResizeRows = false;
this.dgvInfo.BackgroundColor = System.Drawing.Color.White;
this.dgvInfo.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
dataGridViewCellStyle25.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle25.BackColor = System.Drawing.Color.LightGreen;
dataGridViewCellStyle25.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle25.ForeColor = System.Drawing.Color.Black;
dataGridViewCellStyle25.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
this.dgvInfo.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle25;
this.dgvInfo.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewCellStyle26.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle26.BackColor = System.Drawing.Color.White;
dataGridViewCellStyle26.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle26.ForeColor = System.Drawing.Color.Black;
dataGridViewCellStyle26.SelectionBackColor = System.Drawing.Color.Lavender;
dataGridViewCellStyle26.SelectionForeColor = System.Drawing.Color.Crimson;
dataGridViewCellStyle26.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.dgvInfo.DefaultCellStyle = dataGridViewCellStyle26;
this.dgvInfo.Location = new System.Drawing.Point(-1, 65);
this.dgvInfo.MultiSelect = false;
this.dgvInfo.Name = "dgvInfo";
this.dgvInfo.RowHeadersVisible = false;
dataGridViewCellStyle27.BackColor = System.Drawing.Color.White;
this.dgvInfo.RowsDefaultCellStyle = dataGridViewCellStyle27;
this.dgvInfo.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dgvInfo.Size = new System.Drawing.Size(1573, 704);
this.dgvInfo.TabIndex = 7;
this.dgvInfo.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvInfo_CellDoubleClick);
//
// smartLabel6
//
this.smartLabel6.AutoSize = true;
this.smartLabel6.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold);
this.smartLabel6.Location = new System.Drawing.Point(1290, 7);
this.smartLabel6.Name = "smartLabel6";
this.smartLabel6.Size = new System.Drawing.Size(41, 13);
this.smartLabel6.TabIndex = 212;
this.smartLabel6.Text = "Year :";
//
// cboDepartmentGroup
//
this.cboDepartmentGroup.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboDepartmentGroup.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cboDepartmentGroup.ForeColor = System.Drawing.Color.Blue;
this.cboDepartmentGroup.FormattingEnabled = true;
this.cboDepartmentGroup.Location = new System.Drawing.Point(700, 27);
this.cboDepartmentGroup.Name = "cboDepartmentGroup";
this.cboDepartmentGroup.Size = new System.Drawing.Size(219, 26);
this.cboDepartmentGroup.TabIndex = 204;
this.cboDepartmentGroup.SelectedIndexChanged += new System.EventHandler(this.cboDepartmentGroup_SelectedIndexChanged);
//
// smartLabel22
//
this.smartLabel22.AutoSize = true;
this.smartLabel22.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold);
this.smartLabel22.Location = new System.Drawing.Point(697, 7);
this.smartLabel22.Name = "smartLabel22";
this.smartLabel22.Size = new System.Drawing.Size(118, 13);
this.smartLabel22.TabIndex = 211;
this.smartLabel22.Text = "Department Group :";
//
// cboDepartmentType
//
this.cboDepartmentType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboDepartmentType.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cboDepartmentType.ForeColor = System.Drawing.Color.Blue;
this.cboDepartmentType.FormattingEnabled = true;
this.cboDepartmentType.Location = new System.Drawing.Point(520, 27);
this.cboDepartmentType.Name = "cboDepartmentType";
this.cboDepartmentType.Size = new System.Drawing.Size(176, 26);
this.cboDepartmentType.TabIndex = 203;
this.cboDepartmentType.SelectedIndexChanged += new System.EventHandler(this.cboDepartmentType_SelectedIndexChanged);
//
// smartLabel21
//
this.smartLabel21.AutoSize = true;
this.smartLabel21.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold);
this.smartLabel21.Location = new System.Drawing.Point(520, 7);
this.smartLabel21.Name = "smartLabel21";
this.smartLabel21.Size = new System.Drawing.Size(112, 13);
this.smartLabel21.TabIndex = 210;
this.smartLabel21.Text = "Department Type :";
//
// smartLabel4
//
this.smartLabel4.AutoSize = true;
this.smartLabel4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold);
this.smartLabel4.Location = new System.Drawing.Point(1384, 7);
this.smartLabel4.Name = "smartLabel4";
this.smartLabel4.Size = new System.Drawing.Size(50, 13);
this.smartLabel4.TabIndex = 209;
this.smartLabel4.Text = "Month :";
//
// smartLabel5
//
this.smartLabel5.AutoSize = true;
this.smartLabel5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold);
this.smartLabel5.Location = new System.Drawing.Point(1113, 7);
this.smartLabel5.Name = "smartLabel5";
this.smartLabel5.Size = new System.Drawing.Size(38, 13);
this.smartLabel5.TabIndex = 208;
this.smartLabel5.Text = "Unit :";
//
// cboUnit
//
this.cboUnit.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboUnit.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cboUnit.ForeColor = System.Drawing.Color.Blue;
this.cboUnit.FormattingEnabled = true;
this.cboUnit.Location = new System.Drawing.Point(1116, 27);
this.cboUnit.Name = "cboUnit";
this.cboUnit.Size = new System.Drawing.Size(171, 26);
this.cboUnit.TabIndex = 205;
this.cboUnit.SelectedIndexChanged += new System.EventHandler(this.cboUnit_SelectedIndexChanged);
//
// smartLabel7
//
this.smartLabel7.AutoSize = true;
this.smartLabel7.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold);
this.smartLabel7.Location = new System.Drawing.Point(925, 7);
this.smartLabel7.Name = "smartLabel7";
this.smartLabel7.Size = new System.Drawing.Size(80, 13);
this.smartLabel7.TabIndex = 207;
this.smartLabel7.Text = "Department :";
//
// cboYear
//
this.cboYear.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboYear.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cboYear.ForeColor = System.Drawing.Color.Blue;
this.cboYear.FormattingEnabled = true;
this.cboYear.Location = new System.Drawing.Point(1293, 27);
this.cboYear.Name = "cboYear";
this.cboYear.Size = new System.Drawing.Size(85, 26);
this.cboYear.TabIndex = 199;
this.cboYear.SelectedIndexChanged += new System.EventHandler(this.cboYear_SelectedIndexChanged);
//
// gbSelectOptions
//
this.gbSelectOptions.Controls.Add(this.rdoGrpDeptUnit);
this.gbSelectOptions.Controls.Add(this.rdoDeptGrp);
this.gbSelectOptions.Controls.Add(this.rdoAll);
this.gbSelectOptions.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F);
this.gbSelectOptions.Location = new System.Drawing.Point(1, 15);
this.gbSelectOptions.Name = "gbSelectOptions";
this.gbSelectOptions.Size = new System.Drawing.Size(513, 44);
this.gbSelectOptions.TabIndex = 229;
this.gbSelectOptions.TabStop = false;
//
// rdoGrpDeptUnit
//
this.rdoGrpDeptUnit.AutoSize = true;
this.rdoGrpDeptUnit.Font = new System.Drawing.Font("Georgia", 11F);
this.rdoGrpDeptUnit.ForeColor = System.Drawing.Color.Gray;
this.rdoGrpDeptUnit.Location = new System.Drawing.Point(271, 13);
this.rdoGrpDeptUnit.Name = "rdoGrpDeptUnit";
this.rdoGrpDeptUnit.Size = new System.Drawing.Size(215, 22);
this.rdoGrpDeptUnit.TabIndex = 2;
this.rdoGrpDeptUnit.TabStop = true;
this.rdoGrpDeptUnit.Text = " Group , Dept and Unit Wise";
this.rdoGrpDeptUnit.UseVisualStyleBackColor = true;
//
// rdoDeptGrp
//
this.rdoDeptGrp.AutoSize = true;
this.rdoDeptGrp.Font = new System.Drawing.Font("Georgia", 11F);
this.rdoDeptGrp.ForeColor = System.Drawing.Color.Gray;
this.rdoDeptGrp.Location = new System.Drawing.Point(99, 13);
this.rdoDeptGrp.Name = "rdoDeptGrp";
this.rdoDeptGrp.Size = new System.Drawing.Size(140, 22);
this.rdoDeptGrp.TabIndex = 1;
this.rdoDeptGrp.TabStop = true;
this.rdoDeptGrp.Text = "Dept Group Wise";
this.rdoDeptGrp.UseVisualStyleBackColor = true;
//
// rdoAll
//
this.rdoAll.AutoSize = true;
this.rdoAll.Font = new System.Drawing.Font("Georgia", 11F);
this.rdoAll.ForeColor = System.Drawing.Color.Gray;
this.rdoAll.Location = new System.Drawing.Point(20, 13);
this.rdoAll.Name = "rdoAll";
this.rdoAll.Size = new System.Drawing.Size(44, 22);
this.rdoAll.TabIndex = 0;
this.rdoAll.TabStop = true;
this.rdoAll.Text = "All";
this.rdoAll.UseVisualStyleBackColor = true;
//
// frmDepartmentWisePayroll
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.ClientSize = new System.Drawing.Size(1573, 886);
this.isEnterTabAllow = true;
this.Name = "frmDepartmentWisePayroll";
this.Load += new System.EventHandler(this.frmDepartmentWisePayroll_Load);
this.pnlMain.ResumeLayout(false);
this.pnlMain.PerformLayout();
this.pnlTop.ResumeLayout(false);
this.pnlTop.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dgvInfo)).EndInit();
this.gbSelectOptions.ResumeLayout(false);
this.gbSelectOptions.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private AtiqsControlLibrary.SmartComboBox cboDepartment;
private System.Windows.Forms.Button btnShow;
private AtiqsControlLibrary.SmartComboBox cboMonth;
private AtiqsControlLibrary.SmartDataGridView dgvInfo;
private AtiqsControlLibrary.SmartLabel smartLabel6;
private AtiqsControlLibrary.SmartComboBox cboDepartmentGroup;
private AtiqsControlLibrary.SmartLabel smartLabel22;
private AtiqsControlLibrary.SmartComboBox cboDepartmentType;
private AtiqsControlLibrary.SmartLabel smartLabel21;
private AtiqsControlLibrary.SmartLabel smartLabel4;
private AtiqsControlLibrary.SmartLabel smartLabel5;
private AtiqsControlLibrary.SmartComboBox cboUnit;
private AtiqsControlLibrary.SmartLabel smartLabel7;
private AtiqsControlLibrary.SmartComboBox cboYear;
private System.Windows.Forms.GroupBox gbSelectOptions;
private AtiqsControlLibrary.SmartRadioButton rdoGrpDeptUnit;
private AtiqsControlLibrary.SmartRadioButton rdoDeptGrp;
private AtiqsControlLibrary.SmartRadioButton rdoAll;
}
}
|
atiq-shumon/DotNetProjects
|
Hospital_ERP_VS13-WCF_WF/AH.ModuleController/UI/HR/Forms/frmDepartmentWisePayroll.Designer.cs
|
C#
|
apache-2.0
| 22,088
|
package net.smert.xkcdblueeyes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
* @author Jason Sorensen <sorensenj@smert.net>
*/
public class EyeColorGroups {
private final int maxNumberOfGroups;
private final List<EyeColor> eyeColors;
private final Map<Integer, EyeColor> valuesToEyeColors;
public EyeColorGroups(int maxNumberOfGroups) {
// There can be no more than the total number of eye colors
if (maxNumberOfGroups > Config.MAX_COLORS) {
maxNumberOfGroups = Config.MAX_COLORS;
}
this.maxNumberOfGroups = maxNumberOfGroups;
valuesToEyeColors = new HashMap<>();
eyeColors = new ArrayList<>();
mapValuesToEyeColors();
}
private void mapValuesToEyeColors() {
for (EyeColor type : EyeColor.values()) {
valuesToEyeColors.put(type.ordinal(), type);
}
}
public void createRandomEyeColors() {
// Cretea a set with random colors so each color can only be added once
Set<EyeColor> eyeColorsSet = new HashSet<>();
while (eyeColorsSet.size() < maxNumberOfGroups) {
int randomOrdinal = RandomInt.next(0, EyeColor.MAX_EYE_COLOR.ordinal() - 1);
EyeColor eyeColor = valuesToEyeColors.get(randomOrdinal);
if (eyeColor == null) {
throw new RuntimeException("Unknown ordinal for EyeColor: " + randomOrdinal);
}
eyeColorsSet.add(eyeColor); // This might not add a color each time since we only add unique values
}
// Add unique set of colors to the list
Iterator<EyeColor> iterator = eyeColorsSet.iterator();
while (iterator.hasNext()) {
EyeColor eyeColor = iterator.next();
eyeColors.add(eyeColor); // If we didnt use a set we would have duplicates
}
}
public List<EyeColor> getEyeColors() {
return eyeColors;
}
public EyeColor getRandomColor() {
assert (eyeColors.size() > 0);
int randomIndex = RandomInt.next(0, eyeColors.size() - 1);
return eyeColors.get(randomIndex);
}
public int getTotalEyeColors() {
return eyeColors.size();
}
}
|
kovertopz/XKCDBlueEyes
|
src/main/java/net/smert/xkcdblueeyes/EyeColorGroups.java
|
Java
|
apache-2.0
| 2,332
|
package org.reclipse.tracer.extensionpoints;
import java.io.OutputStream;
/**
* @author lowende
* @author Last editor: $Author: lowende $
* @version $Revision: 2356 $ $Date: 2006-06-01 14:04:30 +0200 (Do, 01 Jun 2006) $
*/
public interface IVMStreamReceiver
{
public OutputStream getOutputStream();
}
|
CloudScale-Project/StaticSpotter
|
plugins/org.reclipse.tracer/src/org/reclipse/tracer/extensionpoints/IVMStreamReceiver.java
|
Java
|
apache-2.0
| 331
|
<?PHP
App::uses('Model','Model');
class AdsUserPlan extends Model
{
public $useTable='ads_user_plan';
}
|
hasanmbstu13/Project
|
Cakephp/pikdish/admin/app/Model/AdsUserPlan.php
|
PHP
|
apache-2.0
| 113
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Data;
namespace CareOtter.ServiceFabricUtilities.AsyncEnumerable.Enumerators
{
public class AsyncSelectEnumerator<TValType,TResultType> : IAsyncEnumerator<TResultType>
{
private readonly IAsyncEnumerator<TValType> _parentEnumerator;
private readonly Func<TValType, TResultType> _selectFunc;
internal AsyncSelectEnumerator(IAsyncEnumerator<TValType> parentEnumerator, Func<TValType, TResultType> selectFunc)
{
_parentEnumerator = parentEnumerator;
_selectFunc = selectFunc;
}
public void Dispose()
{
_parentEnumerator.Dispose();
}
public Task<bool> MoveNextAsync(CancellationToken cancellationToken)
{
return _parentEnumerator.MoveNextAsync(cancellationToken);
}
public void Reset()
{
_parentEnumerator.Reset();
}
public TResultType Current => _selectFunc(_parentEnumerator.Current);
}
}
|
devCareOtter/CareOtter.ServiceFabricUtilities
|
CareOtter.ServiceFabricUtilities/AsyncEnumerable/Enumerators/AsyncSelectEnumerator.cs
|
C#
|
apache-2.0
| 1,086
|
/**
*
*/
/**
* @author adamf
*
*/
package org.ihtsdo.otf.security.util;
|
IHTSDO/OTF-User-Module
|
security/src/main/java/org/ihtsdo/otf/security/util/package-info.java
|
Java
|
apache-2.0
| 77
|
/**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2020 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.pnc.environment.openshift;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.io.JsonStringEncoder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.openshift.internal.restclient.model.Pod;
import com.openshift.internal.restclient.model.Route;
import com.openshift.internal.restclient.model.Service;
import com.openshift.internal.restclient.model.properties.ResourcePropertiesRegistry;
import com.openshift.restclient.ClientBuilder;
import com.openshift.restclient.IClient;
import com.openshift.restclient.NotFoundException;
import com.openshift.restclient.ResourceKind;
import com.openshift.restclient.model.IResource;
import org.apache.commons.lang.RandomStringUtils;
import org.jboss.dmr.ModelNode;
import org.jboss.pnc.common.json.moduleconfig.OpenshiftBuildAgentConfig;
import org.jboss.pnc.common.json.moduleconfig.OpenshiftEnvironmentDriverModuleConfig;
import org.jboss.pnc.common.logging.MDCUtils;
import org.jboss.pnc.common.monitor.CancellableCompletableFuture;
import org.jboss.pnc.common.monitor.PollingMonitor;
import org.jboss.pnc.common.util.RandomUtils;
import org.jboss.pnc.common.util.StringUtils;
import org.jboss.pnc.environment.openshift.exceptions.PodFailedStartException;
import org.jboss.pnc.pncmetrics.GaugeMetric;
import org.jboss.pnc.pncmetrics.MetricsConfiguration;
import org.jboss.pnc.spi.builddriver.DebugData;
import org.jboss.pnc.spi.environment.RunningEnvironment;
import org.jboss.pnc.spi.environment.StartedEnvironment;
import org.jboss.pnc.spi.repositorymanager.model.RepositorySession;
import org.jboss.util.StringPropertyReplacer;
import org.jboss.util.collection.ConcurrentSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
import java.util.regex.Pattern;
/**
* @author <a href="mailto:matejonnet@gmail.com">Matej Lazar</a>
*/
public class OpenshiftStartedEnvironment implements StartedEnvironment {
private static final Logger logger = LoggerFactory.getLogger(OpenshiftStartedEnvironment.class);
private static final String SSH_SERVICE_PORT_NAME = "2222-ssh";
private static final String POD_USERNAME = "worker";
private static final String POD_USER_PASSWD = "workerUserPassword";
private static final String OSE_API_VERSION = "v1";
private static final Pattern SECURE_LOG_PATTERN = Pattern
.compile("\"name\":\\s*\"accessToken\",\\s*\"value\":\\s*\"\\p{Print}+\"");
private static final String METRICS_POD_STARTED_KEY = "openshift-environment-driver.started.pod";
private static final String METRICS_POD_STARTED_ATTEMPTED_KEY = METRICS_POD_STARTED_KEY + ".attempts";
private static final String METRICS_POD_STARTED_SUCCESS_KEY = METRICS_POD_STARTED_KEY + ".success";
private static final String METRICS_POD_STARTED_FAILED_KEY = METRICS_POD_STARTED_KEY + ".failed";
private static final String METRICS_POD_STARTED_RETRY_KEY = METRICS_POD_STARTED_KEY + ".retries";
private static final String METRICS_POD_STARTED_FAILED_REASON_KEY = METRICS_POD_STARTED_KEY + ".failed_reason";
private static final int DEFAULT_CREATION_POD_RETRY = 1;
private int creationPodRetry;
/**
* From: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/
*
* ErrImagePull and ImagePullBackOff added to that list. The pod.getStatus() call will return the *reason* of
* failure, and if the reason is not available, then it'll return the regular status (as mentioned in the link)
*
* For pod creation, the failure reason we expect when docker registry is not behaving is 'ErrImagePull' or
* 'ImagePullBackOff'
*/
private static final String[] POD_FAILED_STATUSES = { "Failed", "Unknown", "CrashLoopBackOff", "ErrImagePull",
"ImagePullBackOff" };
/**
* Parameter specifying override for the builder pod memory size.
*/
private static final String BUILDER_POD_MEMORY = "BUILDER_POD_MEMORY";
private final IClient client;
private final RepositorySession repositorySession;
private final OpenshiftBuildAgentConfig openshiftBuildAgentConfig;
private final OpenshiftEnvironmentDriverModuleConfig environmentConfiguration;
private final PollingMonitor pollingMonitor;
private final String imageId;
private final DebugData debugData;
private final Map<String, String> environmetVariables;
private final ExecutorService executor;
private Optional<GaugeMetric> gaugeMetric = Optional.empty();
private Pod pod;
private Service service;
private Route route;
private Service sshService;
private ConcurrentSet<CompletableFuture<Void>> runningMonitors = new ConcurrentSet<>();
private String buildAgentContextPath;
private final boolean createRoute;
private Runnable cancelHook;
private boolean cancelRequested = false;
private CompletableFuture<Void> creatingPod;
private CompletableFuture<Void> creatingService;
private Optional<CompletableFuture<Void>> creatingRoute = Optional.empty();
// Used to track whether all the futures for creation are completed, or failed with an exception
private CompletableFuture<Void> openshiftDefinitions;
public OpenshiftStartedEnvironment(
ExecutorService executor,
OpenshiftBuildAgentConfig openshiftBuildAgentConfig,
OpenshiftEnvironmentDriverModuleConfig environmentConfiguration,
PollingMonitor pollingMonitor,
RepositorySession repositorySession,
String systemImageId,
DebugData debugData,
String accessToken,
boolean tempBuild,
Instant temporaryBuildExpireDate,
MetricsConfiguration metricsConfiguration,
Map<String, String> parameters) {
creationPodRetry = DEFAULT_CREATION_POD_RETRY;
if (environmentConfiguration.getCreationPodRetry() != null) {
try {
creationPodRetry = Integer.parseInt(environmentConfiguration.getCreationPodRetry());
} catch (NumberFormatException e) {
logger.error("Couldn't parse the value of creation pod retry from the configuration. Using default");
}
}
logger.info("Creating new build environment using image id: " + environmentConfiguration.getImageId());
this.executor = executor;
this.openshiftBuildAgentConfig = openshiftBuildAgentConfig;
this.environmentConfiguration = environmentConfiguration;
this.pollingMonitor = pollingMonitor;
this.repositorySession = repositorySession;
this.imageId = systemImageId == null ? environmentConfiguration.getImageId() : systemImageId;
this.debugData = debugData;
if (metricsConfiguration != null) {
this.gaugeMetric = Optional.of(metricsConfiguration.getGaugeMetric());
}
createRoute = environmentConfiguration.getExposeBuildAgentOnPublicUrl();
client = new ClientBuilder(environmentConfiguration.getRestEndpointUrl())
.usingToken(environmentConfiguration.getRestAuthToken())
.build();
client.getServerReadyStatus(); // make sure client is connected
environmetVariables = new HashMap<>();
final String buildAgentHost = environmentConfiguration.getBuildAgentHost();
String expiresDateStamp = Long.toString(temporaryBuildExpireDate.toEpochMilli());
Boolean proxyActive = !StringUtils.isEmpty(environmentConfiguration.getProxyServer())
&& !StringUtils.isEmpty(environmentConfiguration.getProxyPort());
environmetVariables.put("image", imageId);
environmetVariables
.put("firewallAllowedDestinations", environmentConfiguration.getFirewallAllowedDestinations());
// This property sent as Json
environmetVariables.put(
"allowedHttpOutgoingDestinations",
toEscapedJsonString(environmentConfiguration.getAllowedHttpOutgoingDestinations()));
environmetVariables.put("isHttpActive", proxyActive.toString().toLowerCase());
environmetVariables.put("proxyServer", environmentConfiguration.getProxyServer());
environmetVariables.put("proxyPort", environmentConfiguration.getProxyPort());
environmetVariables.put("nonProxyHosts", environmentConfiguration.getNonProxyHosts());
environmetVariables.put("AProxDependencyUrl", repositorySession.getConnectionInfo().getDependencyUrl());
environmetVariables.put("AProxDeployUrl", repositorySession.getConnectionInfo().getDeployUrl());
environmetVariables.put("build-agent-host", buildAgentHost);
environmetVariables.put("containerPort", environmentConfiguration.getContainerPort());
environmetVariables.put("buildContentId", repositorySession.getBuildRepositoryId());
environmetVariables.put("accessToken", accessToken);
environmetVariables.put("tempBuild", Boolean.toString(tempBuild));
environmetVariables.put("expiresDate", "ts" + expiresDateStamp);
MDCUtils.getUserId().ifPresent(v -> environmetVariables.put("logUserId", v));
MDCUtils.getProcessContext().ifPresent(v -> environmetVariables.put("logProcessContext", v));
environmetVariables.put("resourcesMemory", builderPodMemory(environmentConfiguration, parameters));
createEnvironment();
}
private void createEnvironment() {
String randString = RandomUtils.randString(6);// note the 24 char limit
buildAgentContextPath = "pnc-ba-" + randString;
// variables specific to to this pod (retry)
environmetVariables.put("pod-name", "pnc-ba-pod-" + randString);
environmetVariables.put("service-name", "pnc-ba-service-" + randString);
environmetVariables.put("ssh-service-name", "pnc-ba-ssh-" + randString);
environmetVariables.put("route-name", "pnc-ba-route-" + randString);
environmetVariables.put("route-path", "/" + buildAgentContextPath);
environmetVariables.put("buildAgentContextPath", "/" + buildAgentContextPath);
initDebug();
ModelNode podConfigurationNode = createModelNode(
Configurations.getContentAsString(Resource.PNC_BUILDER_POD, openshiftBuildAgentConfig),
environmetVariables);
pod = new Pod(
podConfigurationNode,
client,
ResourcePropertiesRegistry.getInstance().get(OSE_API_VERSION, ResourceKind.POD));
pod.setNamespace(environmentConfiguration.getPncNamespace());
Runnable createPod = () -> {
try {
client.create(pod, pod.getNamespace());
} catch (Throwable e) {
logger.error("Cannot create pod.", e);
throw e;
}
};
creatingPod = CompletableFuture.runAsync(createPod, executor);
ModelNode serviceConfigurationNode = createModelNode(
Configurations.getContentAsString(Resource.PNC_BUILDER_SERVICE, openshiftBuildAgentConfig),
environmetVariables);
service = new Service(
serviceConfigurationNode,
client,
ResourcePropertiesRegistry.getInstance().get(OSE_API_VERSION, ResourceKind.SERVICE));
service.setNamespace(environmentConfiguration.getPncNamespace());
Runnable createService = () -> {
try {
client.create(service, service.getNamespace());
} catch (Throwable e) {
logger.error("Cannot create service.", e);
throw e;
}
};
creatingService = CompletableFuture.runAsync(createService, executor);
if (createRoute) {
ModelNode routeConfigurationNode = createModelNode(
Configurations.getContentAsString(Resource.PNC_BUILDER_ROUTE, openshiftBuildAgentConfig),
environmetVariables);
route = new Route(
routeConfigurationNode,
client,
ResourcePropertiesRegistry.getInstance().get(OSE_API_VERSION, ResourceKind.ROUTE));
route.setNamespace(environmentConfiguration.getPncNamespace());
Runnable createRoute = () -> {
try {
client.create(route, route.getNamespace());
} catch (Throwable e) {
logger.error("Cannot create route.", e);
throw e;
}
};
CompletableFuture<Void> creatingRouteFuture = CompletableFuture.runAsync(createRoute, executor);
creatingRoute = Optional.of(creatingRouteFuture);
openshiftDefinitions = CompletableFuture.allOf(creatingPod, creatingService, creatingRouteFuture);
} else {
openshiftDefinitions = CompletableFuture.allOf(creatingPod, creatingService);
}
gaugeMetric.ifPresent(g -> g.incrementMetric(METRICS_POD_STARTED_ATTEMPTED_KEY));
}
private String builderPodMemory(
OpenshiftEnvironmentDriverModuleConfig environmentConfiguration1,
Map<String, String> parameters) {
double builderPodMemory = environmentConfiguration1.getBuilderPodMemory();
String builderPodMemoryOverride = parameters.get(BUILDER_POD_MEMORY);
if (builderPodMemoryOverride != null) {
try {
builderPodMemory = Double.parseDouble(builderPodMemoryOverride);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException(
"Failed to parse memory size '" + builderPodMemoryOverride + "' from " + BUILDER_POD_MEMORY
+ " parameter.",
ex);
}
logger.info("Using override for builder pod memory size: " + builderPodMemoryOverride);
}
return ((int) Math.ceil(builderPodMemory * 1024)) + "Mi";
}
static String secureLog(String message) {
return SECURE_LOG_PATTERN.matcher(message)
.replaceAll("\"name\": \"accessToken\",\n" + " \"value\": \"***\"");
}
private void initDebug() {
if (debugData.isEnableDebugOnFailure()) {
String password = RandomStringUtils.randomAlphanumeric(10);
debugData.setSshPassword(password);
environmetVariables.put(POD_USER_PASSWD, password);
debugData.setSshServiceInitializer(d -> {
Integer port = startSshService();
d.setSshCommand("ssh " + POD_USERNAME + "@" + route.getHost() + " -p " + port);
});
}
}
private ModelNode createModelNode(String resourceDefinition, Map<String, String> runtimeProperties) {
Properties properties = new Properties();
properties.putAll(runtimeProperties);
String definition = StringPropertyReplacer.replaceProperties(resourceDefinition, properties);
if (logger.isTraceEnabled()) {
logger.trace("Node definition: " + secureLog(definition));
}
return ModelNode.fromJSONString(definition);
}
/**
* Method to retry creating the whole Openshift environment in case of failure
*
* @param onComplete consumer to call if successful
* @param onError consumer to call if no more retries
* @param retries how many times will we retry starting the build environment
*/
private void retryEnvironment(Consumer<RunningEnvironment> onComplete, Consumer<Exception> onError, int retries) {
gaugeMetric.ifPresent(g -> g.incrementMetric(METRICS_POD_STARTED_FAILED_KEY));
gaugeMetric.ifPresent(g -> g.incrementMetric(METRICS_POD_STARTED_RETRY_KEY));
// since deletion runs in an executor, it might run *after* the createEnvironment() is finished.
// createEnvironment() will overwrite the Openshift object fields. So we need to capture the existing
// openshift objects to delete before they get overwritten by createEnvironment()
Route routeToDestroy = route;
Service serviceToDestroy = service;
Service sshServiceToDestroy = sshService;
Pod podToDestroy = pod;
executor.submit(() -> {
try {
logger.debug("Destroying old build environment");
destroyEnvironment(routeToDestroy, serviceToDestroy, sshServiceToDestroy, podToDestroy, true);
} catch (Exception ex) {
logger.error("Error deleting previous environment", ex);
}
});
logger.debug("Creating new build environment");
createEnvironment();
// restart the process again
monitorInitialization(onComplete, onError, retries - 1);
// at this point the running task running this is finished. New ones are created to monitor pod /service/route
// creation
}
/**
* Call stack: monitorInitialization: -> setup monitors, track them and return
*
* -> pollingMonitor.monitor(<pod>) [in background] -> Success: signal via executing onComplete consumer finish ->
* Failure: call retryPod consumer -> if retries == 0: call onError consumer. no more retries -> else: cancel and
* clear monitors, delete existing build environment (if any), recreate build environment, call
* monitorInitialization again with retries decremented finish
*
* While the call stack may appear recursive, it's not in fact recursive due to the fact that we are using
* RunningTask to figure out if the pod / route /service are online or not and they run in the background
*/
@Override
public void monitorInitialization(Consumer<RunningEnvironment> onComplete, Consumer<Exception> onError) {
monitorInitialization(onComplete, onError, creationPodRetry);
}
/**
* retries is decremented in retryPod in case of pod failing to start
*
* @param onComplete
* @param onError
* @param retries
*/
private void monitorInitialization(
Consumer<RunningEnvironment> onComplete,
Consumer<Exception> onError,
int retries) {
URL buildAgentUrl;
try {
buildAgentUrl = new URL(getInternalEndpointUrl());
} catch (MalformedURLException e) {
onError.accept(e);
return;
}
cancelHook = () -> onComplete.accept(null);
CompletableFuture<Void> podFuture = creatingPod.thenComposeAsync(nul -> {
CancellableCompletableFuture<Void> monitor = pollingMonitor.monitor(() -> isPodRunning());
addFuture(monitor);
return monitor;
}, executor);
CompletableFuture<Void> serviceFuture = creatingService.thenComposeAsync(nul -> {
CancellableCompletableFuture<Void> monitor = pollingMonitor.monitor(() -> isServiceRunning());
addFuture(monitor);
return monitor;
}, executor);
CompletableFuture<Void> routeFuture;
if (creatingRoute.isPresent()) {
routeFuture = creatingRoute.get().thenComposeAsync(nul -> {
CancellableCompletableFuture<Void> monitor = pollingMonitor.monitor(() -> isRouteRunning());
addFuture(monitor);
return monitor;
}, executor);
} else {
routeFuture = CompletableFuture.completedFuture(null);
}
CompletableFuture<Void> openshiftDefinitionsError = new CompletableFuture<>();
openshiftDefinitions.exceptionally(t -> {
openshiftDefinitionsError.completeExceptionally(t);
return null;
});
CancellableCompletableFuture<Void> isBuildAgentUpFuture = pollingMonitor
.monitor(() -> isServletAvailable(buildAgentUrl));
addFuture(isBuildAgentUpFuture);
CompletableFuture<RunningEnvironment> runningEnvironmentFuture = CompletableFuture
.allOf(podFuture, serviceFuture, routeFuture)
.thenApplyAsync(nul -> isBuildAgentUpFuture)
.thenApplyAsync(
nul -> RunningEnvironment.createInstance(
pod.getName(),
Integer.parseInt(environmentConfiguration.getContainerPort()),
route.getHost(),
getPublicEndpointUrl(),
getInternalEndpointUrl(),
repositorySession,
Paths.get(environmentConfiguration.getWorkingDirectory()),
this::destroyEnvironment,
debugData),
executor);
CompletableFuture.anyOf(runningEnvironmentFuture, openshiftDefinitionsError)
.handle((runningEnvironment, throwable) -> {
if (throwable != null) {
cancelAndClearMonitors();
// no more retries, execute the onError consumer
if (retries == 0) {
onError.accept(new Exception(throwable));
} else {
logger.error("Creating build environment failed! Retrying...", throwable);
retryEnvironment(onComplete, onError, retries);
}
} else {
logger.info(
"Environment successfully initialized. Pod [{}]; Service [{}].",
pod.getName(),
service.getName());
onComplete.accept((RunningEnvironment) runningEnvironment); // openshiftDefinitionsError
// completes only with error
}
gaugeMetric.ifPresent(g -> g.incrementMetric(METRICS_POD_STARTED_SUCCESS_KEY));
return null;
});
logger.info("Waiting to initialize environment. Pod [{}]; Service [{}].", pod.getName(), service.getName());
}
private void addFuture(CancellableCompletableFuture<Void> future) {
runningMonitors.add(future);
}
private void cancelAndClearMonitors() {
logger.debug("Cancelling existing monitors for this build environment");
runningMonitors.stream().forEach(f -> f.cancel(false));
runningMonitors.clear();
}
private boolean isServletAvailable(URL servletUrl) {
try {
return connectToPingUrl(servletUrl);
} catch (IOException e) {
return false;
}
}
private String getPublicEndpointUrl() {
if (createRoute) {
return "http://" + route.getHost() + "" + route.getPath() + "/"
+ environmentConfiguration.getBuildAgentBindPath();
} else {
return getInternalEndpointUrl();
}
}
private String getInternalEndpointUrl() {
return "http://" + service.getClusterIP() + "/" + buildAgentContextPath + "/"
+ environmentConfiguration.getBuildAgentBindPath();
}
/**
* Check if pod is in running state. If pod is in one of the failure statuses (as specified in POD_FAILED_STATUSES,
* PodFailedStartException is thrown
*
* @return boolean: is pod running?
*/
private boolean isPodRunning() {
pod = client.get(pod.getKind(), pod.getName(), environmentConfiguration.getPncNamespace());
String podStatus = pod.getStatus();
logger.debug("Pod {} status: {}", pod.getName(), podStatus);
if (Arrays.asList(POD_FAILED_STATUSES).contains(podStatus)) {
gaugeMetric.ifPresent(g -> g.incrementMetric(METRICS_POD_STARTED_FAILED_REASON_KEY + "." + podStatus));
throw new PodFailedStartException("Pod failed with status: " + podStatus);
}
boolean isRunning = "Running".equals(pod.getStatus());
if (isRunning) {
logger.debug("Pod {} running.", pod.getName());
return true;
}
return false;
}
private boolean isServiceRunning() {
service = client.get(service.getKind(), service.getName(), environmentConfiguration.getPncNamespace());
boolean isRunning = service.getPods().size() > 0;
if (isRunning) {
logger.debug("Service {} running.", service.getName());
return true;
}
return false;
}
private boolean isRouteRunning() {
try {
if (connectToPingUrl(new URL(getPublicEndpointUrl()))) {
route = client.get(route.getKind(), route.getName(), environmentConfiguration.getPncNamespace());
logger.debug("Route {} running.", route.getName());
return true;
} else {
return false;
}
} catch (IOException e) {
logger.error("Cannot open URL " + getPublicEndpointUrl(), e);
return false;
}
}
@Override
public String getId() {
return pod.getName();
}
@Override
public void cancel() {
cancelRequested = true;
creatingPod.cancel(false);
creatingService.cancel(false);
creatingRoute.ifPresent(f -> f.cancel(false));
cancelAndClearMonitors();
if (cancelHook != null) {
cancelHook.run();
} else {
logger.warn("Trying to cancel operation while no cancel hook is defined.");
}
destroyEnvironment();
}
@Override
public void destroyEnvironment() {
destroyEnvironment(route, service, sshService, pod, false);
}
private void destroyEnvironment(
Route routeLocal,
Service serviceLocal,
Service sshServiceLocal,
Pod podLocal,
boolean force) {
if (!debugData.isDebugEnabled() || force) {
if (!environmentConfiguration.getKeepBuildAgentInstance()) {
if (createRoute) {
tryOpenshiftDeleteResource(routeLocal);
}
tryOpenshiftDeleteResource(serviceLocal);
if (sshService != null) {
tryOpenshiftDeleteResource(sshServiceLocal);
}
tryOpenshiftDeleteResource(podLocal);
}
}
}
/**
* Try to delete an openshift resource. If it doesn't exist, it's fine
*
* @param resource Openshift resource to delete
* @param <T>
*/
private <T extends IResource> void tryOpenshiftDeleteResource(T resource) {
try {
client.delete(resource);
} catch (NotFoundException e) {
logger.warn("Couldn't delete the Openshift resource since it does not exist", e);
}
}
/**
* Enable ssh forwarding
*
* @return port, to which ssh is forwarded
*/
private Integer startSshService() {
ModelNode serviceConfigurationNode = createModelNode(
Configurations.getContentAsString(Resource.PNC_BUILDER_SSH_SERVICE, openshiftBuildAgentConfig),
environmetVariables);
sshService = new Service(
serviceConfigurationNode,
client,
ResourcePropertiesRegistry.getInstance().get(OSE_API_VERSION, ResourceKind.SERVICE));
sshService.setNamespace(environmentConfiguration.getPncNamespace());
try {
Service resultService = client.create(this.sshService, sshService.getNamespace());
return resultService.getNode()
.get("spec")
.get("ports")
.asList()
.stream()
.filter(m -> m.get("name").asString().equals(SSH_SERVICE_PORT_NAME))
.findAny()
.orElseThrow(
() -> new RuntimeException(
"No ssh service in response! Service data: " + describeService(resultService)))
.get("nodePort")
.asInt();
} catch (Throwable e) {
logger.error("Cannot create service.", e);
return null;
}
}
private String describeService(Service resultService) {
if (resultService == null)
return null;
ModelNode node = resultService.getNode();
return "Service[" + "name = " + resultService.getName() + ", node= '"
+ (node == null ? null : node.toJSONString(false)) + "]";
}
private boolean connectToPingUrl(URL url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(500);
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
int responseCode = connection.getResponseCode();
connection.disconnect();
logger.debug("Got {} from {}.", responseCode, url);
return responseCode == 200;
}
/**
* Return an escaped string of the JSON representation of the object
*
* By 'escaped', it means that strings like '"' are escaped to '\"'
*
* @param object object to marshall
* @return Escaped Json String
*/
private String toEscapedJsonString(Object object) {
ObjectMapper mapper = new ObjectMapper();
JsonStringEncoder jsonStringEncoder = JsonStringEncoder.getInstance();
try {
return new String(jsonStringEncoder.quoteAsString(mapper.writeValueAsString(object)));
} catch (JsonProcessingException e) {
logger.error("Could not parse object: " + object, e);
throw new RuntimeException(e);
}
}
}
|
matedo1/pnc
|
openshift-environment-driver/src/main/java/org/jboss/pnc/environment/openshift/OpenshiftStartedEnvironment.java
|
Java
|
apache-2.0
| 31,187
|
/* ==========================================
* Laverca Project
* https://sourceforge.net/projects/laverca/
* ==========================================
* Copyright 2015 Laverca Project
*
* 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 fi.laverca.mss;
public class MssException extends Exception {
private static final long serialVersionUID = 1L;
private String statusCode;
private String statusMessage;
public MssException(final String msg) {
super(msg);
}
public MssException(final Throwable t) {
super(t);
}
public void setStatusCode(final String statusCode) {
this.statusCode = statusCode;
}
public void setStatusMessage(final String statusMessage) {
this.statusMessage = statusMessage;
}
public String getStatusMessage() {
return this.statusMessage;
}
public String getStatusCode() {
return this.statusCode;
}
}
|
laverca/laverca
|
src/core/fi/laverca/mss/MssException.java
|
Java
|
apache-2.0
| 1,484
|
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2016.09.10 um 03:14:29 AM CEST
//
package com.laegler.microservice.adapter.lib.javaee.v7;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
*
*
* This type is a general type that can be used to declare
* parameter/value lists.
*
*
*
* <p>Java-Klasse für param-valueType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="param-valueType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="description" type="{http://xmlns.jcp.org/xml/ns/javaee}descriptionType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="param-name" type="{http://xmlns.jcp.org/xml/ns/javaee}string"/>
* <element name="param-value" type="{http://xmlns.jcp.org/xml/ns/javaee}xsdStringType"/>
* </sequence>
* <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "param-valueType", propOrder = {
"description",
"paramName",
"paramValue"
})
public class ParamValueType {
protected List<DescriptionType> description;
@XmlElement(name = "param-name", required = true)
protected com.laegler.microservice.adapter.lib.javaee.v7.String paramName;
@XmlElement(name = "param-value", required = true)
protected XsdStringType paramValue;
@XmlAttribute(name = "id")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
@XmlSchemaType(name = "ID")
protected java.lang.String id;
/**
* Gets the value of the description property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the description property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDescription().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DescriptionType }
*
*
*/
public List<DescriptionType> getDescription() {
if (description == null) {
description = new ArrayList<DescriptionType>();
}
return this.description;
}
/**
* Ruft den Wert der paramName-Eigenschaft ab.
*
* @return
* possible object is
* {@link com.laegler.microservice.adapter.lib.javaee.v7.String }
*
*/
public com.laegler.microservice.adapter.lib.javaee.v7.String getParamName() {
return paramName;
}
/**
* Legt den Wert der paramName-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link com.laegler.microservice.adapter.lib.javaee.v7.String }
*
*/
public void setParamName(com.laegler.microservice.adapter.lib.javaee.v7.String value) {
this.paramName = value;
}
/**
* Ruft den Wert der paramValue-Eigenschaft ab.
*
* @return
* possible object is
* {@link XsdStringType }
*
*/
public XsdStringType getParamValue() {
return paramValue;
}
/**
* Legt den Wert der paramValue-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link XsdStringType }
*
*/
public void setParamValue(XsdStringType value) {
this.paramValue = value;
}
/**
* Ruft den Wert der id-Eigenschaft ab.
*
* @return
* possible object is
* {@link java.lang.String }
*
*/
public java.lang.String getId() {
return id;
}
/**
* Legt den Wert der id-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link java.lang.String }
*
*/
public void setId(java.lang.String value) {
this.id = value;
}
}
|
thlaegler/microservice
|
microservice-adapter/src/main/java/com/laegler/microservice/adapter/lib/javaee/v7/ParamValueType.java
|
Java
|
apache-2.0
| 5,028
|
package com.zed.livetales;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
/**
* Created by jemalpartida on 06/10/2016.
*/
public class SplashScreenActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate( savedInstanceState );
setContentView( R.layout.splash );
Thread timerThread = new Thread()
{
public void run()
{
try
{
sleep(3000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
finally
{
Intent intent = new Intent( SplashScreenActivity.this, Main2Activity.class );
startActivity(intent);
finish();
}
}
};
timerThread.start();
}
@Override
protected void onPause()
{
super.onPause();
finish();
}
}
|
pyromobile/nubomedia-ouatclient-src
|
android/LiveTales/app/src/main/java/com/zed/livetales/SplashScreenActivity.java
|
Java
|
apache-2.0
| 1,084
|
package com.communote.server.model.attachment;
/**
* @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a>
*/
public class AttachmentStatus implements java.io.Serializable {
/**
* The serial version UID of this class. Needed for serialization.
*/
private static final long serialVersionUID = 2785954006304016699L;
/**
* <p>
* The attachment has been uploaded but not assigned to a note yet.
* </p>
*/
public static final AttachmentStatus UPLOADED = new AttachmentStatus("UPLOADED");
/**
* <p>
* The attachment has been published and assigned to a note.
* </p>
*/
public static final AttachmentStatus PUBLISHED = new AttachmentStatus("PUBLISHED");
/**
* <p>
* The note of the attachment has been deleted or will be. Have this attachment and the
* associated file be deleted as well.
* </p>
*/
public static final AttachmentStatus MARKED_FOR_DELETION = new AttachmentStatus(
"MARKED_FOR_DELETION");
private static final java.util.Map<String, AttachmentStatus> values = new java.util.HashMap<String, AttachmentStatus>(
3, 1);
private static java.util.List<String> literals = new java.util.ArrayList<String>(3);
private static java.util.List<String> names = new java.util.ArrayList<String>(3);
/**
* Initializes the values.
*/
static {
values.put(UPLOADED.value, UPLOADED);
literals.add(UPLOADED.value);
names.add("UPLOADED");
values.put(PUBLISHED.value, PUBLISHED);
literals.add(PUBLISHED.value);
names.add("PUBLISHED");
values.put(MARKED_FOR_DELETION.value, MARKED_FOR_DELETION);
literals.add(MARKED_FOR_DELETION.value);
names.add("MARKED_FOR_DELETION");
literals = java.util.Collections.unmodifiableList(literals);
names = java.util.Collections.unmodifiableList(names);
}
/**
* Creates an instance of AttachmentStatus from <code>value</code>.
*
* @param value
* the value to create the AttachmentStatus from.
*/
public static AttachmentStatus fromString(String value) {
final AttachmentStatus typeValue = values.get(value);
if (typeValue == null) {
throw new IllegalArgumentException("invalid value '" + value
+ "', possible values are: " + literals);
}
return typeValue;
}
/**
* Returns an unmodifiable list containing the literals that are known by this enumeration.
*
* @return A List containing the actual literals defined by this enumeration, this list can not
* be modified.
*/
public static java.util.List<String> literals() {
return literals;
}
/**
* Returns an unmodifiable list containing the names of the literals that are known by this
* enumeration.
*
* @return A List containing the actual names of the literals defined by this enumeration, this
* list can not be modified.
*/
public static java.util.List<String> names() {
return names;
}
private String value;
/**
* The default constructor allowing super classes to access it.
*/
protected AttachmentStatus() {
}
private AttachmentStatus(String value) {
this.value = value;
}
/**
* @see Comparable#compareTo(Object)
*/
public int compareTo(Object that) {
return (this == that) ? 0 : this.getValue().compareTo(((AttachmentStatus) that).getValue());
}
/**
* @see Object#equals(Object)
*/
public boolean equals(Object object) {
return (this == object)
|| (object instanceof AttachmentStatus && ((AttachmentStatus) object).getValue()
.equals(this.getValue()));
}
/**
* Gets the underlying value of this type safe enumeration.
*
* @return the underlying value.
*/
public String getValue() {
return this.value;
}
/**
* @see Object#hashCode()
*/
public int hashCode() {
return this.getValue().hashCode();
}
/**
* This method allows the deserialization of an instance of this enumeration type to return the
* actual instance that will be the singleton for the JVM in which the current thread is
* running.
* <p/>
* Doing this will allow users to safely use the equality operator <code>==</code> for
* enumerations because a regular deserialized object is always a newly constructed instance and
* will therefore never be an existing reference; it is this <code>readResolve()</code> method
* which will intercept the deserialization process in order to return the proper singleton
* reference.
* <p/>
* This method is documented here: <a
* href="http://java.sun.com/j2se/1.3/docs/guide/serialization/spec/input.doc6.html">Java Object
* Serialization Specification</a>
*/
private Object readResolve() throws java.io.ObjectStreamException {
return AttachmentStatus.fromString(this.value);
}
/**
* @see Object#toString()
*/
public String toString() {
return String.valueOf(value);
}
}
|
Communote/communote-server
|
communote/api/src/main/java/com/communote/server/model/attachment/AttachmentStatus.java
|
Java
|
apache-2.0
| 5,302
|
/* $NetBSD: xlint.c,v 1.44 2011/09/18 09:07:35 njoly Exp $ */
/*
* Copyright (c) 1996 Christopher G. Demetriou. All Rights Reserved.
* Copyright (c) 1994, 1995 Jochen Pohl
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Jochen Pohl for
* The NetBSD Project.
* 4. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if HAVE_NBTOOL_CONFIG_H
#include "nbtool_config.h"
#endif
#include <sys/cdefs.h>
#if defined(__RCSID) && !defined(lint)
__RCSID("$NetBSD: xlint.c,v 1.44 2011/09/18 09:07:35 njoly Exp $");
#endif
#include <sys/param.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <errno.h>
#include <fcntl.h>
#include <paths.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <util.h>
#include "lint.h"
#include "pathnames.h"
#include "findcc.h"
#define DEFAULT_PATH _PATH_DEFPATH
int main(int, char *[]);
/* directory for temporary files */
static const char *tmpdir;
/* path name for cpp output */
static char *cppout;
/* file descriptor for cpp output */
static int cppoutfd = -1;
/* files created by 1st pass */
static char **p1out;
/* input files for 2nd pass (without libraries) */
static char **p2in;
/* library which will be created by 2nd pass */
static char *p2out;
/* flags always passed to cc(1) */
static char **cflags;
/* flags for cc(1), controled by sflag/tflag */
static char **lcflags;
/* flags for lint1 */
static char **l1flags;
/* flags for lint2 */
static char **l2flags;
/* libraries for lint2 */
static char **l2libs;
/* default libraries */
static char **deflibs;
/* additional libraries */
static char **libs;
/* search path for libraries */
static char **libsrchpath;
static char *libexec_path;
/* flags */
static int iflag, oflag, Cflag, sflag, tflag, Fflag, dflag, Bflag, Sflag;
/* print the commands executed to run the stages of compilation */
static int Vflag;
/* filename for oflag */
static char *outputfn;
/* reset after first .c source has been processed */
static int first = 1;
/*
* name of a file which is currently written by a child and should
* be removed after abnormal termination of the child
*/
static const char *currfn;
#if !defined(TARGET_PREFIX)
#define TARGET_PREFIX ""
#endif
static const char target_prefix[] = TARGET_PREFIX;
static void appstrg(char ***, char *);
static void appcstrg(char ***, const char *);
static void applst(char ***, char *const *);
static void freelst(char ***);
static char *concat2(const char *, const char *);
static char *concat3(const char *, const char *, const char *);
static void terminate(int) __attribute__((__noreturn__));
static const char *lbasename(const char *, int);
static void appdef(char ***, const char *);
static void usage(void);
static void fname(const char *);
static void runchild(const char *, char *const *, const char *, int);
static void findlibs(char *const *);
static int rdok(const char *);
static void lint2(void);
static void cat(char *const *, const char *);
/*
* Some functions to deal with lists of strings.
* Take care that we get no surprises in case of asynchronous signals.
*/
static void
appstrg(char ***lstp, char *s)
{
char **lst, **olst;
int i;
olst = *lstp;
for (i = 0; olst[i] != NULL; i++)
continue;
lst = xrealloc(olst, (i + 2) * sizeof (char *));
lst[i] = s;
lst[i + 1] = NULL;
*lstp = lst;
}
static void
appcstrg(char ***lstp, const char *s)
{
appstrg(lstp, xstrdup(s));
}
static void
applst(char ***destp, char *const *src)
{
int i, k;
char **dest, **odest;
odest = *destp;
for (i = 0; odest[i] != NULL; i++)
continue;
for (k = 0; src[k] != NULL; k++)
continue;
dest = xrealloc(odest, (i + k + 1) * sizeof (char *));
for (k = 0; src[k] != NULL; k++)
dest[i + k] = xstrdup(src[k]);
dest[i + k] = NULL;
*destp = dest;
}
static void
freelst(char ***lstp)
{
char *s;
int i;
for (i = 0; (*lstp)[i] != NULL; i++)
continue;
while (i-- > 0) {
s = (*lstp)[i];
(*lstp)[i] = NULL;
free(s);
}
}
static char *
concat2(const char *s1, const char *s2)
{
char *s;
s = xmalloc(strlen(s1) + strlen(s2) + 1);
(void)strcpy(s, s1);
(void)strcat(s, s2);
return (s);
}
static char *
concat3(const char *s1, const char *s2, const char *s3)
{
char *s;
s = xmalloc(strlen(s1) + strlen(s2) + strlen(s3) + 1);
(void)strcpy(s, s1);
(void)strcat(s, s2);
(void)strcat(s, s3);
return (s);
}
/*
* Clean up after a signal.
*/
static void
terminate(int signo)
{
int i;
if (cppoutfd != -1)
(void)close(cppoutfd);
if (cppout != NULL)
(void)remove(cppout);
if (p1out != NULL) {
for (i = 0; p1out[i] != NULL; i++)
(void)remove(p1out[i]);
}
if (p2out != NULL)
(void)remove(p2out);
if (currfn != NULL)
(void)remove(currfn);
if (signo != 0)
(void)raise_default_signal(signo);
exit(signo != 0 ? 1 : 0);
}
/*
* Returns a pointer to the last component of strg after delim.
* Returns strg if the string does not contain delim.
*/
static const char *
lbasename(const char *strg, int delim)
{
const char *cp, *cp1, *cp2;
cp = cp1 = cp2 = strg;
while (*cp != '\0') {
if (*cp++ == delim) {
cp2 = cp1;
cp1 = cp;
}
}
return (*cp1 == '\0' ? cp2 : cp1);
}
static void
appdef(char ***lstp, const char *def)
{
appstrg(lstp, concat2("-D__", def));
appstrg(lstp, concat3("-D__", def, "__"));
}
static void
usage(void)
{
(void)fprintf(stderr,
"Usage: %s [-abceghprvwxzHFS] [-s|-t] [-i|-nu] [-Dname[=def]]"
" [-Uname] [-X <id>[,<id>]...\n", getprogname());
(void)fprintf(stderr,
"\t[-Idirectory] [-Ldirectory] [-llibrary] [-ooutputfile]"
" file...\n");
(void)fprintf(stderr,
" %s [-abceghprvwzHFS] [|-s|-t] -Clibrary [-Dname[=def]]\n"
" [-X <id>[,<id>]...\n", getprogname());
(void)fprintf(stderr, "\t[-Idirectory] [-Uname] [-Bpath] file"
" ...\n");
terminate(-1);
}
int
main(int argc, char *argv[])
{
int c;
char flgbuf[3], *tmp;
size_t len;
const char *ks;
setprogname(argv[0]);
if ((tmp = getenv("TMPDIR")) == NULL || (len = strlen(tmp)) == 0) {
tmpdir = xstrdup(_PATH_TMP);
} else {
char *p = xmalloc(len + 2);
(void)sprintf(p, "%s%s", tmp, tmp[len - 1] == '/' ? "" : "/");
tmpdir = p;
}
cppout = xmalloc(strlen(tmpdir) + sizeof ("lint0.XXXXXX"));
(void)sprintf(cppout, "%slint0.XXXXXX", tmpdir);
cppoutfd = mkstemp(cppout);
if (cppoutfd == -1) {
warn("can't make temp");
terminate(-1);
}
p1out = xcalloc(1, sizeof (char *));
p2in = xcalloc(1, sizeof (char *));
cflags = xcalloc(1, sizeof (char *));
lcflags = xcalloc(1, sizeof (char *));
l1flags = xcalloc(1, sizeof (char *));
l2flags = xcalloc(1, sizeof (char *));
l2libs = xcalloc(1, sizeof (char *));
deflibs = xcalloc(1, sizeof (char *));
libs = xcalloc(1, sizeof (char *));
libsrchpath = xcalloc(1, sizeof (char *));
appcstrg(&cflags, "-E");
appcstrg(&cflags, "-x");
appcstrg(&cflags, "c");
#if 0
appcstrg(&cflags, "-D__attribute__(x)=");
appcstrg(&cflags, "-D__extension__(x)=/*NOSTRICT*/0");
#else
appcstrg(&cflags, "-U__GNUC__");
appcstrg(&cflags, "-U__PCC__");
#endif
#if 0
appcstrg(&cflags, "-Wp,-$");
#endif
appcstrg(&cflags, "-Wp,-CC");
appcstrg(&cflags, "-Wcomment");
appcstrg(&cflags, "-D__LINT__");
appcstrg(&cflags, "-Dlint"); /* XXX don't def. with -s */
appdef(&cflags, "lint");
appcstrg(&deflibs, "c");
if (signal(SIGHUP, terminate) == SIG_IGN)
(void)signal(SIGHUP, SIG_IGN);
(void)signal(SIGINT, terminate);
(void)signal(SIGQUIT, terminate);
(void)signal(SIGTERM, terminate);
while ((c = getopt(argc, argv, "abcd:eghil:no:prstuvwxzB:C:D:FHI:L:M:PSU:VX:")) != -1) {
switch (c) {
case 'a':
case 'b':
case 'c':
case 'e':
case 'g':
case 'r':
case 'v':
case 'w':
case 'z':
(void)sprintf(flgbuf, "-%c", c);
appcstrg(&l1flags, flgbuf);
break;
case 'F':
Fflag = 1;
/* FALLTHROUGH */
case 'u':
case 'h':
(void)sprintf(flgbuf, "-%c", c);
appcstrg(&l1flags, flgbuf);
appcstrg(&l2flags, flgbuf);
break;
case 'X':
(void)sprintf(flgbuf, "-%c", c);
appcstrg(&l1flags, flgbuf);
appcstrg(&l1flags, optarg);
break;
case 'i':
if (Cflag)
usage();
iflag = 1;
break;
case 'n':
freelst(&deflibs);
break;
case 'p':
appcstrg(&l1flags, "-p");
appcstrg(&l2flags, "-p");
if (*deflibs != NULL) {
freelst(&deflibs);
appcstrg(&deflibs, "c");
}
break;
case 'P':
appcstrg(&l1flags, "-P");
break;
case 's':
if (tflag)
usage();
freelst(&lcflags);
appcstrg(&lcflags, "-trigraphs");
appcstrg(&lcflags, "-Wtrigraphs");
appcstrg(&lcflags, "-pedantic");
appcstrg(&lcflags, "-D__STRICT_ANSI__");
appcstrg(&l1flags, "-s");
appcstrg(&l2flags, "-s");
sflag = 1;
break;
case 'S':
if (tflag)
usage();
appcstrg(&l1flags, "-S");
Sflag = 1;
break;
#if ! HAVE_NBTOOL_CONFIG_H
case 't':
if (sflag)
usage();
freelst(&lcflags);
appcstrg(&lcflags, "-traditional");
appcstrg(&lcflags, "-Wtraditional");
appstrg(&lcflags, concat2("-D", MACHINE));
appstrg(&lcflags, concat2("-D", MACHINE_ARCH));
appcstrg(&l1flags, "-t");
appcstrg(&l2flags, "-t");
tflag = 1;
break;
#endif
case 'x':
appcstrg(&l2flags, "-x");
break;
case 'C':
if (Cflag || oflag || iflag)
usage();
Cflag = 1;
appstrg(&l2flags, concat2("-C", optarg));
p2out = xmalloc(sizeof ("llib-l.ln") + strlen(optarg));
(void)sprintf(p2out, "llib-l%s.ln", optarg);
freelst(&deflibs);
break;
case 'd':
if (dflag)
usage();
dflag = 1;
appcstrg(&cflags, "-nostdinc");
appcstrg(&cflags, "-isystem");
appcstrg(&cflags, optarg);
break;
case 'D':
case 'I':
case 'M':
case 'U':
(void)sprintf(flgbuf, "-%c", c);
appstrg(&cflags, concat2(flgbuf, optarg));
break;
case 'l':
appcstrg(&libs, optarg);
break;
case 'o':
if (Cflag || oflag)
usage();
oflag = 1;
outputfn = xstrdup(optarg);
break;
case 'L':
appcstrg(&libsrchpath, optarg);
break;
case 'H':
appcstrg(&l2flags, "-H");
break;
case 'B':
Bflag = 1;
libexec_path = xstrdup(optarg);
break;
case 'V':
Vflag = 1;
break;
default:
usage();
/* NOTREACHED */
}
}
argc -= optind;
argv += optind;
/*
* To avoid modifying getopt(3)'s state engine midstream, we
* explicitly accept just a few options after the first source file.
*
* In particular, only -l<lib> and -L<libdir> (and these with a space
* after -l or -L) are allowed.
*/
while (argc > 0) {
const char *arg = argv[0];
if (arg[0] == '-') {
char ***list;
list = NULL; /* XXXGCC -Wuninitialized */
/* option */
switch (arg[1]) {
case 'l':
list = &libs;
break;
case 'L':
list = &libsrchpath;
break;
default:
usage();
/* NOTREACHED */
}
if (arg[2])
appcstrg(list, arg + 2);
else if (argc > 1) {
argc--;
appcstrg(list, *++argv);
} else
usage();
} else {
/* filename */
fname(arg);
first = 0;
}
argc--;
argv++;
}
if (first)
usage();
if (iflag)
terminate(0);
if (!oflag) {
if ((ks = getenv("LIBDIR")) == NULL || strlen(ks) == 0)
ks = PATH_LINTLIB;
appcstrg(&libsrchpath, ks);
findlibs(libs);
findlibs(deflibs);
}
(void)printf("Lint pass2:\n");
lint2();
if (oflag)
cat(p2in, outputfn);
if (Cflag)
p2out = NULL;
terminate(0);
/* NOTREACHED */
}
/*
* Read a file name from the command line
* and pass it through lint1 if it is a C source.
*/
static void
fname(const char *name)
{
const char *bn, *suff;
char **args, *ofn, *pathname;
const char *CC;
size_t len;
int is_stdin;
int fd;
is_stdin = (strcmp(name, "-") == 0);
bn = lbasename(name, '/');
suff = lbasename(bn, '.');
if (strcmp(suff, "ln") == 0) {
/* only for lint2 */
if (!iflag)
appcstrg(&p2in, name);
return;
}
if (!is_stdin && strcmp(suff, "c") != 0 &&
(strncmp(bn, "llib-l", 6) != 0 || bn != suff)) {
warnx("unknown file type: %s", name);
return;
}
if (!iflag || !first)
(void)printf("%s:\n",
is_stdin ? "{standard input}" : Fflag ? name : bn);
/* build the name of the output file of lint1 */
if (oflag) {
ofn = outputfn;
outputfn = NULL;
oflag = 0;
} else if (iflag) {
if (is_stdin) {
warnx("-i not supported without -o for standard input");
return;
}
ofn = xmalloc(strlen(bn) + (bn == suff ? 4 : 2));
len = bn == suff ? strlen(bn) : (size_t)((suff - 1) - bn);
(void)sprintf(ofn, "%.*s", (int)len, bn);
(void)strcat(ofn, ".ln");
} else {
ofn = xmalloc(strlen(tmpdir) + sizeof ("lint1.XXXXXX"));
(void)sprintf(ofn, "%slint1.XXXXXX", tmpdir);
fd = mkstemp(ofn);
if (fd == -1) {
warn("can't make temp");
terminate(-1);
}
close(fd);
}
if (!iflag)
appcstrg(&p1out, ofn);
args = xcalloc(1, sizeof (char *));
/* run cc */
if ((CC = getenv("CC")) == NULL)
CC = DEFAULT_CC;
if ((pathname = findcc(CC)) == NULL)
if (!setenv("PATH", DEFAULT_PATH, 1))
pathname = findcc(CC);
if (pathname == NULL) {
(void)fprintf(stderr, "%s: %s: not found\n", getprogname(), CC);
exit(EXIT_FAILURE);
}
appcstrg(&args, pathname);
applst(&args, cflags);
applst(&args, lcflags);
appcstrg(&args, name);
/* we reuse the same tmp file for cpp output, so rewind and truncate */
if (lseek(cppoutfd, (off_t)0, SEEK_SET) != 0) {
warn("lseek");
terminate(-1);
}
if (ftruncate(cppoutfd, (off_t)0) != 0) {
warn("ftruncate");
terminate(-1);
}
runchild(pathname, args, cppout, cppoutfd);
free(pathname);
freelst(&args);
/* run lint1 */
if (!Bflag) {
pathname = xmalloc(strlen(PATH_LIBEXEC) + sizeof ("/lint1") +
strlen(target_prefix));
(void)sprintf(pathname, "%s/%slint1", PATH_LIBEXEC,
target_prefix);
} else {
/*
* XXX Unclear whether we should be using target_prefix
* XXX here. --thorpej@wasabisystems.com
*/
pathname = xmalloc(strlen(libexec_path) + sizeof ("/lint1"));
(void)sprintf(pathname, "%s/lint1", libexec_path);
}
appcstrg(&args, pathname);
applst(&args, l1flags);
appcstrg(&args, cppout);
appcstrg(&args, ofn);
runchild(pathname, args, ofn, -1);
free(pathname);
freelst(&args);
appcstrg(&p2in, ofn);
free(ofn);
free(args);
}
static void
runchild(const char *path, char *const *args, const char *crfn, int fdout)
{
int status, rv, signo, i;
if (Vflag) {
for (i = 0; args[i] != NULL; i++)
(void)printf("%s ", args[i]);
(void)printf("\n");
}
currfn = crfn;
(void)fflush(stdout);
switch (vfork()) {
case -1:
warn("cannot fork");
terminate(-1);
/* NOTREACHED */
default:
/* parent */
break;
case 0:
/* child */
/* setup the standard output if necessary */
if (fdout != -1) {
dup2(fdout, STDOUT_FILENO);
close(fdout);
}
(void)execvp(path, args);
warn("cannot exec %s", path);
_exit(1);
/* NOTREACHED */
}
while ((rv = wait(&status)) == -1 && errno == EINTR) ;
if (rv == -1) {
warn("wait");
terminate(-1);
}
if (WIFSIGNALED(status)) {
signo = WTERMSIG(status);
#if HAVE_DECL_SYS_SIGNAME
warnx("%s got SIG%s", path, sys_signame[signo]);
#else
warnx("%s got signal %d", path, signo);
#endif
terminate(-1);
}
if (WEXITSTATUS(status) != 0)
terminate(-1);
currfn = NULL;
}
static void
findlibs(char *const *liblst)
{
int i, k;
const char *lib, *path;
char *lfn;
size_t len;
lfn = NULL;
for (i = 0; (lib = liblst[i]) != NULL; i++) {
for (k = 0; (path = libsrchpath[k]) != NULL; k++) {
len = strlen(path) + strlen(lib);
lfn = xrealloc(lfn, len + sizeof ("/llib-l.ln"));
(void)sprintf(lfn, "%s/llib-l%s.ln", path, lib);
if (rdok(lfn))
break;
lfn = xrealloc(lfn, len + sizeof ("/lint/llib-l.ln"));
(void)sprintf(lfn, "%s/lint/llib-l%s.ln", path, lib);
if (rdok(lfn))
break;
}
if (path != NULL) {
appstrg(&l2libs, concat2("-l", lfn));
} else {
warnx("cannot find llib-l%s.ln", lib);
}
}
free(lfn);
}
static int
rdok(const char *path)
{
struct stat sbuf;
if (stat(path, &sbuf) == -1)
return (0);
if (!S_ISREG(sbuf.st_mode))
return (0);
if (access(path, R_OK) == -1)
return (0);
return (1);
}
static void
lint2(void)
{
char *path, **args;
args = xcalloc(1, sizeof (char *));
if (!Bflag) {
path = xmalloc(strlen(PATH_LIBEXEC) + sizeof ("/lint2") +
strlen(target_prefix));
(void)sprintf(path, "%s/%slint2", PATH_LIBEXEC,
target_prefix);
} else {
/*
* XXX Unclear whether we should be using target_prefix
* XXX here. --thorpej@wasabisystems.com
*/
path = xmalloc(strlen(libexec_path) + sizeof ("/lint2"));
(void)sprintf(path, "%s/lint2", libexec_path);
}
appcstrg(&args, path);
applst(&args, l2flags);
applst(&args, l2libs);
applst(&args, p2in);
runchild(path, args, p2out, -1);
free(path);
freelst(&args);
free(args);
}
static void
cat(char *const *srcs, const char *dest)
{
int ifd, ofd, i;
char *src, *buf;
ssize_t rlen;
if ((ofd = open(dest, O_WRONLY | O_CREAT | O_TRUNC, 0666)) == -1) {
warn("cannot open %s", dest);
terminate(-1);
}
buf = xmalloc(MBLKSIZ);
for (i = 0; (src = srcs[i]) != NULL; i++) {
if ((ifd = open(src, O_RDONLY)) == -1) {
free(buf);
warn("cannot open %s", src);
terminate(-1);
}
do {
if ((rlen = read(ifd, buf, MBLKSIZ)) == -1) {
free(buf);
warn("read error on %s", src);
terminate(-1);
}
if (write(ofd, buf, (size_t)rlen) == -1) {
free(buf);
warn("write error on %s", dest);
terminate(-1);
}
} while (rlen == MBLKSIZ);
(void)close(ifd);
}
(void)close(ofd);
free(buf);
}
|
execunix/vinos
|
usr.bin/xlint/xlint/xlint.c
|
C
|
apache-2.0
| 19,005
|
/*
* Copyright (c) 2014-2020 by The Monix Project Developers.
* See the project homepage at: https://monix.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monix.reactive
import cats.Eq
import cats.Monoid
import minitest.{SimpleTestSuite, TestSuite}
import minitest.laws.Checkers
import monix.eval.Task
import monix.execution.internal.Platform
import monix.execution.schedulers.TestScheduler
import monix.reactive.Notification.{OnComplete, OnError, OnNext}
import monix.reactive.observables.CombineObservable
import monix.reactive.subjects._
import org.scalacheck.Test.Parameters
import org.scalacheck.{Arbitrary, Cogen, Gen, Prop}
import org.typelevel.discipline.Laws
import scala.concurrent.duration._
trait BaseTestSuite extends TestSuite[TestScheduler] with Checkers with ArbitraryInstances {
def setup(): TestScheduler = TestScheduler()
def tearDown(env: TestScheduler): Unit = {
assert(env.state.tasks.isEmpty, "should not have tasks left to execute")
}
}
trait BaseLawsTestSuite extends SimpleTestSuite with Checkers with ArbitraryInstances {
override lazy val checkConfig: Parameters =
Parameters.default
.withMinSuccessfulTests(if (Platform.isJVM) 100 else 10)
.withMaxDiscardRatio(if (Platform.isJVM) 5.0f else 50.0f)
.withMaxSize(10)
def checkAllAsync(name: String, config: Parameters = checkConfig)(f: TestScheduler => Laws#RuleSet): Unit = {
val s = TestScheduler()
val ruleSet = f(s)
for ((id, prop: Prop) <- ruleSet.all.properties)
test(name + "." + id) {
s.tick(1.day)
check(prop)
}
}
}
trait ArbitraryInstances extends ArbitraryInstancesBase with monix.eval.ArbitraryInstances {
implicit def equalityNotification[A](implicit A: Eq[A]): Eq[Notification[A]] =
new Eq[Notification[A]] {
def eqv(x: Notification[A], y: Notification[A]): Boolean = {
x match {
case OnNext(v1) =>
y match {
case OnNext(v2) => A.eqv(v1, v2)
case _ => false
}
case OnError(ex1) =>
y match {
case OnError(ex2) => equalityThrowable.eqv(ex1, ex2)
case _ => false
}
case OnComplete =>
y == OnComplete
}
}
}
implicit def equalityObservable[A](implicit A: Eq[A], ec: TestScheduler): Eq[Observable[A]] =
new Eq[Observable[A]] {
def eqv(lh: Observable[A], rh: Observable[A]): Boolean = {
val eqList = implicitly[Eq[List[Notification[A]]]]
val fa = lh.materialize.toListL.runToFuture
val fb = rh.materialize.toListL.runToFuture
equalityFuture(eqList, ec).eqv(fa, fb)
}
}
implicit def equalityCombineObservable[A](implicit A: Eq[A], ec: TestScheduler): Eq[CombineObservable.Type[A]] =
new Eq[CombineObservable.Type[A]] {
import CombineObservable.unwrap
def eqv(lh: CombineObservable.Type[A], rh: CombineObservable.Type[A]): Boolean = {
Eq[Observable[A]].eqv(unwrap(lh), unwrap(rh))
}
}
implicit def equalitySubject[A: Arbitrary](implicit A: Eq[A], ec: TestScheduler): Eq[Subject[A, A]] =
new Eq[Subject[A, A]] {
def eqv(lh: Subject[A, A], rh: Subject[A, A]): Boolean = {
val eqList = implicitly[Eq[List[Notification[A]]]]
val arbList = implicitly[Arbitrary[List[A]]]
val list = arbList.arbitrary.sample
list.map(lh.feed)
list.map(rh.feed)
val fa = lh.materialize.toListL.runToFuture
val fb = rh.materialize.toListL.runToFuture
lh.size == rh.size && equalityFuture(eqList, ec).eqv(fa, fb)
}
}
implicit def equalityConsumer[A: Arbitrary](implicit A: Eq[A], ec: TestScheduler): Eq[Consumer[A, A]] =
new Eq[Consumer[A, A]] {
override def eqv(lh: Consumer[A, A], rh: Consumer[A, A]): Boolean = {
val eqList = implicitly[Eq[List[A]]]
val arbObservable = implicitly[Arbitrary[Observable[A]]]
val observable = arbObservable.arbitrary.sample
val fa = Task.sequence(observable.map(_.consumeWith(lh)).toList).runToFuture
val fb = Task.sequence(observable.map(_.consumeWith(rh)).toList).runToFuture
equalityFuture(eqList, ec).eqv(fa, fb)
}
}
}
trait ArbitraryInstancesBase extends monix.eval.ArbitraryInstancesBase {
implicit def arbitraryObservable[A: Arbitrary]: Arbitrary[Observable[A]] =
Arbitrary {
implicitly[Arbitrary[List[A]]].arbitrary
.map(Observable.fromIterable)
}
implicit def arbitraryCombineObservable[A: Arbitrary]: Arbitrary[CombineObservable.Type[A]] = {
import CombineObservable.{apply => wrap}
Arbitrary {
implicitly[Arbitrary[List[A]]].arbitrary
.map(list => wrap(Observable.fromIterable(list)))
}
}
implicit def arbitrarySubject[A](implicit arb: Arbitrary[A]): Arbitrary[Subject[A, A]] = Arbitrary {
Gen.oneOf(
Gen.const(AsyncSubject[A]()),
Gen.const(PublishSubject[A]()),
arb.arbitrary.map(BehaviorSubject(_)),
implicitly[Arbitrary[List[A]]].arbitrary.map(ReplaySubject.create(_))
)
}
implicit def arbitraryConsumer[A](implicit arb: Arbitrary[A], M: Monoid[A]): Arbitrary[Consumer[A, A]] =
Arbitrary {
Gen.oneOf(
Gen.const(Consumer.foldLeft(M.empty)(M.combine)),
Gen.const(Consumer.head[A])
)
}
implicit def cogenForObservable[A]: Cogen[Observable[A]] =
Cogen[Unit].contramap(_ => ())
}
|
alexandru/monifu
|
monix-reactive/shared/src/test/scala/monix/reactive/BaseTestSuite.scala
|
Scala
|
apache-2.0
| 5,973
|
package genericpilot
import (
"sync"
"time"
"github.com/golang/glog"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/record"
clientset "github.com/jetstack/navigator/pkg/client/clientset/versioned"
listersv1alpha1 "github.com/jetstack/navigator/pkg/client/listers/navigator/v1alpha1"
"github.com/jetstack/navigator/pkg/pilot/genericpilot/controller"
"github.com/jetstack/navigator/pkg/pilot/genericpilot/leaderelection"
"github.com/jetstack/navigator/pkg/pilot/genericpilot/processmanager"
)
type GenericPilot struct {
Options Options
// TODO: remove use of the kubernetes clientset. Absorb required
// functionality into the navigator api group
kubeClientset kubernetes.Interface
client clientset.Interface
pilotLister listersv1alpha1.PilotLister
recorder record.EventRecorder
controller *controller.Controller
// process is a reference to a process manager for the application this
// Pilot manages
process processmanager.Interface
// shutdown is true when the process has been told to gracefully exit
shutdown bool
// lock is used internally to coordinate updates to fields on the
// GenericPilot structure
lock sync.Mutex
elector leaderelection.Interface
}
func (g *GenericPilot) Run() error {
glog.Infof("Starting generic pilot controller")
// setup healthz handlers
g.serveHealthz()
ctrlStopCh := make(chan struct{})
defer close(ctrlStopCh)
var err error
// block until told to shutdown
select {
case <-g.Options.StopCh:
glog.Infof("Shutdown signal received")
case <-g.waitForProcess():
if err = g.process.Error(); err != nil {
glog.Errorf("Underlying process failed with error: %s", err)
} else {
glog.Errorf("Underlying process unexpectedly exited")
}
case err = <-g.runController(ctrlStopCh):
if err != nil {
glog.Errorf("Control loop failed with error: %s", err)
} else {
glog.Errorf("Control loop unexpectedly exited")
}
case err = <-g.runElector(ctrlStopCh):
if err != nil {
glog.Errorf("Leader elector failed with error: %s", err)
} else {
glog.Errorf("Leader elector unexpectedly exited")
}
}
thisPilot, err := g.controller.ThisPilot()
if err != nil {
return err
}
return g.stop(thisPilot)
}
// waitForProcess will return a chan that will be closed once the underlying
// subprocess exits. This function exists to 'mask' the fact the process may
// not ever exist/be started (as starting the process relies on the Pilot
// resource existing in the API).
func (g *GenericPilot) waitForProcess() <-chan struct{} {
out := make(chan struct{})
go func() {
defer close(out)
for {
if g.process != nil {
break
}
time.Sleep(2)
}
<-g.process.Wait()
}()
return out
}
func (g *GenericPilot) runController(stopCh <-chan struct{}) <-chan error {
out := make(chan error, 1)
go func() {
defer close(out)
out <- g.controller.Run(stopCh)
}()
return out
}
func (g *GenericPilot) runElector(stopCh <-chan struct{}) <-chan error {
out := make(chan error, 1)
go func() {
defer close(out)
out <- g.elector.Run()
}()
return out
}
func (g *GenericPilot) Elector() leaderelection.Interface {
return g.elector
}
|
jetstack/navigator
|
pkg/pilot/genericpilot/genericpilot.go
|
GO
|
apache-2.0
| 3,159
|
import React from 'react';
import Icon from '@ichef/gypcrete/src/Icon';
import iconMap from '@ichef/gypcrete/src/icons/components';
export default {
title: '@ichef/gypcrete|Icon',
component: Icon,
};
export function BasicUsage() {
/**
* Show all icons, ordering from a to z.
*/
return (
<>
{
Object.keys(iconMap).sort().map(iconType => (
<Icon
type={iconType}
spinning={iconType.includes('loading')}
/>
))
}
</>
);
}
BasicUsage.story = {
name: 'Basic Icons Set',
};
export function CRMIconsSet() {
return (
<div>
<Icon type="crm-address" />
<Icon type="crm-age" />
<Icon type="crm-birthday" />
<Icon type="crm-email" />
<Icon type="crm-gender" />
<Icon type="crm-member-name" />
<Icon type="crm-member-note" />
<Icon type="crm-phone-land" />
<Icon type="crm-phone-mobile" />
</div>
);
}
export function ColorOptions() {
return (
<div>
<Icon type="drag" color="gray" />
<Icon type="edit" color="blue" />
<Icon type="trashcan" color="red" />
<Icon type="add" style={{ color: '#78c878' }} />
</div>
);
}
export function InlineIconsSet() {
return (
<div>
<Icon type="inline-loading" />
<Icon type="inline-success" />
<Icon type="inline-error" />
<Icon type="inline-question" />
</div>
);
}
InlineIconsSet.story = {
name: 'Inline-sized Icons Set',
};
export function InventoryIconsSet() {
return (
<div>
<Icon type="inventory-category" />
<Icon type="inventory-item" />
</div>
);
}
export function LargeSizeOptions() {
return (
<div>
<Icon type="loading" large spinning />
<Icon type="success" large color="blue" />
<Icon type="error" large color="red" />
</div>
);
}
export function MenuPageIconsSet() {
return (
<div>
<Icon type="add-item" />
<Icon type="add-multi-items" />
<Icon type="clear-item" />
</div>
);
}
export function PaginationIconsSet() {
return (
<div>
<Icon type="first-page" />
<Icon type="prev-page" />
<Icon type="next-page" />
<Icon type="last-page" />
</div>
);
}
export function PaymentIconsSet() {
return (
<div>
<Icon type="cash" />
<Icon type="credit-card" />
<Icon type="ctbc-direct" />
<Icon type="ctbc-mpos" />
<Icon type="custom-pay" />
</div>
);
}
|
iCHEF/gypcrete
|
packages/storybook/examples/core/Icon.stories.js
|
JavaScript
|
apache-2.0
| 2,492
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import Lozenge from './';
storiesOf('Lozenge', module)
.add('Base', () => {
return <Lozenge>Foo</Lozenge>;
})
.add('With Custom Background Colors', () => {
return (
<div>
<div style={{ marginBottom: '10px' }}>
<Lozenge backgroundColor="#E91E63">foo</Lozenge>
</div>
<div style={{ marginBottom: '10px' }}>
<Lozenge backgroundColor="#009688">bar</Lozenge>
</div>
<div>
<Lozenge backgroundColor="red">baz</Lozenge>
</div>
</div>
);
})
.add('With Custom Text Colors', () => {
return (
<div>
<div style={{ marginBottom: '10px' }}>
<Lozenge backgroundColor="lightgrey" textColor="#E91E63">
foo
</Lozenge>
</div>
<div style={{ marginBottom: '10px' }}>
<Lozenge backgroundColor="lightgrey" textColor="#009688">
bar
</Lozenge>
</div>
<div>
<Lozenge backgroundColor="lightgrey" textColor="red">
baz
</Lozenge>
</div>
</div>
);
})
.add('With Icons', () => {
return (
<div>
<div style={{ marginBottom: '10px' }}>
<Lozenge iconClassName="icon-gps">foo</Lozenge>
</div>
<div style={{ marginBottom: '10px' }}>
<Lozenge iconClassName="icon-face">bar</Lozenge>
</div>
<div>
<Lozenge iconClassName="icon-ocr">baz</Lozenge>
</div>
</div>
);
});
|
veritone/veritone-sdk
|
packages/veritone-react-common/src/components/Lozenge/story.js
|
JavaScript
|
apache-2.0
| 1,581
|
package io.katharsis.internal.boot;
public interface PropertiesProvider {
public String getProperty(String key);
}
|
iMDT/katharsis-framework-j6
|
katharsis-core/src/main/java/io/katharsis/internal/boot/PropertiesProvider.java
|
Java
|
apache-2.0
| 118
|
angular
.module('services')
.service('UserService', UserService);
UserService.$inject = ['$resource', '$q'];
function UserService($resource, $q) {
var resource = $resource('', {}, {
get_current_user: {
method: 'GET',
url: '/console/user/current'
},
logout: {
method: 'GET',
url: '/console/user/logout'
}
});
function getCurrentUser() {
var d = $q.defer();
resource.get_current_user({},
function (result) {
d.resolve(result);
}, function (result) {
d.reject(result);
});
return d.promise;
}
function logout() {
var d = $q.defer();
resource.logout({},
function (result) {
d.resolve(result);
}, function (result) {
d.reject(result);
});
return d.promise;
}
return {
getCurrentUser: getCurrentUser,
logout: logout
}
}
|
ctripcorp/x-pipe
|
redis/redis-console/src/main/resources/static/scripts/services/UserService.ts
|
TypeScript
|
apache-2.0
| 1,141
|
# Solenia maxima Massee SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Brit. Fung. -Fl. 1: 143 (1892)
#### Original name
Solenia maxima Massee
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Marasmiaceae/Henningsomyces/Solenia maxima/README.md
|
Markdown
|
apache-2.0
| 197
|
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2014 The ZAP Development 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 org.zaproxy.zap.extension.importLogFiles;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.log4j.Logger;
import org.jwall.web.audit.AuditEvent;
import org.jwall.web.audit.io.ModSecurity2AuditReader;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.db.DatabaseException;
import org.parosproxy.paros.extension.ExtensionAdaptor;
import org.parosproxy.paros.extension.ExtensionHook;
import org.parosproxy.paros.model.HistoryReference;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.model.Session;
import org.parosproxy.paros.model.SiteMap;
import org.parosproxy.paros.network.HttpMalformedHeaderException;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.network.HttpRequestHeader;
import org.parosproxy.paros.network.HttpResponseHeader;
import org.parosproxy.paros.view.View;
import org.zaproxy.zap.network.HttpRequestBody;
import org.zaproxy.zap.network.HttpResponseBody;
import org.zaproxy.zap.view.ZapMenuItem;
public class ExtensionImportLogFiles extends ExtensionAdaptor {
/** Logging options for the import */
public static enum LogType {
ZAP("zap"),
MOD_SECURITY_2("modsec2");
private String i18nKey;
private LogType(String i18nKey) {
this.i18nKey = i18nKey;
}
@Override
public String toString() {
return Constant.messages.getString("importLogFiles.log.type." + i18nKey);
}
}
private ZapMenuItem menuExample = null;
private static Logger log = Logger.getLogger(ExtensionImportLogFiles.class);
private ImportLogAPI importLogAPI;
public ExtensionImportLogFiles() {
super("ExtensionImportLogFiles");
}
@SuppressWarnings("deprecation")
@Override
public void hook(ExtensionHook extensionHook) {
super.hook(extensionHook);
importLogAPI = new ImportLogAPI(null);
extensionHook.addApiImplementor(importLogAPI);
if (getView() != null) {
extensionHook.getHookMenu().addImportMenuItem(getImportOption());
}
}
@Override
public boolean canUnload() {
return true;
}
private ZapMenuItem getImportOption() {
if (menuExample == null) {
menuExample = new ZapMenuItem("importLogFiles.import.importLOG");
menuExample.addActionListener(
new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
View view = View.getSingleton();
JFrame main = view.getMainFrame();
JFileChooser fc = new JFileChooser();
fc.setAcceptAllFileFilterUsed(false);
FileFilter filter =
new FileNameExtensionFilter(
getMessageString(
"importLogFiles.choosefile.filter.description"),
"txt");
fc.addChoosableFileFilter(filter);
LogType logChoice =
(LogType)
JOptionPane.showInputDialog(
main,
getMessageString(
"importLogFiles.choosefile.message"),
getMessageString(
"importLogFiles.choosefile.title"),
JOptionPane.QUESTION_MESSAGE,
null,
LogType.values(),
LogType.ZAP);
if (logChoice != null) {
int openChoice = fc.showOpenDialog(main);
if (openChoice == JFileChooser.APPROVE_OPTION) {
File newFile = fc.getSelectedFile();
processInput(newFile, logChoice);
}
}
}
});
}
return menuExample;
}
public List<HttpMessage> ReadModSecAuditEvent(InputStream stream) {
ModSecurity2AuditReader reader = null;
try {
reader = new ModSecurity2AuditReader(stream);
return readModSecLogs(reader);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
/**
* For reading logs that are exported from the ModSecurity application
*
* @param newFile java.io.File object referring to the ModSecurity text log file
* @return List of HttpMessages containing Request Header and Body and Response Header and Body
* @throws IOException
*/
public List<HttpMessage> readModSecLogsFromFile(File newFile) {
ModSecurity2AuditReader reader = null;
try {
reader = new ModSecurity2AuditReader(newFile);
return readModSecLogs(reader);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
private synchronized List<HttpMessage> readModSecLogs(ModSecurity2AuditReader reader)
throws IOException {
List<HttpMessage> messages = new ArrayList<>();
while (reader.bytesRead() < reader.bytesAvailable()) {
try {
AuditEvent a = reader.readNext();
if (a != null) {
// Mod Security logs don't provide http response bodies to load in.
HttpMessage httpMessage =
new HttpMessage(
new HttpRequestHeader(a.getRequestHeader()),
new HttpRequestBody(a.getRequestBody()),
new HttpResponseHeader(a.getResponseHeader()),
new HttpResponseBody());
httpMessage.setResponseFromTargetHost(true);
messages.add(httpMessage);
} else break;
} catch (Exception e) {
// View.getSingleton().showWarningDialog("Cannot import this log as it does not
// match the ModSecurity2 data format");
log.error(e.getMessage(), e);
}
}
reader.close();
if (messages.size() == 0) {
return null;
}
return messages;
}
/**
* Updates the UI view with the newly added HttpMessages This method needs to be public as it
* can be called internally and by the API
*
* @param historyList List of History References returned from adding HttpMessages to the ZAP
* database
*/
public void addToTree(List<HistoryReference> historyList) {
SiteMap currentTree = Model.getSingleton().getSession().getSiteTree();
for (HistoryReference historyref : historyList) {
currentTree.addPath(historyref);
}
currentTree.reload();
// /Need to refresh history tabs for details and alerts refresh
}
/**
* Switch method called by the entry point for the log imports to choose path to take based on
* the log type selected by the user
*
* @param newFile java.IO.File representation of the logfile, called from both the UI and from
* the API
* @param logChoice type of logfile being imported
*/
public void processInput(File newFile, LogType logChoice) {
if (logChoice == LogType.ZAP) {
List<String> parsedText = readFile(newFile);
try {
List<HttpMessage> messages = getHttpMessages(parsedText);
List<HistoryReference> history = getHistoryRefs(messages);
addToTree(history);
} catch (HttpMalformedHeaderException e) {
log.error(e.getMessage(), e);
}
} else if (logChoice == LogType.MOD_SECURITY_2) {
try {
List<HttpMessage> messages = readModSecLogsFromFile(newFile);
List<HistoryReference> history = getHistoryRefs(messages);
SiteMap currentTree = Model.getSingleton().getSession().getSiteTree();
for (HistoryReference historyref : history) {
currentTree.addPath(historyref);
}
currentTree.reload();
// /Need to refresh history tabs for details.
} catch (IOException e) {
log.error(e.getMessage(), e);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
List<String> readFile(File file) {
return readFileFromPath(Paths.get(file.getPath()));
}
List<String> readFileFromPath(Path filePath) {
List<String> parsed = new ArrayList<String>();
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(filePath, charset)) {
Scanner sc = new Scanner(reader);
sc.useDelimiter(Pattern.compile("====\\s[0-9]*\\s=========="));
while (sc.hasNext()) {
parsed.add(sc.next());
}
sc.close();
return parsed;
} catch (IOException x) {
log.error(x.getMessage(), x);
}
return null;
}
/**
* Called exclusively by the REST API to get the HttpMessage ZAP object representation of the
* request response pair.
*
* @param request HttpRequest string
* @param response HttpRespones string
* @return List of the HttpMessage objects
* @throws HttpMalformedHeaderException
*/
public List<HttpMessage> getHttpMessageFromPair(String request, String response)
throws HttpMalformedHeaderException {
List<String> reqResp = new ArrayList<>(2);
reqResp.add(request);
reqResp.add(response);
return getHttpMessages(reqResp);
}
private List<HttpMessage> getHttpMessages(List<String> parsedrequestandresponse)
throws HttpMalformedHeaderException {
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html
Pattern requestP =
Pattern.compile("^OPTIONS|^GET|^HEAD|^POST|^PUT|^DELETE|^TRACE|^CONNECT");
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html
// Not sure whether to use the allchars-then-allwhitespacechars or just the DOTALL to get
// the httprequestbody?
Pattern responseP =
Pattern.compile(
"(\\S*\\s*)?(HTTP/[0-9].[0-9]\\s[0-9]{3}.*)",
Pattern.DOTALL | Pattern.MULTILINE);
// Pattern responseP = Pattern.compile("(.*)?(HTTP/[0-9].[0-9]\\s[0-9]{3}.*)",
// Pattern.DOTALL | Pattern.MULTILINE);
// Add capture group as we want to just match the html, not the rest of the payload
Pattern responseBodyP =
Pattern.compile("\\S*?(<html>.*</html>)", Pattern.DOTALL | Pattern.MULTILINE);
HttpRequestHeader tempRequestHeader = null;
HttpRequestBody tempRequestBody = new HttpRequestBody();
HttpResponseHeader tempResponseHeader = null;
HttpResponseBody tempResponseBody = new HttpResponseBody();
// Initialise list at total parsed message count for performance.
List<HttpMessage> messages = new ArrayList<>(parsedrequestandresponse.size());
for (String block : parsedrequestandresponse) {
// HTTP request and response header pairs have a 2 line break between them as per RFC
// 2616
// http://tools.ietf.org/html/rfc2616
String[] httpComponents = block.split("\r\n\r\n");
for (String component : httpComponents) {
// Remove leading and trailing whitespace
component = component.trim();
Matcher requestM = requestP.matcher(component);
if (requestM.find()) {
tempRequestHeader = new HttpRequestHeader(component);
}
// Strange way of splitting it up but usually if the httpRequestBody is present,
// i.e. on a Post request there's
// a token in the body usually
// So I'm using the group matching in the regex to split that up. We'll need either
// a blank HttpRequestBody or
// the actual one further down the line.
Matcher responseM = responseP.matcher(component);
if (responseM.find()) {
if (!responseM.group(1).trim().isEmpty())
tempRequestBody = new HttpRequestBody(responseM.group(1).trim());
tempResponseHeader = new HttpResponseHeader(responseM.group(2).trim());
}
Matcher responseBodyM = responseBodyP.matcher(component);
if (responseBodyM.find()) {
tempResponseBody = new HttpResponseBody(responseBodyM.group(1));
}
}
if (tempRequestHeader != null && tempResponseHeader != null) {
HttpMessage httpMessage =
new HttpMessage(
tempRequestHeader,
tempRequestBody,
tempResponseHeader,
tempResponseBody);
httpMessage.setResponseFromTargetHost(true);
messages.add(httpMessage);
}
}
return messages;
}
public List<HistoryReference> getHistoryRefs(List<HttpMessage> messages)
throws HttpMalformedHeaderException {
// Initialise list at total parsed message count for performance.
List<HistoryReference> historyRefs = new ArrayList<>(messages.size());
Session currentSession = Model.getSingleton().getSession();
for (HttpMessage message : messages) {
try {
historyRefs.add(new HistoryReference(currentSession, 1, message));
} catch (DatabaseException e) {
log.error(e.getMessage(), e);
} catch (HttpMalformedHeaderException e) {
log.error(e.getMessage(), e);
} catch (NullPointerException n) {
log.error(n.getMessage(), n);
}
}
return historyRefs;
}
public String getMessageString(String key) {
return getMessages().getString(key);
}
@Override
public String getDescription() {
return getMessages().getString("importLogFiles.desc");
}
@Override
public URL getURL() {
try {
return new URL(
"https://github.com/zaproxy/zaproxy/wiki/MozillaMentorship_ImportingModSecurityLogs");
} catch (MalformedURLException e) {
return null;
}
}
}
|
zapbot/zap-extensions
|
addOns/importLogFiles/src/main/java/org/zaproxy/zap/extension/importLogFiles/ExtensionImportLogFiles.java
|
Java
|
apache-2.0
| 16,740
|
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* BatchJobStatus.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.adwords.axis.v201809.cm;
public class BatchJobStatus implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected BatchJobStatus(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _UNKNOWN = "UNKNOWN";
public static final java.lang.String _AWAITING_FILE = "AWAITING_FILE";
public static final java.lang.String _ACTIVE = "ACTIVE";
public static final java.lang.String _CANCELING = "CANCELING";
public static final java.lang.String _CANCELED = "CANCELED";
public static final java.lang.String _DONE = "DONE";
public static final BatchJobStatus UNKNOWN = new BatchJobStatus(_UNKNOWN);
public static final BatchJobStatus AWAITING_FILE = new BatchJobStatus(_AWAITING_FILE);
public static final BatchJobStatus ACTIVE = new BatchJobStatus(_ACTIVE);
public static final BatchJobStatus CANCELING = new BatchJobStatus(_CANCELING);
public static final BatchJobStatus CANCELED = new BatchJobStatus(_CANCELED);
public static final BatchJobStatus DONE = new BatchJobStatus(_DONE);
public java.lang.String getValue() { return _value_;}
public static BatchJobStatus fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
BatchJobStatus enumeration = (BatchJobStatus)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static BatchJobStatus fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(BatchJobStatus.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "BatchJobStatus"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
|
googleads/googleads-java-lib
|
modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201809/cm/BatchJobStatus.java
|
Java
|
apache-2.0
| 3,907
|
<?php
namespace BrasseursApplis\Arrows\App\DTO\Helper;
use Assert\AssertionFailedException;
use BrasseursApplis\Arrows\App\DTO\SequenceDTO;
use BrasseursApplis\Arrows\VO\Orientation;
use BrasseursApplis\Arrows\VO\Position;
use BrasseursApplis\Arrows\VO\Sequence;
use BrasseursApplis\Arrows\VO\SequenceCollection;
class SequenceConverter
{
/**
* @param SequenceDTO[] $sequences
*
* @return SequenceCollection
*
* @throws AssertionFailedException
*/
public static function toSequenceCollection(array $sequences)
{
return new SequenceCollection(array_map(function (SequenceDTO $sequence) {
return self::toSequence($sequence);
}, $sequences));
}
/**
* @param array $array
*
* @return SequenceDTO[]
*/
public static function fromJsonArray(array $array)
{
return array_map(function (array $array) {
return new SequenceDTO(
$array['position'],
$array['previewOrientation'],
$array['initiationOrientation'],
$array['mainOrientation']
);
}, $array);
}
/**
* @param SequenceDTO $sequenceDTO
*
* @return Sequence
*/
private static function toSequence(SequenceDTO $sequenceDTO)
{
return new Sequence(
new Position($sequenceDTO->getPosition()),
new Orientation($sequenceDTO->getPreviewOrientation()),
new Orientation($sequenceDTO->getInitiationOrientation()),
new Orientation($sequenceDTO->getMainOrientation())
);
}
}
|
brasseurs-applis/arrows
|
app/DTO/Helper/SequenceConverter.php
|
PHP
|
apache-2.0
| 1,625
|
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#ifndef TITITANIUMOBJECT_H_
#define TITITANIUMOBJECT_H_
#include "TiProxy.h"
class TiCascadesApp;
/*
* TiTitaniumObject
*
* Titanium namespace
*/
class TiTitaniumObject : public TiProxy
{
public:
static TiObject* createObject(NativeObjectFactory* objectFactory);
protected:
virtual ~TiTitaniumObject();
virtual void onCreateStaticMembers();
virtual bool canAddMembers() const;
private:
explicit TiTitaniumObject();
TiTitaniumObject(const TiTitaniumObject&);
TiTitaniumObject& operator=(const TiTitaniumObject&);
static Handle<Value> _globalInclude(void* userContext, TiObject* caller, const Arguments& args);
static Handle<Value> _createBuffer(void* userContext, TiObject* caller, const Arguments& args);
NativeObjectFactory* objectFactory_;
};
#endif /* TITITANIUMOBJECT_H_ */
|
appcelerator/titanium_mobile_blackberry
|
src/tibb/src/TiTitaniumObject.h
|
C
|
apache-2.0
| 1,067
|
<!DOCTYPE html>
<html lang="en" ng-app="GoldCastingApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Gold Casting System</title>
<!-- Bootstrap Core CSS -->
<link href="bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="bower_components/metisMenu/dist/metisMenu.min.css" rel="stylesheet">
<!-- DataTables CSS -->
<link href="bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet">
<!-- DataTables Responsive CSS -->
<link href="bower_components/datatables-responsive/css/dataTables.responsive.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="dist/css/sb-admin-2.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<style type="text/css">
.clear { clear:both !important;}
.error { color: #F00 !important; font-weight:normal;}
.p-0 { padding:0px !important;}
.m-b-0 { margin-bottom: 0px; }
.p-l-0 { padding-left: 0px !important;}
/*.txt-box { width: 91px !important; padding:0px !important;}*/
.dir-right{ direction:rtl;}
.m-t-0{ margin-top: 0px !important; }
.m-t-5{ margin-top: 5px !important; }
.m-t-10{ margin-top: 10px !important; }
.m-t-15{ margin-top: 15px !important; }
.m-l-0{ margin-left: 0px !important; }
.m-l-5{ margin-left: 5px !important; }
.m-l-10{ margin-left: 10px !important; }
.m-l-15{ margin-left: 15px !important; }
.m-l-20{ margin-left: 20px !important; }
.m-r-0{ margin-left: 0px !important; }
.m-r-5{ margin-left: 5px !important; }
.m-r-10{ margin-left: 10px !important; }
.m-r-15{ margin-left: 15px !important; }
.m-r-20{ margin-left: 20px !important; }
</style>
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="home">Gold Casting System</a>
</div>
<!-- /.navbar-header -->
<!-- /.navbar-top-links -->
<div class="navbar-default sidebar" role="navigation">
<div class="sidebar-nav navbar-collapse">
<ul class="nav" id="side-menu">
<li>
<a href="#" style="cursor:pointer;" ng-click="show='a'"><i class="fa fa-dashboard fa-fw"></i> Dashboard</a>
</li>
<li>
<a href="advance.html" style="cursor:pointer;"><i class="fa fa-table fa-fw"></i> Advance Gold</a>
</li>
<li>
<a href="#" style="cursor:pointer;" ng-click="show='c'"><i class="fa fa-edit fa-fw"></i> Gold Casting</a>
</li>
<li>
<a href="#" style="cursor:pointer;" ng-click="show='d'"><i class="fa fa-wrench fa-fw"></i> Today Work</a>
</li>
<li>
<a href="#" style="cursor:pointer;" ng-click="show='e'"><i class="fa fa-wrench fa-fw"></i> User Management</a>
</li>
<li>
<a style="cursor:pointer;" ng-click="logOutUser()"> Log Out</a>
</li>
</ul>
</div>
<!-- /.sidebar-collapse -->
</div>
<!-- /.navbar-static-side -->
</nav>
|
jhassan/casting
|
include/header.html
|
HTML
|
apache-2.0
| 4,675
|
/*
* Created by JFormDesigner on Mon Jun 23 01:28:18 EEST 2014
*/
package ga.thesis.gui.table.settings.common;
import com.jgoodies.forms.factories.Borders;
import com.jgoodies.forms.factories.CC;
import com.jgoodies.forms.layout.FormLayout;
import ga.thesis.gui.table.async.CreateSwingWorker;
import ga.thesis.hibernate.service.CRUDService;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* @author Mike Kravchenko
*/
public abstract class AbstractSettingsDialog<T> extends JDialog {
private final SaveListener<T> listener;
private Editor<T> editor;
public AbstractSettingsDialog(Frame owner, SaveListener<T> listener) {
super(owner);
this.listener = listener;
initComponents();
}
public JPanel initEditor() {
editor = getEditor();
return editor.getEditor();
}
private void okButtonActionPerformed(ActionEvent e) {
new CreateSwingWorker<T>(getService(), this, editor.getModel()).execute();
}
private void cancelButtonActionPerformed(ActionEvent e) {
this.setVisible(false);
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner Evaluation license - Marianna Pasichnyk
dialogPane = new JPanel();
buttonBar = new JPanel();
okButton = new JButton();
cancelButton = new JButton();
//======== this ========
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
//======== dialogPane ========
{
dialogPane.setBorder(Borders.createEmptyBorder("9dlu, 9dlu, 9dlu, 9dlu"));
dialogPane.setPreferredSize(new Dimension(400, 250));
dialogPane.setMinimumSize(new Dimension(400, 250));
// JFormDesigner evaluation mark
dialogPane.setBorder(new javax.swing.border.CompoundBorder(
new javax.swing.border.TitledBorder(new javax.swing.border.EmptyBorder(0, 0, 0, 0),
"", javax.swing.border.TitledBorder.CENTER,
javax.swing.border.TitledBorder.BOTTOM, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12),
java.awt.Color.red), dialogPane.getBorder())); dialogPane.addPropertyChangeListener(new java.beans.PropertyChangeListener(){public void propertyChange(java.beans.PropertyChangeEvent e){if("border".equals(e.getPropertyName()))throw new RuntimeException();}});
dialogPane.setLayout(new BorderLayout());
//======== buttonBar ========
{
buttonBar.setBorder(Borders.createEmptyBorder("4dlu, 0dlu, 0dlu, 0dlu"));
buttonBar.setLayout(new FormLayout(
"$glue, $button, $rgap, $button",
"pref"));
//---- okButton ----
okButton.setText("OK");
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
okButtonActionPerformed(e);
}
});
buttonBar.add(okButton, CC.xy(2, 1));
//---- cancelButton ----
cancelButton.setText("Cancel");
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cancelButtonActionPerformed(e);
}
});
buttonBar.add(cancelButton, CC.xy(4, 1));
}
dialogPane.add(buttonBar, BorderLayout.SOUTH);
}
contentPane.add(dialogPane, BorderLayout.CENTER);
pack();
setLocationRelativeTo(getOwner());
// JFormDesigner - End of component initialization //GEN-END:initComponents
init();
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
// Generated using JFormDesigner Evaluation license - Marianna Pasichnyk
private JPanel dialogPane;
private JPanel buttonBar;
private JButton okButton;
private JButton cancelButton;
// JFormDesigner - End of variables declaration //GEN-END:variables
protected void init() {
dialogPane.add(initEditor(), BorderLayout.CENTER);
}
public abstract Editor<T> getEditor();
public abstract CRUDService<T,?> getService();
public void onAfterSave(T model) {
this.setVisible(false);
listener.onSave(model);
}
public static interface SaveListener<T> {
public void onSave(T model);
}
}
|
skylady/GAThesis2
|
src/main/java/ga/thesis/gui/table/settings/common/AbstractSettingsDialog.java
|
Java
|
apache-2.0
| 4,783
|
# csvupdate
Script in python for update data from two files in format CSV.
With this script you can:
- `Update the data row`
- `Add new row`
# Help
# python csvupdate.py
Usage: example usage: csvupdate.py -p primary.csv -s secondary.csv -o output.csv [-k key] [-n] [-f arg1,arg2,arg3...] [-d ';']
Options:
--version show program's version number and exit
-h, --help show this help message and exit
-p PRIMARY_FILE, --primary_file=PRIMARY_FILE
input: primary file
-s SECONDARY_FILE, --secondary_file=SECONDARY_FILE
input: secondary file
-o OUTPUT_FILE, --output=OUTPUT_FILE
output: file
-k KEY, --key=KEY puts key name, the default is the first data (first
column of primary input)
-n, --no-add do not add the secondary input data does not exist if
the primary input, by default data add
-f OUTPUT_FIELDS, --output-fields=OUTPUT_FIELDS
format output fields
-d DELIMITER, --delimiter=DELIMITER
delimiter
# Examples:
Basic, In this example you can obtain all data from 2 files: output.csv
python ./csvupdate.py -p primary.csv -s secondary.csv -o output.csv
Select Fields, "-f": output_fields.csv
python ./csvupdate.py -p primary.csv -s secondary.csv -o output_fields.csv -f first_name,last_name,email
No add new row, but updating data, "-n": output_fields.csv
python ./csvupdate.py -p primary_example_no_add.csv -s secondary_example_no_add.csv -o output_no_add.csv -n
Key, "-k": output_key.csv
python ./csvupdate.py -p primary_example_key.csv -s secondary_example_key.csv -o output_key.csv -k email
|
ordenador/csvupdate
|
README.md
|
Markdown
|
apache-2.0
| 1,869
|
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace CarMarketPlace.Areas.HelpPage.ModelDescriptions
{
public class ParameterDescription
{
public ParameterDescription()
{
Annotations = new Collection<ParameterAnnotation>();
}
public Collection<ParameterAnnotation> Annotations { get; private set; }
public string Documentation { get; set; }
public string Name { get; set; }
public ModelDescription TypeDescription { get; set; }
}
}
|
amartynenko/CarMarketplace
|
CarMarketPlace.Host/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs
|
C#
|
apache-2.0
| 545
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_07.html">Class Test_AbaRouteValidator_07</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_14061_good
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_07.html?line=38728#src-38728" >testAbaNumberCheck_14061_good</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:37:15
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_14061_good</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=26484#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.7352941</span>73.5%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html>
|
dcarda/aba.route.validator
|
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_07_testAbaNumberCheck_14061_good_kfo.html
|
HTML
|
apache-2.0
| 9,181
|
'use strict';
import React,{ Component } from 'react';
import { StyleSheet, AppState, Dimensions, Image } from 'react-native';
import CodePush from 'react-native-code-push';
import { Container, Text, View, InputGroup, Input, Icon } from 'native-base';
import Modal from 'react-native-modalbox';
import AppNavigator from './AppNavigator';
import ProgressBar from './components/loaders/ProgressBar';
import theme from './themes/base-theme';
var height = Dimensions.get('window').height;
let styles = StyleSheet.create({
container: {
flex: 1,
width: null,
height: null
},
box: {
padding: 10,
backgroundColor: 'transparent',
flex: 1,
height: height-70
},
space: {
marginTop: 10,
marginBottom: 10,
justifyContent: 'center'
},
modal: {
justifyContent: 'center',
alignItems: 'center'
},
modal1: {
height: 300,
width: 300
}
});
class App extends Component {
constructor(props) {
super(props);
this.state = {
showDownloadingModal: false,
showInstalling: false,
downloadProgress: 0
}
}
componentDidMount() {
CodePush.sync({ updateDialog: true, installMode: CodePush.InstallMode.IMMEDIATE },
(status) => {
switch (status) {
case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
this.setState({showDownloadingModal: true});
this.refs.modal.open();
break;
case CodePush.SyncStatus.INSTALLING_UPDATE:
this.setState({showInstalling: true});
break;
case CodePush.SyncStatus.UPDATE_INSTALLED:
this.refs.modal.close();
this.setState({showDownloadingModal: false});
break;
}
},
({ receivedBytes, totalBytes, }) => {
this.setState({downloadProgress: receivedBytes / totalBytes * 100});
}
);
}
render() {
if(this.state.showDownloadingModal)
return (
<View style={{backgroundColor: theme.brandSecondary}}>
<InputGroup
borderType='rounded'
>
<Icon name='ios-person-outline' />
<Input placeholder='Username' />
</InputGroup>
<InputGroup
borderType='rounded'
>
<Icon name='ios-unlock-outline' />
<Input
placeholder='Password'
secureTextEntry={true}
/>
</InputGroup>
</View>
);
else
return(
<AppNavigator store={this.props.store} />
);
}
}
export default App
|
chris50bn/Between
|
js/App.js
|
JavaScript
|
apache-2.0
| 3,096
|
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver14;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
class OFMeterFeaturesStatsReplyVer14 implements OFMeterFeaturesStatsReply {
private static final Logger logger = LoggerFactory.getLogger(OFMeterFeaturesStatsReplyVer14.class);
// version: 1.4
final static byte WIRE_VERSION = 5;
final static int LENGTH = 32;
private final static long DEFAULT_XID = 0x0L;
private final static Set<OFStatsReplyFlags> DEFAULT_FLAGS = ImmutableSet.<OFStatsReplyFlags>of();
// OF message fields
private final long xid;
private final Set<OFStatsReplyFlags> flags;
private final OFMeterFeatures features;
//
// package private constructor - used by readers, builders, and factory
OFMeterFeaturesStatsReplyVer14(long xid, Set<OFStatsReplyFlags> flags, OFMeterFeatures features) {
if(flags == null) {
throw new NullPointerException("OFMeterFeaturesStatsReplyVer14: property flags cannot be null");
}
if(features == null) {
throw new NullPointerException("OFMeterFeaturesStatsReplyVer14: property features cannot be null");
}
this.xid = U32.normalize(xid);
this.flags = flags;
this.features = features;
}
// Accessors for OF message fields
@Override
public OFVersion getVersion() {
return OFVersion.OF_14;
}
@Override
public OFType getType() {
return OFType.STATS_REPLY;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFStatsType getStatsType() {
return OFStatsType.METER_FEATURES;
}
@Override
public Set<OFStatsReplyFlags> getFlags() {
return flags;
}
@Override
public OFMeterFeatures getFeatures() {
return features;
}
public OFMeterFeaturesStatsReply.Builder createBuilder() {
return new BuilderWithParent(this);
}
static class BuilderWithParent implements OFMeterFeaturesStatsReply.Builder {
final OFMeterFeaturesStatsReplyVer14 parentMessage;
// OF message fields
private boolean xidSet;
private long xid;
private boolean flagsSet;
private Set<OFStatsReplyFlags> flags;
private boolean featuresSet;
private OFMeterFeatures features;
BuilderWithParent(OFMeterFeaturesStatsReplyVer14 parentMessage) {
this.parentMessage = parentMessage;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_14;
}
@Override
public OFType getType() {
return OFType.STATS_REPLY;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFMeterFeaturesStatsReply.Builder setXid(long xid) {
this.xid = xid;
this.xidSet = true;
return this;
}
@Override
public OFStatsType getStatsType() {
return OFStatsType.METER_FEATURES;
}
@Override
public Set<OFStatsReplyFlags> getFlags() {
return flags;
}
@Override
public OFMeterFeaturesStatsReply.Builder setFlags(Set<OFStatsReplyFlags> flags) {
this.flags = flags;
this.flagsSet = true;
return this;
}
@Override
public OFMeterFeatures getFeatures() {
return features;
}
@Override
public OFMeterFeaturesStatsReply.Builder setFeatures(OFMeterFeatures features) {
this.features = features;
this.featuresSet = true;
return this;
}
@Override
public OFMeterFeaturesStatsReply build() {
long xid = this.xidSet ? this.xid : parentMessage.xid;
Set<OFStatsReplyFlags> flags = this.flagsSet ? this.flags : parentMessage.flags;
if(flags == null)
throw new NullPointerException("Property flags must not be null");
OFMeterFeatures features = this.featuresSet ? this.features : parentMessage.features;
if(features == null)
throw new NullPointerException("Property features must not be null");
//
return new OFMeterFeaturesStatsReplyVer14(
xid,
flags,
features
);
}
}
static class Builder implements OFMeterFeaturesStatsReply.Builder {
// OF message fields
private boolean xidSet;
private long xid;
private boolean flagsSet;
private Set<OFStatsReplyFlags> flags;
private boolean featuresSet;
private OFMeterFeatures features;
@Override
public OFVersion getVersion() {
return OFVersion.OF_14;
}
@Override
public OFType getType() {
return OFType.STATS_REPLY;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFMeterFeaturesStatsReply.Builder setXid(long xid) {
this.xid = xid;
this.xidSet = true;
return this;
}
@Override
public OFStatsType getStatsType() {
return OFStatsType.METER_FEATURES;
}
@Override
public Set<OFStatsReplyFlags> getFlags() {
return flags;
}
@Override
public OFMeterFeaturesStatsReply.Builder setFlags(Set<OFStatsReplyFlags> flags) {
this.flags = flags;
this.flagsSet = true;
return this;
}
@Override
public OFMeterFeatures getFeatures() {
return features;
}
@Override
public OFMeterFeaturesStatsReply.Builder setFeatures(OFMeterFeatures features) {
this.features = features;
this.featuresSet = true;
return this;
}
//
@Override
public OFMeterFeaturesStatsReply build() {
long xid = this.xidSet ? this.xid : DEFAULT_XID;
Set<OFStatsReplyFlags> flags = this.flagsSet ? this.flags : DEFAULT_FLAGS;
if(flags == null)
throw new NullPointerException("Property flags must not be null");
if(!this.featuresSet)
throw new IllegalStateException("Property features doesn't have default value -- must be set");
if(features == null)
throw new NullPointerException("Property features must not be null");
return new OFMeterFeaturesStatsReplyVer14(
xid,
flags,
features
);
}
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFMeterFeaturesStatsReply> {
@Override
public OFMeterFeaturesStatsReply readFrom(ByteBuf bb) throws OFParseError {
int start = bb.readerIndex();
// fixed value property version == 5
byte version = bb.readByte();
if(version != (byte) 0x5)
throw new OFParseError("Wrong version: Expected=OFVersion.OF_14(5), got="+version);
// fixed value property type == 19
byte type = bb.readByte();
if(type != (byte) 0x13)
throw new OFParseError("Wrong type: Expected=OFType.STATS_REPLY(19), got="+type);
int length = U16.f(bb.readShort());
if(length != 32)
throw new OFParseError("Wrong length: Expected=32(32), got="+length);
if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
// Buffer does not have all data yet
bb.readerIndex(start);
return null;
}
if(logger.isTraceEnabled())
logger.trace("readFrom - length={}", length);
long xid = U32.f(bb.readInt());
// fixed value property statsType == 11
short statsType = bb.readShort();
if(statsType != (short) 0xb)
throw new OFParseError("Wrong statsType: Expected=OFStatsType.METER_FEATURES(11), got="+statsType);
Set<OFStatsReplyFlags> flags = OFStatsReplyFlagsSerializerVer14.readFrom(bb);
// pad: 4 bytes
bb.skipBytes(4);
OFMeterFeatures features = OFMeterFeaturesVer14.READER.readFrom(bb);
OFMeterFeaturesStatsReplyVer14 meterFeaturesStatsReplyVer14 = new OFMeterFeaturesStatsReplyVer14(
xid,
flags,
features
);
if(logger.isTraceEnabled())
logger.trace("readFrom - read={}", meterFeaturesStatsReplyVer14);
return meterFeaturesStatsReplyVer14;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFMeterFeaturesStatsReplyVer14Funnel FUNNEL = new OFMeterFeaturesStatsReplyVer14Funnel();
static class OFMeterFeaturesStatsReplyVer14Funnel implements Funnel<OFMeterFeaturesStatsReplyVer14> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFMeterFeaturesStatsReplyVer14 message, PrimitiveSink sink) {
// fixed value property version = 5
sink.putByte((byte) 0x5);
// fixed value property type = 19
sink.putByte((byte) 0x13);
// fixed value property length = 32
sink.putShort((short) 0x20);
sink.putLong(message.xid);
// fixed value property statsType = 11
sink.putShort((short) 0xb);
OFStatsReplyFlagsSerializerVer14.putTo(message.flags, sink);
// skip pad (4 bytes)
message.features.putTo(sink);
}
}
public void writeTo(ByteBuf bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFMeterFeaturesStatsReplyVer14> {
@Override
public void write(ByteBuf bb, OFMeterFeaturesStatsReplyVer14 message) {
// fixed value property version = 5
bb.writeByte((byte) 0x5);
// fixed value property type = 19
bb.writeByte((byte) 0x13);
// fixed value property length = 32
bb.writeShort((short) 0x20);
bb.writeInt(U32.t(message.xid));
// fixed value property statsType = 11
bb.writeShort((short) 0xb);
OFStatsReplyFlagsSerializerVer14.writeTo(bb, message.flags);
// pad: 4 bytes
bb.writeZero(4);
message.features.writeTo(bb);
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFMeterFeaturesStatsReplyVer14(");
b.append("xid=").append(xid);
b.append(", ");
b.append("flags=").append(flags);
b.append(", ");
b.append("features=").append(features);
b.append(")");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFMeterFeaturesStatsReplyVer14 other = (OFMeterFeaturesStatsReplyVer14) obj;
if( xid != other.xid)
return false;
if (flags == null) {
if (other.flags != null)
return false;
} else if (!flags.equals(other.flags))
return false;
if (features == null) {
if (other.features != null)
return false;
} else if (!features.equals(other.features))
return false;
return true;
}
@Override
public boolean equalsIgnoreXid(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFMeterFeaturesStatsReplyVer14 other = (OFMeterFeaturesStatsReplyVer14) obj;
// ignore XID
if (flags == null) {
if (other.flags != null)
return false;
} else if (!flags.equals(other.flags))
return false;
if (features == null) {
if (other.features != null)
return false;
} else if (!features.equals(other.features))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * (int) (xid ^ (xid >>> 32));
result = prime * result + ((flags == null) ? 0 : flags.hashCode());
result = prime * result + ((features == null) ? 0 : features.hashCode());
return result;
}
@Override
public int hashCodeIgnoreXid() {
final int prime = 31;
int result = 1;
// ignore XID
result = prime * result + ((flags == null) ? 0 : flags.hashCode());
result = prime * result + ((features == null) ? 0 : features.hashCode());
return result;
}
}
|
floodlight/loxigen-artifacts
|
openflowj/gen-src/main/java/org/projectfloodlight/openflow/protocol/ver14/OFMeterFeaturesStatsReplyVer14.java
|
Java
|
apache-2.0
| 14,506
|
Function Get-3PARAo {
<#
.SYNOPSIS
Retrieve informations about the configuration of Adaptive optimization (AO).
.DESCRIPTION
This function will retrieve informations about the configuration of Adaptive optimization (AO). You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence.
.LINK
https://github.com/equelin/3PAR-Powershell
.EXAMPLE
Get-3PARAo
Retrieve information about the configuration of Adaptive optimization (AO).
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $false,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'AO Name')]
[String]$name
)
Write-host "This function is deprecated. It's still present for compatibility purpose." -foreground yellow
<#
Begin {
# Test if connection exist
Check-3PARConnection
#Request
$data = Send-3PARRequest -uri '/aoconfigurations' -type 'GET'
# Results
$dataPS = ($data.content | ConvertFrom-Json).members
$dataCount = ($data.content | ConvertFrom-Json).total
# Add custom type to the resulting oject for formating purpose
[array]$AlldataPS = Format-Result -dataPS $dataPS -TypeName '3PAR.Ao'
#Write result + Formating
Write-Verbose "Total number of AO Configuration: $($dataCount)"
}
Process {
If ($name) {
Write-Verbose "Return result(s) with the filter: $($name)"
return $AlldataPS | Where-Object -FilterScript {$_.Name -like $name}
} else {
Write-Verbose "Return result(s) without any filter"
return $AlldataPS
}
}
#>
}
|
equelin/3PAR-Powershell
|
3PAR-Powershell/Public/Get-3PARAo.ps1
|
PowerShell
|
apache-2.0
| 1,649
|
package email
import (
"bytes"
"crypto/tls"
"html/template"
"net"
"net/mail"
"net/smtp"
"time"
"github.com/labstack/gommon/random"
)
type (
Email struct {
Auth smtp.Auth
Header map[string]string
Template *template.Template
smtpAddress string
}
Message struct {
ID string `json:"id"`
From string `json:"from"`
To string `json:"to"`
CC string `json:"cc"`
Subject string `json:"subject"`
BodyText string `json:"body_text"`
BodyHTML string `json:"body_html"`
Inlines []*File `json:"inlines"`
Attachments []*File `json:"attachments"`
buffer *bytes.Buffer
boundary string
}
File struct {
Name string
Type string
Content string
}
)
func New(smtpAddress string) *Email {
return &Email{
smtpAddress: smtpAddress,
Header: map[string]string{},
}
}
func (m *Message) writeHeader(key, value string) {
m.buffer.WriteString(key)
m.buffer.WriteString(": ")
m.buffer.WriteString(value)
m.buffer.WriteString("\r\n")
}
func (m *Message) writeBoundary() {
m.buffer.WriteString("--")
m.buffer.WriteString(m.boundary)
m.buffer.WriteString("\r\n")
}
func (m *Message) writeText(content string, contentType string) {
m.writeBoundary()
m.writeHeader("Content-Type", contentType+"; charset=UTF-8")
m.buffer.WriteString("\r\n")
m.buffer.WriteString(content)
m.buffer.WriteString("\r\n")
m.buffer.WriteString("\r\n")
}
func (m *Message) writeFile(f *File, disposition string) {
m.writeBoundary()
m.writeHeader("Content-Type", f.Type+`; name="`+f.Name+`"`)
m.writeHeader("Content-Disposition", disposition+`; filename="`+f.Name+`"`)
m.writeHeader("Content-Transfer-Encoding", "base64")
m.buffer.WriteString("\r\n")
m.buffer.WriteString(f.Content)
m.buffer.WriteString("\r\n")
m.buffer.WriteString("\r\n")
}
func (e *Email) Send(m *Message) (err error) {
// Message header
m.buffer = bytes.NewBuffer(make([]byte, 256))
m.buffer.Reset()
m.boundary = random.String(16)
m.writeHeader("MIME-Version", "1.0")
m.writeHeader("Message-ID", m.ID)
m.writeHeader("Date", time.Now().Format(time.RFC1123Z))
m.writeHeader("From", m.From)
m.writeHeader("To", m.To)
if m.CC != "" {
m.writeHeader("CC", m.CC)
}
if m.Subject != "" {
m.writeHeader("Subject", m.Subject)
}
// Extra
for k, v := range e.Header {
m.writeHeader(k, v)
}
m.writeHeader("Content-Type", "multipart/mixed; boundary="+m.boundary)
m.buffer.WriteString("\r\n")
// Message body
if m.BodyText != "" {
m.writeText(m.BodyText, "text/plain")
} else if m.BodyHTML != "" {
m.writeText(m.BodyHTML, "text/html")
} else {
m.writeBoundary()
}
// Inlines/attachments
for _, f := range m.Inlines {
m.writeFile(f, "inline")
}
for _, f := range m.Attachments {
m.writeFile(f, "attachment")
}
m.buffer.WriteString("--")
m.buffer.WriteString(m.boundary)
m.buffer.WriteString("--")
// Dial
c, err := smtp.Dial(e.smtpAddress)
if err != nil {
return
}
defer c.Close()
// Check if TLS is required
if ok, _ := c.Extension("STARTTLS"); ok {
host, _, _ := net.SplitHostPort(e.smtpAddress)
config := &tls.Config{ServerName: host}
if err = c.StartTLS(config); err != nil {
return err
}
}
// Authenticate
if e.Auth != nil {
if err = c.Auth(e.Auth); err != nil {
return
}
}
// Send message
from, err := mail.ParseAddress(m.From)
if err != nil {
return
}
if err = c.Mail(from.Address); err != nil {
return
}
to, err := mail.ParseAddressList(m.To)
if err != nil {
return
}
for _, a := range to {
if err = c.Rcpt(a.Address); err != nil {
return
}
}
wc, err := c.Data()
if err != nil {
return
}
defer wc.Close()
_, err = m.buffer.WriteTo(wc)
return
}
|
apiend/web
|
src/apiServer/vendor/github.com/labstack/gommon/email/email.go
|
GO
|
apache-2.0
| 3,734
|
package org.mule.modules.hornetq.connection;
import javax.annotation.Generated;
/**
* Exception thrown when the release connection operation of the
* connection manager fails.
*
*/
@Generated(value = "Mule DevKit Version 3.5.0", date = "2016-02-05T01:35:45-04:30", comments = "Build UNNAMED.1937.40b93b4")
public class UnableToReleaseConnectionException
extends Exception
{
/**
* Create a new exception
*
* @param throwable Inner exception
*/
public UnableToReleaseConnectionException(Throwable throwable) {
super(throwable);
}
}
|
larrymagallanes/hornetq-connector
|
target/generated-sources/mule/org/mule/modules/hornetq/connection/UnableToReleaseConnectionException.java
|
Java
|
apache-2.0
| 586
|
//
// FlyClip.h
// FlyClipSDK
//
// Created by wanghexiang on 2017/7/11.
// Copyright © 2017年 Eric. All rights reserved.
//
#import "FCMedia.h"
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
@interface FlyClip : NSObject
/*
* 设置当前应用的URLSchema
*/
+(void)setURLSchema:(NSString *)urlSchema; // 此处设置为当前App的host即可
/*
* 开启SDK的功能
*/
+(void)startWithAppKey:(NSString *)key;
/*
* 打开飞屏App
*/
+(void)openFlyClipApplication;
/*
* 打开指定App的host
*/
+(void)openApplicationWithHost:(NSString *)applicationHost;
/*
* openApplication;
*/
+(void)applicationOpenedWithURL:(NSString *)url;
/*
* 进入后台
*/
+(void)applicationDidEnterBackground;
/*
* 程序变活跃
*/
+(void)applicationDidBecomeActive;
/*
* 设置当前的媒体文件
*/
+(void)setCurrentMedia:(FCMedia *)media;
+(void)back;
@end
|
Makeanamesohard/FlyClipSDk
|
FlyClipSDK/FlyClipSDK.framework/Headers/FlyClip.h
|
C
|
apache-2.0
| 890
|
#!/usr/bin/env python
import os
import glob
import unittest
import pysmile
import json
__author__ = 'Jonathan Hosmer'
class PySmileTestDecode(unittest.TestCase):
def setUp(self):
curdir = os.path.dirname(os.path.abspath(__file__))
self.smile_dir = os.path.join(curdir, 'data', 'smile')
self.json_dir = os.path.join(curdir, 'data', 'json')
def test_json_org_sample1(self):
s = os.path.join(self.smile_dir, 'json-org-sample1.smile')
j = os.path.join(self.json_dir, 'json-org-sample1.jsn')
b = json.load(open(j, 'rb'))
try:
a = pysmile.decode(open(s, 'rb').read())
except pysmile.SMILEDecodeError, e:
self.fail('Failed to decode:\n{!r}\n{!r}'.format(b, e.args[1]))
else:
if isinstance(a, list):
self.assertListEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
elif isinstance(a, dict):
self.assertDictEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
else:
self.fail('Unexpected Type: {!r}'.format(type(a)))
def test_json_org_sample2(self):
s = os.path.join(self.smile_dir, 'json-org-sample2.smile')
j = os.path.join(self.json_dir, 'json-org-sample2.jsn')
b = json.load(open(j, 'rb'))
try:
a = pysmile.decode(open(s, 'rb').read())
except pysmile.SMILEDecodeError, e:
self.fail('Failed to decode:\n{!r}\n{!r}'.format(b, e.args[1]))
else:
if isinstance(a, list):
self.assertListEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
elif isinstance(a, dict):
self.assertDictEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
else:
self.fail('Unexpected Type: {!r}'.format(type(a)))
def test_json_org_sample3(self):
s = os.path.join(self.smile_dir, 'json-org-sample3.smile')
j = os.path.join(self.json_dir, 'json-org-sample3.jsn')
b = json.load(open(j, 'rb'))
try:
a = pysmile.decode(open(s, 'rb').read())
except pysmile.SMILEDecodeError, e:
self.fail('Failed to decode:\n{!r}\n{!r}'.format(b, e.args[1]))
else:
if isinstance(a, list):
self.assertListEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
elif isinstance(a, dict):
self.assertDictEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
else:
self.fail('Unexpected Type: {!r}'.format(type(a)))
def test_json_org_sample4(self):
s = os.path.join(self.smile_dir, 'json-org-sample4.smile')
j = os.path.join(self.json_dir, 'json-org-sample4.jsn')
b = json.load(open(j, 'rb'))
try:
a = pysmile.decode(open(s, 'rb').read())
except pysmile.SMILEDecodeError, e:
self.fail('Failed to decode:\n{!r}\n{!r}'.format(b, e.args[1]))
else:
if isinstance(a, list):
self.assertListEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
elif isinstance(a, dict):
self.assertDictEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
else:
self.fail('Unexpected Type: {!r}'.format(type(a)))
def test_json_org_sample5(self):
s = os.path.join(self.smile_dir, 'json-org-sample5.smile')
j = os.path.join(self.json_dir, 'json-org-sample5.jsn')
b = json.load(open(j, 'rb'))
try:
a = pysmile.decode(open(s, 'rb').read())
except pysmile.SMILEDecodeError, e:
self.fail('Failed to decode:\n{!r}\n{!r}'.format(b, e.args[1]))
else:
if isinstance(a, list):
self.assertListEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
elif isinstance(a, dict):
self.assertDictEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
else:
self.fail('Unexpected Type: {!r}'.format(type(a)))
def test_numbers_int_4k(self):
s = os.path.join(self.smile_dir, 'numbers-int-4k.smile')
j = os.path.join(self.json_dir, 'numbers-int-4k.jsn')
b = json.load(open(j, 'rb'))
try:
a = pysmile.decode(open(s, 'rb').read())
except pysmile.SMILEDecodeError, e:
self.fail('Failed to decode:\n{!r}\n{!r}'.format(b, e.args[1]))
else:
if isinstance(a, list):
self.assertListEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
elif isinstance(a, dict):
self.assertDictEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
else:
self.fail('Unexpected Type: {!r}'.format(type(a)))
def test_numbers_int_64k(self):
s = os.path.join(self.smile_dir, 'numbers-int-64k.smile')
j = os.path.join(self.json_dir, 'numbers-int-64k.jsn')
b = json.load(open(j, 'rb'))
try:
a = pysmile.decode(open(s, 'rb').read())
except pysmile.SMILEDecodeError, e:
self.fail('Failed to decode:\n{!r}\n{!r}'.format(b, e.args[1]))
else:
if isinstance(a, list):
self.assertListEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
elif isinstance(a, dict):
self.assertDictEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
else:
self.fail('Unexpected Type: {!r}'.format(type(a)))
def test_test1(self):
s = os.path.join(self.smile_dir, 'test1.smile')
j = os.path.join(self.json_dir, 'test1.jsn')
b = json.load(open(j, 'rb'))
try:
a = pysmile.decode(open(s, 'rb').read())
except pysmile.SMILEDecodeError, e:
self.fail('Failed to decode:\n{!r}\n{!r}'.format(b, e.args[1]))
else:
if isinstance(a, list):
self.assertListEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
elif isinstance(a, dict):
self.assertDictEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
else:
self.fail('Unexpected Type: {!r}'.format(type(a)))
def test_test2(self):
s = os.path.join(self.smile_dir, 'test2.smile')
j = os.path.join(self.json_dir, 'test2.jsn')
b = json.load(open(j, 'rb'))
try:
a = pysmile.decode(open(s, 'rb').read())
except pysmile.SMILEDecodeError, e:
self.fail('Failed to decode:\n{!r}\n{!r}'.format(b, e.args[1]))
else:
if isinstance(a, list):
self.assertListEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
elif isinstance(a, dict):
self.assertDictEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
else:
self.fail('Unexpected Type: {!r}'.format(type(a)))
class PySmileTestEncode(unittest.TestCase):
def setUp(self):
curdir = os.path.dirname(os.path.abspath(__file__))
self.smile_dir = os.path.join(curdir, 'data', 'smile')
self.json_dir = os.path.join(curdir, 'data', 'json')
def test_json_org_sample1(self):
s = os.path.join(self.smile_dir, 'json-org-sample1.smile')
j = os.path.join(self.json_dir, 'json-org-sample1.jsn')
a = pysmile.encode(json.load(open(j, 'rb')))
b = open(s, 'rb').read()
self.assertEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
def test_json_org_sample2(self):
s = os.path.join(self.smile_dir, 'json-org-sample2.smile')
j = os.path.join(self.json_dir, 'json-org-sample2.jsn')
a = pysmile.encode(json.load(open(j, 'rb')))
b = open(s, 'rb').read()
self.assertEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
def test_json_org_sample3(self):
s = os.path.join(self.smile_dir, 'json-org-sample3.smile')
j = os.path.join(self.json_dir, 'json-org-sample3.jsn')
a = pysmile.encode(json.load(open(j, 'rb')))
b = open(s, 'rb').read()
self.assertEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
def test_json_org_sample4(self):
s = os.path.join(self.smile_dir, 'json-org-sample4.smile')
j = os.path.join(self.json_dir, 'json-org-sample4.jsn')
a = pysmile.encode(json.load(open(j, 'rb')))
b = open(s, 'rb').read()
self.assertEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
def test_json_org_sample5(self):
s = os.path.join(self.smile_dir, 'json-org-sample5.smile')
j = os.path.join(self.json_dir, 'json-org-sample5.jsn')
a = pysmile.encode(json.load(open(j, 'rb')))
b = open(s, 'rb').read()
self.assertEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
def test_numbers_int_4k(self):
s = os.path.join(self.smile_dir, 'numbers-int-4k.smile')
j = os.path.join(self.json_dir, 'numbers-int-4k.jsn')
a = pysmile.encode(json.load(open(j, 'rb')))
b = open(s, 'rb').read()
self.assertEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
def test_numbers_int_64k(self):
s = os.path.join(self.smile_dir, 'numbers-int-64k.smile')
j = os.path.join(self.json_dir, 'numbers-int-64k.jsn')
a = pysmile.encode(json.load(open(j, 'rb')))
b = open(s, 'rb').read()
self.assertEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
def test_test1(self):
s = os.path.join(self.smile_dir, 'test1.smile')
j = os.path.join(self.json_dir, 'test1.jsn')
a = pysmile.encode(json.load(open(j, 'rb')))
b = open(s, 'rb').read()
self.assertEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
def test_test2(self):
s = os.path.join(self.smile_dir, 'test2.smile')
j = os.path.join(self.json_dir, 'test2.jsn')
a = pysmile.encode(json.load(open(j, 'rb')))
b = open(s, 'rb').read()
self.assertEqual(a, b, '{}\nExpected:\n{!r}\nGot:\n{!r}'.format(s, b, a))
class PySmileTestMisc(unittest.TestCase):
def test_1(self):
a = [1]
b = pysmile.decode(':)\n\x03\xf8\xc2\xf9')
self.assertListEqual(a, b, 'Expected:\n{!r}\nGot:\n{!r}'.format(a, b))
def test_2(self):
a = [1, 2]
b = pysmile.decode(':)\n\x03\xf8\xc2\xc4\xf9')
self.assertListEqual(a, b, 'Expected:\n{!r}\nGot:\n{!r}'.format(a, b))
def test_3(self):
a = [1, 2, {'c': 3}]
b = pysmile.decode(':)\n\x03\xf8\xc2\xc4\xfa\x80c\xc6\xfb\xf9')
self.assertListEqual(a, b, 'Expected:\n{!r}\nGot:\n{!r}'.format(a, b))
def test_4(self):
a = {'a': 1}
b = pysmile.decode(':)\n\x03\xfa\x80a\xc2\xfb')
self.assertDictEqual(a, b, 'Expected:\n{!r}\nGot:\n{!r}'.format(a, b))
def test_5(self):
a = {'a': '1', 'b': 2, 'c': [3], 'd': -1, 'e': 4.20}
b = pysmile.decode(
':)\n\x03\xfa\x80a@1\x80c\xf8\xc6\xf9\x80b\xc4\x80e(fL\x19\x04\x04\x80d\xc1\xfb')
self.assertDictEqual(a, b, 'Expected:\n{!r}\nGot:\n{!r}'.format(a, b))
def test_6(self):
a = {'a': {'b': {'c': {'d': ['e']}}}}
b = pysmile.decode(
':)\n\x03\xfa\x80a\xfa\x80b\xfa\x80c\xfa\x80d\xf8@e\xf9\xfb\xfb\xfb\xfb')
self.assertDictEqual(a, b, 'Expected:\n{!r}\nGot:\n{!r}'.format(a, b))
|
jhosmer/PySmile
|
tests/pysmile_tests.py
|
Python
|
apache-2.0
| 11,679
|
package com.athbk.changeavtarliketinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.athbk.avatarview.TinderRecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TinderRecyclerView recyclerView = (TinderRecyclerView) findViewById(R.id.recyclerView);
List<Integer> listInt = new ArrayList<>();
listInt.add(R.drawable.anh1);
listInt.add(R.drawable.anh2);
listInt.add(R.drawable.anh3);
listInt.add(R.drawable.anh1);
listInt.add(R.drawable.anh2);
listInt.add(R.drawable.anh3);
listInt.add(R.drawable.anh1);
listInt.add(R.drawable.anh2);
listInt.add(R.drawable.anh3);
List<String> listString = new ArrayList<>();
listString.add("http://sohanews.sohacdn.com/2016/photo-7-1467618024092.jpg");
listString.add("http://cms.kienthuc.net.vn/zoom/1000/uploaded/manhtu/2015_12_21/tl/hot-girl-xinh-dep-khien-ai-ngam-cung-muon-phau-thuat-tham-my-hinh-9.jpg");
listString.add("https://s-media-cache-ak0.pinimg.com/736x/be/0a/b7/be0ab7e1a7f2f5a319e190ec0bad1e31.jpg");
listString.add("https://tapchianhdep.com/wp-content/uploads/2016/07/girl-xinh-11.jpg");
listString.add("https://image.freepik.com/free-icon/apple-logo_318-40184.jpg");
listString.add("http://g.vatgia.vn/gallery_img/9/alz1492504789.jpg");
listString.add("http://arena.fpt.edu.vn/wp-content/uploads/2010/11/wwf-logo-design.jpg");
listString.add("https://image.freepik.com/free-vector/abstract-logo-with-colorful-leaves_1025-695.jpg");
listString.add("https://s-media-cache-ak0.pinimg.com/736x/ed/de/11/edde11f4abdb1cd40f8b018f66a8710c.jpg");
listString.add("https://image.freepik.com/free-vector/abstract-logo-in-flame-shape_1043-44.jpg");
// listString.add("http://sohanews.sohacdn.com/2016/photo-7-1467618024092.jpg");
// listString.add("http://cms.kienthuc.net.vn/zoom/1000/uploaded/manhtu/2015_12_21/tl/hot-girl-xinh-dep-khien-ai-ngam-cung-muon-phau-thuat-tham-my-hinh-9.jpg");
// listString.add("http://cms.kienthuc.net.vn/zoom/1000/uploaded/manhtu/2015_12_21/tl/hot-girl-xinh-dep-khien-ai-ngam-cung-muon-phau-thuat-tham-my-hinh-9.jpg");
// listString.add("http://cms.kienthuc.net.vn/zoom/1000/uploaded/manhtu/2015_12_21/tl/hot-girl-xinh-dep-khien-ai-ngam-cung-muon-phau-thuat-tham-my-hinh-9.jpg");
// listString.add("http://cms.kienthuc.net.vn/zoom/1000/uploaded/manhtu/2015_12_21/tl/hot-girl-xinh-dep-khien-ai-ngam-cung-muon-phau-thuat-tham-my-hinh-9.jpg");
// listString.add("http://cms.kienthuc.net.vn/zoom/1000/uploaded/manhtu/2015_12_21/tl/hot-girl-xinh-dep-khien-ai-ngam-cung-muon-phau-thuat-tham-my-hinh-9.jpg");
// listString.add("http://cms.kienthuc.net.vn/zoom/1000/uploaded/manhtu/2015_12_21/tl/hot-girl-xinh-dep-khien-ai-ngam-cung-muon-phau-thuat-tham-my-hinh-9.jpg");
// listString.add("http://cms.kienthuc.net.vn/zoom/1000/uploaded/manhtu/2015_12_21/tl/hot-girl-xinh-dep-khien-ai-ngam-cung-muon-phau-thuat-tham-my-hinh-9.jpg");
// listString.add("http://cms.kienthuc.net.vn/zoom/1000/uploaded/manhtu/2015_12_21/tl/hot-girl-xinh-dep-khien-ai-ngam-cung-muon-phau-thuat-tham-my-hinh-9.jpg");
// listString.add("http://cms.kienthuc.net.vn/zoom/1000/uploaded/manhtu/2015_12_21/tl/hot-girl-xinh-dep-khien-ai-ngam-cung-muon-phau-thuat-tham-my-hinh-9.jpg");
// listString.add("http://cms.kienthuc.net.vn/zoom/1000/uploaded/manhtu/2015_12_21/tl/hot-girl-xinh-dep-khien-ai-ngam-cung-muon-phau-thuat-tham-my-hinh-9.jpg");
List<DataModel> listData = new ArrayList<>();
DataModel data1 = new DataModel("http://sohanews.sohacdn.com/2016/photo-7-1467618024092.jpg", 0);
DataModel data2 = new DataModel("http://cms.kienthuc.net.vn/zoom/1000/uploaded/manhtu/2015_12_21/tl/hot-girl-xinh-dep-khien-ai-ngam-cung-muon-phau-thuat-tham-my-hinh-9.jpg", 1);
DataModel data3 = new DataModel("https://s-media-cache-ak0.pinimg.com/736x/be/0a/b7/be0ab7e1a7f2f5a319e190ec0bad1e31.jpg", 2);
DataModel data4 = new DataModel("https://tapchianhdep.com/wp-content/uploads/2016/07/girl-xinh-11.jpg", 3);
DataModel data5 = new DataModel("https://image.freepik.com/free-icon/apple-logo_318-40184.jpg", 4);
DataModel data6 = new DataModel("http://g.vatgia.vn/gallery_img/9/alz1492504789.jpg", 5);
DataModel data7 = new DataModel("http://arena.fpt.edu.vn/wp-content/uploads/2010/11/wwf-logo-design.jpg", 6);
DataModel data8 = new DataModel("https://image.freepik.com/free-vector/abstract-logo-with-colorful-leaves_1025-695.jpg", 7);
DataModel data9 = new DataModel("https://s-media-cache-ak0.pinimg.com/736x/ed/de/11/edde11f4abdb1cd40f8b018f66a8710c.jpg", 8);
DataModel data10 = new DataModel("https://image.freepik.com/free-vector/abstract-logo-in-flame-shape_1043-44.jpg", 9);
listData.add(data1);
listData.add(data2);
listData.add(data3);
listData.add(data4);
listData.add(data5);
listData.add(data6);
listData.add(data7);
listData.add(data8);
listData.add(data9);
listData.add(data10);
AvatarAdapter adapter = new AvatarAdapter(this, listData);
recyclerView.initRecyclerView(this, adapter);
adapter.setiFinishDrag(new IFinishDrag() {
@Override
public void updateListData(ArrayList<DataModel> listData) {
for (int i=0; i< listData.size(); i++){
Log.e("TAG", "" + i + "/"+ listData.get(i).getLogo());
}
}
});
}
}
|
ATHBK/AvatarTinderView
|
app/src/main/java/com/athbk/changeavtarliketinder/MainActivity.java
|
Java
|
apache-2.0
| 5,897
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack LLC.
# 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.
from quantum.openstack.common import log as logging
from quantum.plugins.services.agent_loadbalancer.drivers.vedge.vmware.vshield.vseapi import VseAPI
from quantum.plugins.services.agent_loadbalancer.drivers.vedge.lbapi import LoadBalancerAPI
from quantum.plugins.services.agent_loadbalancer.drivers.vedge import (
cfg as hacfg
)
from oslo.config import cfg
LOG = logging.getLogger(__name__)
edgeUri = 'https://10.117.5.245'
edgeId = 'edge-7'
edgeUser = 'admin'
edgePasswd = 'default'
OPTS = [
cfg.StrOpt('pool_vseid',
help='this is a vseid of pool'),
cfg.StrOpt('vip_vseid',
help='this is a vseid of vip')
]
class VShieldEdgeLB():
supported_extension_aliases = ["lbaas"]
def __init__(self):
# Hard coded for now
vseapi = VseAPI(edgeUri, edgeUser, edgePasswd, edgeId)
self.vselbapi = LoadBalancerAPI(vseapi)
self.conf = cfg.CONF
self._max_monitors = 255
count = 0
while count < self._max_monitors:
monitorMap = "monitorMap_%d" % count
OPTS.append(cfg.ListOpt(monitorMap))
count = count + 1
self.conf.register_opts(OPTS)
def ini_update(self, ini_path):
argv = ["--config-file", ini_path]
self.conf(argv)
def ini2vseid(self, ini_path):
pool_vseid = self.conf.pool_vseid
vip_vseid = self.conf.vip_vseid
return (pool_vseid, vip_vseid)
def extract_monitorids(self, monitors):
monitor_ids = []
for monitor in monitors:
monitor_ids.append(monitor['id'])
return monitor_ids
def extract_vsemonitor_maps(self):
monitor_maps = {}
count = 0
while count < self._max_monitors:
monitorMap = "monitorMap_%d" % count
opt = "self.conf.{}".format(monitorMap)
monitorMap = eval(opt)
if monitorMap is not None:
monitor_id = monitorMap[0]
monitor_vseid = monitorMap[1]
monitor_maps[monitor_id] = monitor_vseid
else:
return monitor_maps
count = count + 1
return monitor_maps
def ini2monitorvseids(self, monitor_ids, monitor_maps):
monitor_vseids = {}
monitor_vseids_delete = {}
for k,v in monitor_maps.items():
if k in monitor_ids:
monitor_vseids[k] = v
else:
monitor_vseids_delete[k] = v
return (monitor_vseids,monitor_vseids_delete)
# def ini2monitorvseids2(self, ini_path):
# monitor_vseids = {}
# except_opts = ("config_file", "config_dir", "pool_vseid", "vip_vseid")
# opts = self.conf._opts()
# print "opts: %s" % opts
# for index in opts.keys():
# if index not in except_opts:
# opt = "self.conf.{}".format(index)
# index = eval(opt)
# if index is not None:
# monitor_id = index[0]
# monitor_vseid = index[1]
# monitor_vseids[monitor_id] = monitor_vseid
# return monitor_vseids
def create(self, logical_config, ini_path, conf_path):
monitors = logical_config['healthmonitors']
members = logical_config['members']
pool = logical_config['pool']
vip = logical_config['vip']
if monitors is not None:
#try:
monitor_vseids,monitors_request = self.vselbapi.create_monitors(monitors)
#except Exception:
# LOG.error(_("monitors create error %s") % monitors)
# exit(1)
#try:
pool_vseid,pool_request = self.vselbapi.create_pool(pool, members, monitor_vseids)
if vip is not None:
vip_vseid,vip_request = self.vselbapi.create_vip(vip, pool_vseid)
#except Exception:
# hacfg.save_ini(ini_path, pool_vseid, None, monitor_vseids)
# self.vselbapi.delete_monitors(ini_path)
# self.vselbapi.delete_pool(ini_path)
# print "pool or vip create error!"
# exit(1)
hacfg.save_ini(ini_path, pool_vseid, vip_vseid, monitor_vseids)
hacfg.save_conf(conf_path, pool_request, vip_request)
def update(self, logical_config, ini_path, conf_path):
self.ini_update(ini_path)
monitors = logical_config['healthmonitors']
members = logical_config['members']
pool = logical_config['pool']
vip = logical_config['vip']
pool_vseid,vip_vseid = self.ini2vseid(ini_path)
monitor_ids = self.extract_monitorids(monitors)
old_vsemonitor_maps = self.extract_vsemonitor_maps()
monitor_vseids_update,monitor_vseids_delete = self.ini2monitorvseids(monitor_ids, old_vsemonitor_maps)
#try:
if monitors is not None:
monitor_vseids,monitors_request = self.vselbapi.update_monitors(monitors, old_vsemonitor_maps,
monitor_ids, monitor_vseids_update,
monitor_vseids_delete, pool_vseid)
pool_vseid,pool_request = self.vselbapi.update_pool(pool, pool_vseid, members, monitor_vseids)
if vip is not None:
vip_vseid,vip_request = self.vselbapi.update_vip(vip, pool_vseid, vip_vseid)
#except Exception:
# print "pool or vip update error!"
# exit(1)
hacfg.save_ini(ini_path, pool_vseid, vip_vseid, monitor_vseids)
hacfg.save_conf(conf_path, pool_request, vip_request)
def destroy(self, pool_id, ini_path, conf_path):
self.ini_update(ini_path)
pool_vseid,vip_vseid = self.ini2vseid(ini_path)
monitor_vseids = self.extract_vsemonitor_maps()
# monitor_vseids = self.ini2monitorvseids2(ini_path)
if vip_vseid is not None:
self.vselbapi.delete_vip(vip_vseid)
self.vselbapi.delete_pool(pool_vseid, monitor_vseids)
if monitor_vseids is not None:
self.vselbapi.delete_monitors(monitor_vseids, pool_vseid)
def get_stats(pool_id, ini_path, conf_path):
# self.vselbapi.get_stats()
self.vselbapi.get_config()
|
linvictor88/vse-lbaas-driver
|
quantum/plugins/services/agent_loadbalancer/drivers/vedge/vselb.py
|
Python
|
apache-2.0
| 7,013
|
/*
* Copyright 2010-2017 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.
*/
#pragma once
#include <aws/lambda/Lambda_EXPORTS.h>
#include <aws/lambda/LambdaRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Http
{
class URI;
} //namespace Http
namespace Lambda
{
namespace Model
{
/**
*/
class AWS_LAMBDA_API AddLayerVersionPermissionRequest : public LambdaRequest
{
public:
AddLayerVersionPermissionRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "AddLayerVersionPermission"; }
Aws::String SerializePayload() const override;
void AddQueryStringParameters(Aws::Http::URI& uri) const override;
/**
* <p>The name or Amazon Resource Name (ARN) of the layer.</p>
*/
inline const Aws::String& GetLayerName() const{ return m_layerName; }
/**
* <p>The name or Amazon Resource Name (ARN) of the layer.</p>
*/
inline bool LayerNameHasBeenSet() const { return m_layerNameHasBeenSet; }
/**
* <p>The name or Amazon Resource Name (ARN) of the layer.</p>
*/
inline void SetLayerName(const Aws::String& value) { m_layerNameHasBeenSet = true; m_layerName = value; }
/**
* <p>The name or Amazon Resource Name (ARN) of the layer.</p>
*/
inline void SetLayerName(Aws::String&& value) { m_layerNameHasBeenSet = true; m_layerName = std::move(value); }
/**
* <p>The name or Amazon Resource Name (ARN) of the layer.</p>
*/
inline void SetLayerName(const char* value) { m_layerNameHasBeenSet = true; m_layerName.assign(value); }
/**
* <p>The name or Amazon Resource Name (ARN) of the layer.</p>
*/
inline AddLayerVersionPermissionRequest& WithLayerName(const Aws::String& value) { SetLayerName(value); return *this;}
/**
* <p>The name or Amazon Resource Name (ARN) of the layer.</p>
*/
inline AddLayerVersionPermissionRequest& WithLayerName(Aws::String&& value) { SetLayerName(std::move(value)); return *this;}
/**
* <p>The name or Amazon Resource Name (ARN) of the layer.</p>
*/
inline AddLayerVersionPermissionRequest& WithLayerName(const char* value) { SetLayerName(value); return *this;}
/**
* <p>The version number.</p>
*/
inline long long GetVersionNumber() const{ return m_versionNumber; }
/**
* <p>The version number.</p>
*/
inline bool VersionNumberHasBeenSet() const { return m_versionNumberHasBeenSet; }
/**
* <p>The version number.</p>
*/
inline void SetVersionNumber(long long value) { m_versionNumberHasBeenSet = true; m_versionNumber = value; }
/**
* <p>The version number.</p>
*/
inline AddLayerVersionPermissionRequest& WithVersionNumber(long long value) { SetVersionNumber(value); return *this;}
/**
* <p>An identifier that distinguishes the policy from others on the same layer
* version.</p>
*/
inline const Aws::String& GetStatementId() const{ return m_statementId; }
/**
* <p>An identifier that distinguishes the policy from others on the same layer
* version.</p>
*/
inline bool StatementIdHasBeenSet() const { return m_statementIdHasBeenSet; }
/**
* <p>An identifier that distinguishes the policy from others on the same layer
* version.</p>
*/
inline void SetStatementId(const Aws::String& value) { m_statementIdHasBeenSet = true; m_statementId = value; }
/**
* <p>An identifier that distinguishes the policy from others on the same layer
* version.</p>
*/
inline void SetStatementId(Aws::String&& value) { m_statementIdHasBeenSet = true; m_statementId = std::move(value); }
/**
* <p>An identifier that distinguishes the policy from others on the same layer
* version.</p>
*/
inline void SetStatementId(const char* value) { m_statementIdHasBeenSet = true; m_statementId.assign(value); }
/**
* <p>An identifier that distinguishes the policy from others on the same layer
* version.</p>
*/
inline AddLayerVersionPermissionRequest& WithStatementId(const Aws::String& value) { SetStatementId(value); return *this;}
/**
* <p>An identifier that distinguishes the policy from others on the same layer
* version.</p>
*/
inline AddLayerVersionPermissionRequest& WithStatementId(Aws::String&& value) { SetStatementId(std::move(value)); return *this;}
/**
* <p>An identifier that distinguishes the policy from others on the same layer
* version.</p>
*/
inline AddLayerVersionPermissionRequest& WithStatementId(const char* value) { SetStatementId(value); return *this;}
/**
* <p>The API action that grants access to the layer. For example,
* <code>lambda:GetLayerVersion</code>.</p>
*/
inline const Aws::String& GetAction() const{ return m_action; }
/**
* <p>The API action that grants access to the layer. For example,
* <code>lambda:GetLayerVersion</code>.</p>
*/
inline bool ActionHasBeenSet() const { return m_actionHasBeenSet; }
/**
* <p>The API action that grants access to the layer. For example,
* <code>lambda:GetLayerVersion</code>.</p>
*/
inline void SetAction(const Aws::String& value) { m_actionHasBeenSet = true; m_action = value; }
/**
* <p>The API action that grants access to the layer. For example,
* <code>lambda:GetLayerVersion</code>.</p>
*/
inline void SetAction(Aws::String&& value) { m_actionHasBeenSet = true; m_action = std::move(value); }
/**
* <p>The API action that grants access to the layer. For example,
* <code>lambda:GetLayerVersion</code>.</p>
*/
inline void SetAction(const char* value) { m_actionHasBeenSet = true; m_action.assign(value); }
/**
* <p>The API action that grants access to the layer. For example,
* <code>lambda:GetLayerVersion</code>.</p>
*/
inline AddLayerVersionPermissionRequest& WithAction(const Aws::String& value) { SetAction(value); return *this;}
/**
* <p>The API action that grants access to the layer. For example,
* <code>lambda:GetLayerVersion</code>.</p>
*/
inline AddLayerVersionPermissionRequest& WithAction(Aws::String&& value) { SetAction(std::move(value)); return *this;}
/**
* <p>The API action that grants access to the layer. For example,
* <code>lambda:GetLayerVersion</code>.</p>
*/
inline AddLayerVersionPermissionRequest& WithAction(const char* value) { SetAction(value); return *this;}
/**
* <p>An account ID, or <code>*</code> to grant permission to all AWS accounts.</p>
*/
inline const Aws::String& GetPrincipal() const{ return m_principal; }
/**
* <p>An account ID, or <code>*</code> to grant permission to all AWS accounts.</p>
*/
inline bool PrincipalHasBeenSet() const { return m_principalHasBeenSet; }
/**
* <p>An account ID, or <code>*</code> to grant permission to all AWS accounts.</p>
*/
inline void SetPrincipal(const Aws::String& value) { m_principalHasBeenSet = true; m_principal = value; }
/**
* <p>An account ID, or <code>*</code> to grant permission to all AWS accounts.</p>
*/
inline void SetPrincipal(Aws::String&& value) { m_principalHasBeenSet = true; m_principal = std::move(value); }
/**
* <p>An account ID, or <code>*</code> to grant permission to all AWS accounts.</p>
*/
inline void SetPrincipal(const char* value) { m_principalHasBeenSet = true; m_principal.assign(value); }
/**
* <p>An account ID, or <code>*</code> to grant permission to all AWS accounts.</p>
*/
inline AddLayerVersionPermissionRequest& WithPrincipal(const Aws::String& value) { SetPrincipal(value); return *this;}
/**
* <p>An account ID, or <code>*</code> to grant permission to all AWS accounts.</p>
*/
inline AddLayerVersionPermissionRequest& WithPrincipal(Aws::String&& value) { SetPrincipal(std::move(value)); return *this;}
/**
* <p>An account ID, or <code>*</code> to grant permission to all AWS accounts.</p>
*/
inline AddLayerVersionPermissionRequest& WithPrincipal(const char* value) { SetPrincipal(value); return *this;}
/**
* <p>With the principal set to <code>*</code>, grant permission to all accounts in
* the specified organization.</p>
*/
inline const Aws::String& GetOrganizationId() const{ return m_organizationId; }
/**
* <p>With the principal set to <code>*</code>, grant permission to all accounts in
* the specified organization.</p>
*/
inline bool OrganizationIdHasBeenSet() const { return m_organizationIdHasBeenSet; }
/**
* <p>With the principal set to <code>*</code>, grant permission to all accounts in
* the specified organization.</p>
*/
inline void SetOrganizationId(const Aws::String& value) { m_organizationIdHasBeenSet = true; m_organizationId = value; }
/**
* <p>With the principal set to <code>*</code>, grant permission to all accounts in
* the specified organization.</p>
*/
inline void SetOrganizationId(Aws::String&& value) { m_organizationIdHasBeenSet = true; m_organizationId = std::move(value); }
/**
* <p>With the principal set to <code>*</code>, grant permission to all accounts in
* the specified organization.</p>
*/
inline void SetOrganizationId(const char* value) { m_organizationIdHasBeenSet = true; m_organizationId.assign(value); }
/**
* <p>With the principal set to <code>*</code>, grant permission to all accounts in
* the specified organization.</p>
*/
inline AddLayerVersionPermissionRequest& WithOrganizationId(const Aws::String& value) { SetOrganizationId(value); return *this;}
/**
* <p>With the principal set to <code>*</code>, grant permission to all accounts in
* the specified organization.</p>
*/
inline AddLayerVersionPermissionRequest& WithOrganizationId(Aws::String&& value) { SetOrganizationId(std::move(value)); return *this;}
/**
* <p>With the principal set to <code>*</code>, grant permission to all accounts in
* the specified organization.</p>
*/
inline AddLayerVersionPermissionRequest& WithOrganizationId(const char* value) { SetOrganizationId(value); return *this;}
/**
* <p>Only update the policy if the revision ID matches the ID specified. Use this
* option to avoid modifying a policy that has changed since you last read it.</p>
*/
inline const Aws::String& GetRevisionId() const{ return m_revisionId; }
/**
* <p>Only update the policy if the revision ID matches the ID specified. Use this
* option to avoid modifying a policy that has changed since you last read it.</p>
*/
inline bool RevisionIdHasBeenSet() const { return m_revisionIdHasBeenSet; }
/**
* <p>Only update the policy if the revision ID matches the ID specified. Use this
* option to avoid modifying a policy that has changed since you last read it.</p>
*/
inline void SetRevisionId(const Aws::String& value) { m_revisionIdHasBeenSet = true; m_revisionId = value; }
/**
* <p>Only update the policy if the revision ID matches the ID specified. Use this
* option to avoid modifying a policy that has changed since you last read it.</p>
*/
inline void SetRevisionId(Aws::String&& value) { m_revisionIdHasBeenSet = true; m_revisionId = std::move(value); }
/**
* <p>Only update the policy if the revision ID matches the ID specified. Use this
* option to avoid modifying a policy that has changed since you last read it.</p>
*/
inline void SetRevisionId(const char* value) { m_revisionIdHasBeenSet = true; m_revisionId.assign(value); }
/**
* <p>Only update the policy if the revision ID matches the ID specified. Use this
* option to avoid modifying a policy that has changed since you last read it.</p>
*/
inline AddLayerVersionPermissionRequest& WithRevisionId(const Aws::String& value) { SetRevisionId(value); return *this;}
/**
* <p>Only update the policy if the revision ID matches the ID specified. Use this
* option to avoid modifying a policy that has changed since you last read it.</p>
*/
inline AddLayerVersionPermissionRequest& WithRevisionId(Aws::String&& value) { SetRevisionId(std::move(value)); return *this;}
/**
* <p>Only update the policy if the revision ID matches the ID specified. Use this
* option to avoid modifying a policy that has changed since you last read it.</p>
*/
inline AddLayerVersionPermissionRequest& WithRevisionId(const char* value) { SetRevisionId(value); return *this;}
private:
Aws::String m_layerName;
bool m_layerNameHasBeenSet;
long long m_versionNumber;
bool m_versionNumberHasBeenSet;
Aws::String m_statementId;
bool m_statementIdHasBeenSet;
Aws::String m_action;
bool m_actionHasBeenSet;
Aws::String m_principal;
bool m_principalHasBeenSet;
Aws::String m_organizationId;
bool m_organizationIdHasBeenSet;
Aws::String m_revisionId;
bool m_revisionIdHasBeenSet;
};
} // namespace Model
} // namespace Lambda
} // namespace Aws
|
cedral/aws-sdk-cpp
|
aws-cpp-sdk-lambda/include/aws/lambda/model/AddLayerVersionPermissionRequest.h
|
C
|
apache-2.0
| 14,175
|
/*
* Copyright © 2015-2016
*
* This file is part of Spoofax for IntelliJ.
*
* 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.metaborg.intellij.idea.gui.languagespanel;
import org.metaborg.core.language.*;
import org.metaborg.intellij.idea.graphics.IIconManager;
import javax.annotation.Nullable;
import javax.swing.*;
/**
* A language node.
*/
public final class LanguageNode extends TreeNodeWithValue<ILanguage, LanguageNode>
implements ITreeNodeWithIcon, ILanguageTreeNode<ILanguage> {
private final IIconManager iconManager;
/**
* Initializes a new instance of the {@link LanguageNode} class.
*
* @param language The language.
* @param iconManager The icon manager.
*/
public LanguageNode(@Nullable final ILanguage language, final IIconManager iconManager) {
super(language);
this.iconManager = iconManager;
}
/**
* {@inheritDoc}
*/
@Nullable
@Override
public Object getValueOfColumn(final ModelColumnInfo<LanguageNode> column) {
return getName();
}
/**
* {@inheritDoc}
*/
@Nullable
@Override
public Icon getIcon() {
return this.iconManager.getLanguageFileIcon(this.getValue());
}
/**
* {@inheritDoc}
*/
@Nullable
@Override
public String getName() {
if (getValue() != null)
return getValue().name();
else
return "Unknown";
}
/**
* {@inheritDoc}
*/
@Override
@Nullable
public String getGroupId() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
@Nullable
public LanguageVersion getVersion() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
@Nullable
public LanguageStatus getStatus() {
return null;
}
}
|
metaborg/spoofax-intellij
|
src/main/java/org/metaborg/intellij/idea/gui/languagespanel/LanguageNode.java
|
Java
|
apache-2.0
| 2,373
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_72) on Wed May 13 11:47:55 EDT 2015 -->
<title>Uses of Class org.apache.cassandra.thrift.KeyRange._Fields (apache-cassandra API)</title>
<meta name="date" content="2015-05-13">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.cassandra.thrift.KeyRange._Fields (apache-cassandra API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/thrift/class-use/KeyRange._Fields.html" target="_top">Frames</a></li>
<li><a href="KeyRange._Fields.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.cassandra.thrift.KeyRange._Fields" class="title">Uses of Class<br>org.apache.cassandra.thrift.KeyRange._Fields</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">KeyRange._Fields</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.cassandra.thrift">org.apache.cassandra.thrift</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.cassandra.thrift">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">KeyRange._Fields</a> in <a href="../../../../../org/apache/cassandra/thrift/package-summary.html">org.apache.cassandra.thrift</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../org/apache/cassandra/thrift/package-summary.html">org.apache.cassandra.thrift</a> with type parameters of type <a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">KeyRange._Fields</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static java.util.Map<<a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">KeyRange._Fields</a>,org.apache.thrift.meta_data.FieldMetaData></code></td>
<td class="colLast"><span class="strong">KeyRange.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/KeyRange.html#metaDataMap">metaDataMap</a></strong></code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/apache/cassandra/thrift/package-summary.html">org.apache.cassandra.thrift</a> that return <a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">KeyRange._Fields</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">KeyRange._Fields</a></code></td>
<td class="colLast"><span class="strong">KeyRange.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/KeyRange.html#fieldForId(int)">fieldForId</a></strong>(int fieldId)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">KeyRange._Fields</a></code></td>
<td class="colLast"><span class="strong">KeyRange._Fields.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html#findByName(java.lang.String)">findByName</a></strong>(java.lang.String name)</code>
<div class="block">Find the _Fields constant that matches name, or null if its not found.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">KeyRange._Fields</a></code></td>
<td class="colLast"><span class="strong">KeyRange._Fields.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html#findByThriftId(int)">findByThriftId</a></strong>(int fieldId)</code>
<div class="block">Find the _Fields constant that matches fieldId, or null if its not found.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">KeyRange._Fields</a></code></td>
<td class="colLast"><span class="strong">KeyRange._Fields.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html#findByThriftIdOrThrow(int)">findByThriftIdOrThrow</a></strong>(int fieldId)</code>
<div class="block">Find the _Fields constant that matches fieldId, throwing an exception
if it is not found.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">KeyRange._Fields</a></code></td>
<td class="colLast"><span class="strong">KeyRange._Fields.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html#valueOf(java.lang.String)">valueOf</a></strong>(java.lang.String name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">KeyRange._Fields</a>[]</code></td>
<td class="colLast"><span class="strong">KeyRange._Fields.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html#values()">values</a></strong>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/apache/cassandra/thrift/package-summary.html">org.apache.cassandra.thrift</a> with parameters of type <a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">KeyRange._Fields</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>java.lang.Object</code></td>
<td class="colLast"><span class="strong">KeyRange.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/KeyRange.html#getFieldValue(org.apache.cassandra.thrift.KeyRange._Fields)">getFieldValue</a></strong>(<a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">KeyRange._Fields</a> field)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><span class="strong">KeyRange.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/KeyRange.html#isSet(org.apache.cassandra.thrift.KeyRange._Fields)">isSet</a></strong>(<a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">KeyRange._Fields</a> field)</code>
<div class="block">Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">KeyRange.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/KeyRange.html#setFieldValue(org.apache.cassandra.thrift.KeyRange._Fields,%20java.lang.Object)">setFieldValue</a></strong>(<a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">KeyRange._Fields</a> field,
java.lang.Object value)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/cassandra/thrift/KeyRange._Fields.html" title="enum in org.apache.cassandra.thrift">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/thrift/class-use/KeyRange._Fields.html" target="_top">Frames</a></li>
<li><a href="KeyRange._Fields.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2015 The Apache Software Foundation</small></p>
</body>
</html>
|
anuragkapur/cassandra-2.1.2-ak-skynet
|
apache-cassandra-2.0.15/javadoc/org/apache/cassandra/thrift/class-use/KeyRange._Fields.html
|
HTML
|
apache-2.0
| 12,451
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "driver.h"
#include <ros/ros.h>
#include <time.h>
#include <cmath>
#include <string>
namespace apollo {
namespace drivers {
namespace rslidar {
RslidarDriver::RslidarDriver() : basetime_(0), last_gps_time_(0) {}
void RslidarDriver::set_base_time_from_nmea_time(const NMEATimePtr& nmea_time,
uint64_t& basetime) {
tm time;
time.tm_year = nmea_time->year + (2000 - 1900);
time.tm_mon = nmea_time->mon - 1;
time.tm_mday = nmea_time->day;
time.tm_hour = nmea_time->hour;
time.tm_min = 0;
time.tm_sec = 0;
// set last gps time using gps socket packet
last_gps_time_ = (nmea_time->min * 60 + nmea_time->sec) * 1e6;
ROS_INFO("Set base unix time : %d-%d-%d %d:%d:%d", time.tm_year, time.tm_mon,
time.tm_mday, time.tm_hour, time.tm_min, time.tm_sec);
uint64_t unix_base = static_cast<uint64_t>(timegm(&time));
basetime = unix_base * 1e6;
}
bool RslidarDriver::set_base_time() {
NMEATimePtr nmea_time(new NMEATime);
set_base_time_from_nmea_time(nmea_time, basetime_);
input_->init(config_.msop_data_port);
return true;
}
int RslidarDriver::poll_standard(rslidar_msgs::rslidarScanPtr& scan) {
scan->packets.resize(config_.npackets);
for (int i = 0; i < config_.npackets; ++i) {
while (true) {
// keep reading until full packet received
int rc = input_->get_msop_data_packet(&scan->packets[i]);
if (rc == 0) {
break; // got a full packet?
}else if (rc < 0) {
return rc;
}
}
}
return 0;
}
void RslidarDriver::update_gps_top_hour(uint32_t current_time) {
if (last_gps_time_ == 0) {
last_gps_time_ = current_time;
return;
}
if (last_gps_time_ > current_time) {
if (std::abs(last_gps_time_ - current_time) > 3599000000) {
basetime_ += 3600 * 1e6;
ROS_INFO_STREAM("Base time plus 3600s. Model: "
<< config_.model << std::fixed << ". current:"
<< current_time << ", last time:" << last_gps_time_);
} else {
ROS_WARN_STREAM("Currrnt stamp:" << std::fixed << current_time
<< " less than previous statmp:"
<< last_gps_time_
<< ". GPS time stamp maybe incorrect!");
}
}
last_gps_time_ = current_time;
}
RslidarDriver* RslidarDriverFactory::create_driver(
ros::NodeHandle private_nh) {
Config config;
// use private node handle to get parameters
private_nh.param("frame_id", config.frame_id, std::string("rslidar"));
private_nh.param("model", config.model, std::string("RS16"));
private_nh.param("topic", config.topic, std::string("rslidar_packets"));
private_nh.param("msop_data_port", config.msop_data_port,
MSOP_DATA_PORT);
private_nh.param("difop_data_port", config.difop_data_port,
DIFOP_DATA_PORT);
private_nh.param("rpm", config.rpm, 600.0);
double packet_rate;
if (config.model == "RS16") {
packet_rate = 840;
return new Rslidar16Driver(config);
} else if (config.model == "RS32") {
packet_rate = 1690;
return new Rslidar32Driver(config);
} else {
ROS_ERROR_STREAM("unknown LIDAR model: " << config.model);
packet_rate = 2600.0;
return nullptr;
}
}
} // namespace rslidar
} // namespace drivers
} // namespace apollo
|
startcode/apollo
|
modules/drivers/rslidar/rslidar_driver/src/driver/driver.cpp
|
C++
|
apache-2.0
| 4,175
|
#include "relay.h"
#include "../net/tcpsocket.h"
#include "../core/timeout.h"
#include <chrono>
namespace Epyx
{
namespace N2NP
{
Relay::Relay(const SockAddress& addr)
:WorkerPool(1, "Relay@" + addr.toString()),
relayAddr(addr), relayId(addr), nodeNextId(1) {
log::info << "Relay: Start " << relayId << log::endl;
}
NodeId Relay::attachNode(const std::shared_ptr<Socket>& sock) {
EPYX_ASSERT(sock);
// Build a random unique node name
std::ostringstream nodeNameStream;
unsigned long number = std::atomic_fetch_add(&nodeNextId, 1UL);
if (number == 1) {
nodeNameStream << "self";
} else {
nodeNameStream << number << '-' << sock->getAddress();
}
const std::string nodeName = nodeNameStream.str();
const NodeId nodeid(nodeName.c_str(), relayAddr);
// Insert new node information
{
std::unique_ptr<NodeInfo> node(new NodeInfo(nodeid, sock));
std::lock_guard<std::mutex> lock(nodesMutex);
nodes[nodeName].swap(node);
}
log::info << "Relay: Attach node " << nodeid
<< " from " << sock->getAddress() << log::endl;
// Send IP to node in data
std::ostringstream dataStream;
dataStream << "IP: " << sock->getAddress() << String::crlf;
const std::string dataString = dataStream.str();
Packet pkt("ID", string2bytes_c(dataString));
pkt.from = relayId;
pkt.to = nodeid;
sock->sendBytes(pkt.build());
// Notify everybody there's a new node
nodesCond.notify_all();
// Return ID
return nodeid;
}
bool Relay::detachNode(const NodeId& nodeid) {
if (nodeid.getRelay() != relayAddr)
return false;
log::info << "Relay: Detach node " << nodeid << log::endl;
std::lock_guard<std::mutex> lock(nodesMutex);
nodes.erase(nodeid.getName());
nodesCond.notify_all();
return true;
}
bool Relay::waitForAllDetach(int msec) {
std::unique_lock<std::mutex> lock(nodesMutex);
while (!nodes.empty()) {
if (nodesCond.wait_for(lock, std::chrono::milliseconds(msec)) == std::cv_status::timeout) {
// Timeout
return nodes.empty();
}
}
return true;
}
void Relay::detachAllNodes() {
// Delete every Node information
std::lock_guard<std::mutex> lock(nodesMutex);
nodes.clear();
nodesCond.notify_all();
}
const NodeId& Relay::getId() const {
return relayId;
}
void Relay::treat(std::unique_ptr<Packet> pkt) {
EPYX_ASSERT(pkt);
// TODO: Send a message back to from node when an error happens
// Send packet to another relay
const SockAddress toAddr = pkt->to.getRelay();
if (toAddr != relayAddr) {
TCPSocket toSock(toAddr);
//log::info << "Relay " << relayId << ": Transmit " << *pkt << log::endl;
if (!toSock.sendBytes(pkt->build())) {
log::error << "[Relay " << relayId << "] Unable to transmit packet "
<< *pkt << log::endl;
return;
}
// OK, packet was successfully transmitted
return;
}
// Packet is for one of my nodes. Let's find it in the map !
std::lock_guard<std::mutex> lock(nodesMutex);
// node is an iterator on a map
auto nodeit = nodes.find(pkt->to.getName());
if (nodeit == nodes.end()) {
log::error << "[Relay " << relayId << "] Destination not found: "
<< *pkt << log::endl;
return;
}
// Send packet
//log::info << "Relay " << relayId << ": Send " << *pkt << log::endl;
if (!nodeit->second->sock->sendBytes(pkt->build())) {
log::error << "[Relay " << relayId << "] Unable to send packet "
<< *pkt << log::endl;
return;
}
}
Relay::NodeInfo::NodeInfo(const NodeId& id, const std::shared_ptr<Socket>& sock)
:id(id), sock(sock) {
}
Relay::NodeInfo::~NodeInfo() {
// Close the socket
if (sock) {
sock->close();
}
}
}
}
|
Kangz/epyx
|
src/n2np/relay.cpp
|
C++
|
apache-2.0
| 4,769
|
'use strict';
module.exports = {
ClientRequest: function () {}
};
|
StackStorm/st2client.js
|
lib/util/http.js
|
JavaScript
|
apache-2.0
| 69
|
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Facilities for creating multiple test combinations.
Here is an example of testing various optimizers in Eager and Graph mode:
class AdditionExample(test.TestCase, parameterized.TestCase):
@combinations.generate(
combinations.combine(mode=["graph", "eager"],
optimizer=[AdamOptimizer(),
GradientDescentOptimizer()]))
def testOptimizer(self, optimizer):
... f(optimizer)...
This will run `testOptimizer` 4 times with the specified optimizers: 2 in
Eager and 2 in Graph mode.
The test will be provided with arguments that match the arguments of combine
by name. It is necessary to request all arguments, except for `mode`, which is
optional.
`combine()` function is available for creating a cross product of various
options. `times()` function exists for creating a product of N `combine()`-ed
results. See below.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import OrderedDict
import sys
import types
import unittest
from absl.testing import parameterized
import six
from tensorflow.contrib.cluster_resolver import TPUClusterResolver
from tensorflow.contrib.distribute.python import mirrored_strategy as mirrored_lib
from tensorflow.contrib.distribute.python import one_device_strategy as one_device_lib
from tensorflow.contrib.distribute.python import tpu_strategy as tpu_lib
from tensorflow.contrib.optimizer_v2 import adagrad as adagrad_v2
from tensorflow.contrib.optimizer_v2 import adam as adam_v2
from tensorflow.contrib.optimizer_v2 import gradient_descent as gradient_descent_v2
from tensorflow.python.distribute import distribution_strategy_context
from tensorflow.python.eager import context
from tensorflow.python.framework import ops
from tensorflow.python.training import adagrad
from tensorflow.python.training import adam
from tensorflow.python.training import gradient_descent
from tensorflow.python.training import rmsprop
from tensorflow.python.util import tf_inspect
GPU_TEST = "test_gpu" in sys.argv[0]
TPU_TEST = "test_tpu" in sys.argv[0]
def generate(combinations):
"""A decorator for generating test cases of a test method or a test class.
Args:
combinations: a list of dictionaries created using combine() and times().
Restrictions:
-- the "mode" argument can be either "eager" or "graph". It's "graph" by
default.
-- arguments of the test method must match by name to get the corresponding
value of the combination. Tests must accept all arguments except the
"mode", "required_tpu" and "required_gpus".
-- "distribution" argument is special and optional. It is meant for passing
instances of DistributionStrategy. Each instance is to be passed as via
`NamedDistribution`. If using "distribution", "required_gpus" and
"required_tpu" should be specified via the NamedDistribution instance,
rather than as separate arguments.
-- "required_tpu" argument is special and optional. If not `None`, then the
test will be skipped if TPUs aren't available.
-- "required_gpus" argument is special and optional. If not `None`, then the
test will be skipped if the specified number of GPUs aren't available.
Returns:
a decorator that will cause the test method or the test class to be run
under the specified conditions.
Raises:
ValueError - if "mode" argument wasn't either "eager" or "graph" or if other
arguments were not accepted by the test method.
"""
def decorator(test_method_or_class):
"""The decorator to be returned."""
# Generate good test names that can be used with --test_filter.
named_combinations = []
for combination in combinations:
# We use OrderedDicts in `combine()` and `times()` to ensure stable
# order of keys in each dictionary.
assert isinstance(combination, OrderedDict)
name = "".join([
"_{}_{}".format(
"".join(filter(str.isalnum, key)),
"".join(filter(str.isalnum, str(value))))
for key, value in combination.items()
])
named_combinations.append(
OrderedDict(
list(combination.items()) + [("testcase_name",
"_test{}".format(name))]))
if isinstance(test_method_or_class, type):
class_object = test_method_or_class
class_object._test_method_ids = test_method_ids = {}
for name, test_method in six.iteritems(class_object.__dict__.copy()):
if (name.startswith(unittest.TestLoader.testMethodPrefix) and
isinstance(test_method, types.FunctionType)):
delattr(class_object, name)
methods = {}
parameterized._update_class_dict_for_param_test_case(
class_object.__name__, methods, test_method_ids, name,
parameterized._ParameterizedTestIter(
_augment_with_special_arguments(test_method),
named_combinations, parameterized._NAMED, name))
for method_name, method in six.iteritems(methods):
setattr(class_object, method_name, method)
return class_object
else:
test_method = _augment_with_special_arguments(test_method_or_class)
return parameterized.named_parameters(*named_combinations)(test_method)
return decorator
def _augment_with_special_arguments(test_method):
def decorated(self, **kwargs):
"""A wrapped test method that treats some arguments in a special way."""
mode = kwargs.pop("mode", "graph")
distribution = kwargs.get("distribution", None)
required_tpu = kwargs.pop("required_tpu", False)
required_gpus = kwargs.pop("required_gpus", None)
if distribution:
assert required_gpus is None, (
"Do not use `required_gpus` and `distribution` together.")
assert required_tpu is False, (
"Do not use `required_tpu` and `distribution` together.")
required_gpus = distribution.required_gpus
required_tpu = distribution.required_tpu
if required_tpu and not TPU_TEST:
self.skipTest("Test requires a TPU, but it's not available.")
if not required_tpu and TPU_TEST:
self.skipTest("Test that doesn't require a TPU.")
if not required_gpus:
if GPU_TEST:
self.skipTest("Test that doesn't require GPUs.")
elif context.num_gpus() < required_gpus:
# TODO(priyag): Consider allowing tests in graph mode using soft
# placement.
self.skipTest(
"{} GPUs are not available for this test. {} GPUs are available".
format(required_gpus, context.num_gpus()))
# At this point, `kwargs` doesn't have `required_gpus` or `required_tpu`
# that the user might have specified. `kwargs` still has `mode`, which
# the test is allowed to accept or ignore.
requested_arguments = tf_inspect.getfullargspec(test_method).args
missing_arguments = set(list(kwargs.keys()) + ["self"]).difference(
set(requested_arguments + ["mode"]))
if missing_arguments:
raise ValueError("The test is missing arguments {} .".format(
missing_arguments))
kwargs_to_pass = {}
for arg in requested_arguments:
if arg == "self":
kwargs_to_pass[arg] = self
else:
kwargs_to_pass[arg] = kwargs[arg]
if mode == "eager":
with context.eager_mode():
if distribution:
kwargs_to_pass["distribution"] = distribution.strategy
test_method(**kwargs_to_pass)
elif mode == "graph":
with ops.Graph().as_default(), context.graph_mode():
if distribution:
kwargs_to_pass["distribution"] = distribution.strategy
test_method(**kwargs_to_pass)
else:
raise ValueError(
"'mode' has to be either 'eager' or 'graph' and not {}".format(
mode))
return decorated
def combine(**kwargs):
"""Generate combinations based on its keyword arguments.
Two sets of returned combinations can be concatenated using +. Their product
can be computed using `times()`.
Args:
**kwargs: keyword arguments of form `option=[possibilities, ...]`
or `option=the_only_possibility`.
Returns:
a list of dictionaries for each combination. Keys in the dictionaries are
the keyword argument names. Each key has one value - one of the
corresponding keyword argument values.
"""
if not kwargs:
return [OrderedDict()]
sort_by_key = lambda k: k[0][0]
kwargs = OrderedDict(sorted(kwargs.items(), key=sort_by_key))
first = list(kwargs.items())[0]
rest = dict(list(kwargs.items())[1:])
rest_combined = combine(**rest)
key = first[0]
values = first[1]
if not isinstance(values, list):
values = [values]
return [
OrderedDict(sorted(list(combined.items()) + [(key, v)], key=sort_by_key))
for v in values
for combined in rest_combined
]
def times(*combined):
"""Generate a product of N sets of combinations.
times(combine(a=[1,2]), combine(b=[3,4])) == combine(a=[1,2], b=[3,4])
Args:
*combined: N lists of dictionaries that specify combinations.
Returns:
a list of dictionaries for each combination.
Raises:
ValueError: if some of the inputs have overlapping keys.
"""
assert combined
if len(combined) == 1:
return combined[0]
first = combined[0]
rest_combined = times(*combined[1:])
combined_results = []
for a in first:
for b in rest_combined:
if set(a.keys()).intersection(set(b.keys())):
raise ValueError("Keys need to not overlap: {} vs {}".format(
a.keys(), b.keys()))
combined_results.append(OrderedDict(list(a.items()) + list(b.items())))
return combined_results
class NamedObject(object):
"""A class that translates an object into a good test name."""
def __init__(self, name, obj):
self._name = name
self._obj = obj
def __getattr__(self, name):
return getattr(self._obj, name)
def __call__(self, *args, **kwargs):
return self._obj(*args, **kwargs)
def __repr__(self):
return self._name
class NamedDistribution(object):
"""Translates DistributionStrategy and its data into a good name."""
def __init__(self, name, distribution_fn, required_gpus=None,
required_tpu=False):
self._distribution_fn = distribution_fn
self._name = name
self._required_gpus = required_gpus
self._required_tpu = required_tpu
def __repr__(self):
return self._name
@property
def strategy(self):
return self._distribution_fn()
@property
def required_gpus(self):
return self._required_gpus
@property
def required_tpu(self):
return self._required_tpu
# pylint: disable=g-long-lambda
default_strategy = NamedDistribution(
"Default",
distribution_strategy_context._get_default_distribution_strategy, # pylint: disable=protected-access
required_gpus=None)
one_device_strategy = NamedDistribution(
"OneDeviceCPU", lambda: one_device_lib.OneDeviceStrategy("/cpu:0"),
required_gpus=None)
tpu_strategy = NamedDistribution(
"TPU", lambda: tpu_lib.TPUStrategy(
TPUClusterResolver(""), steps_per_run=2),
required_tpu=True)
tpu_strategy_one_step = NamedDistribution(
"TPUOneStep", lambda: tpu_lib.TPUStrategy(
TPUClusterResolver(""), steps_per_run=1),
required_tpu=True)
mirrored_strategy_with_one_cpu = NamedDistribution(
"Mirrored1CPU",
lambda: mirrored_lib.MirroredStrategy(["/cpu:0"]))
mirrored_strategy_with_one_gpu = NamedDistribution(
"Mirrored1GPU",
lambda: mirrored_lib.MirroredStrategy(["/gpu:0"]),
required_gpus=1)
mirrored_strategy_with_gpu_and_cpu = NamedDistribution(
"MirroredCPUAndGPU",
lambda: mirrored_lib.MirroredStrategy(["/gpu:0", "/cpu:0"]),
required_gpus=1)
mirrored_strategy_with_two_gpus = NamedDistribution(
"Mirrored2GPUs",
lambda: mirrored_lib.MirroredStrategy(["/gpu:0", "/gpu:1"]),
required_gpus=2)
core_mirrored_strategy_with_one_cpu = NamedDistribution(
"CoreMirrored1CPU",
lambda: mirrored_lib.CoreMirroredStrategy(["/cpu:0"]))
core_mirrored_strategy_with_one_gpu = NamedDistribution(
"CoreMirrored1GPU",
lambda: mirrored_lib.CoreMirroredStrategy(["/gpu:0"]),
required_gpus=1)
core_mirrored_strategy_with_gpu_and_cpu = NamedDistribution(
"CoreMirroredCPUAndGPU",
lambda: mirrored_lib.CoreMirroredStrategy(["/gpu:0", "/cpu:0"]),
required_gpus=1)
core_mirrored_strategy_with_two_gpus = NamedDistribution(
"CoreMirrored2GPUs",
lambda: mirrored_lib.CoreMirroredStrategy(["/gpu:0", "/gpu:1"]),
required_gpus=2)
gradient_descent_optimizer_v1_fn = NamedObject(
"GradientDescentV1", lambda: gradient_descent.GradientDescentOptimizer(0.2))
adagrad_optimizer_v1_fn = NamedObject(
"AdagradV1", lambda: adagrad.AdagradOptimizer(0.001))
adam_optimizer_v1_fn = NamedObject("AdamV1",
lambda: adam.AdamOptimizer(0.001, epsilon=1))
rmsprop_optimizer_v1_fn = NamedObject(
"RmsPropV1", lambda: rmsprop.RMSPropOptimizer(0.001))
optimizers_v1 = [gradient_descent_optimizer_v1_fn, adagrad_optimizer_v1_fn]
gradient_descent_optimizer_v2_fn = NamedObject(
"GradientDescentV2",
lambda: gradient_descent_v2.GradientDescentOptimizer(0.2))
adagrad_optimizer_v2_fn = NamedObject(
"AdagradV2", lambda: adagrad_v2.AdagradOptimizer(0.001))
adam_optimizer_v2_fn = NamedObject(
"AdamV2", lambda: adam_v2.AdamOptimizer(0.001, epsilon=1))
optimizers_v2 = [gradient_descent_optimizer_v2_fn, adagrad_optimizer_v2_fn]
graph_and_eager_modes = ["graph", "eager"]
def distributions_and_v1_optimizers():
"""A common set of combination with DistributionStrategies and Optimizers."""
return combine(
distribution=[
one_device_strategy,
mirrored_strategy_with_gpu_and_cpu,
mirrored_strategy_with_two_gpus,
core_mirrored_strategy_with_gpu_and_cpu,
core_mirrored_strategy_with_two_gpus,
],
optimizer_fn=optimizers_v1)
def distributions_and_v2_optimizers():
"""DistributionStrategies and V2 Optimizers."""
return combine(
distribution=[
one_device_strategy,
mirrored_strategy_with_gpu_and_cpu,
mirrored_strategy_with_two_gpus,
core_mirrored_strategy_with_gpu_and_cpu,
core_mirrored_strategy_with_two_gpus,
],
optimizer_fn=optimizers_v2)
|
asimshankar/tensorflow
|
tensorflow/contrib/distribute/python/combinations.py
|
Python
|
apache-2.0
| 15,137
|
package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_6179 {
}
|
lesaint/experimenting-annotation-processing
|
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_6179.java
|
Java
|
apache-2.0
| 151
|
// 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.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class OutKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public OutKeywordRecommender()
: base(SyntaxKind.OutKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
// TODO(cyrusn): lambda/anon methods can have out/ref parameters
return
context.TargetToken.IsTypeParameterVarianceContext() ||
IsOutParameterModifierContext(position, context) ||
syntaxTree.IsAnonymousMethodParameterModifierContext(position, context.LeftToken) ||
syntaxTree.IsPossibleLambdaParameterModifierContext(position, context.LeftToken) ||
context.TargetToken.IsConstructorOrMethodParameterArgumentContext() ||
context.TargetToken.IsXmlCrefParameterModifierContext();
}
private static bool IsOutParameterModifierContext(int position, CSharpSyntaxContext context)
{
return context.SyntaxTree.IsParameterModifierContext(
position, context.LeftToken, includeOperators: false, out _, out var previousModifier) &&
previousModifier == SyntaxKind.None;
}
}
}
|
aelij/roslyn
|
src/Features/CSharp/Portable/Completion/KeywordRecommenders/OutKeywordRecommender.cs
|
C#
|
apache-2.0
| 1,676
|
package bootstrap
import (
"fmt"
"os"
"syscall"
"time"
"github.com/funkygao/gafka"
log "github.com/funkygao/log4go"
)
var (
logLevel log.Level
)
func SetupLogging(logFile, level, crashLogFile string) {
logLevel = log.ToLogLevel(level, log.TRACE)
log.SetLevel(logLevel)
log.LogBufferLength = 10 << 10 // default 32, chan cap
if logFile != "stdout" {
log.DeleteFilter("stdout")
rotateEnabled, discardWhenDiskFull := true, false
filer := log.NewFileLogWriter(logFile, rotateEnabled, discardWhenDiskFull, 0644)
filer.SetFormat("[%d %T] [%L] (%S) %M")
if Options.LogRotateSize > 0 {
filer.SetRotateSize(Options.LogRotateSize)
}
filer.SetRotateKeepDuration(time.Hour * 24 * 30)
filer.SetRotateLines(0)
filer.SetRotateDaily(true)
log.AddFilter("file", logLevel, filer)
}
if crashLogFile != "" {
f, err := os.OpenFile(crashLogFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
syscall.Dup2(int(f.Fd()), int(os.Stdout.Fd()))
syscall.Dup2(int(f.Fd()), int(os.Stderr.Fd()))
fmt.Fprintf(os.Stderr, "\n%s %s (build: %s)\n===================\n",
time.Now().String(),
gafka.Version, gafka.BuildId)
}
}
|
funkygao/gafka
|
cmd/actord/bootstrap/log.go
|
GO
|
apache-2.0
| 1,181
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.documentapi.messagebus.protocol;
import com.yahoo.document.BucketId;
import java.util.ArrayList;
import java.util.List;
public class DocumentListMessage extends VisitorMessage {
private BucketId bucket = new BucketId(16, 0);
private final List<DocumentListEntry> entries = new ArrayList<DocumentListEntry>();
public DocumentListMessage() {
// empty
}
public DocumentListMessage(DocumentListMessage cmd) {
bucket = cmd.bucket;
entries.addAll(cmd.entries);
}
public BucketId getBucketId() {
return bucket;
}
public void setBucketId(BucketId id) {
bucket = id;
}
public List<DocumentListEntry> getDocuments() {
return entries;
}
@Override
public DocumentReply createReply() {
return new VisitorReply(DocumentProtocol.REPLY_DOCUMENTLIST);
}
@Override
public int getType() {
return DocumentProtocol.MESSAGE_DOCUMENTLIST;
}
@Override
public int getApproxSize() {
return DocumentListEntry.getApproxSize() * entries.size();
}
@Override
public String toString() {
return "DocumentListMessage(" + entries.toString() + ")";
}
}
|
vespa-engine/vespa
|
documentapi/src/main/java/com/yahoo/documentapi/messagebus/protocol/DocumentListMessage.java
|
Java
|
apache-2.0
| 1,329
|
# PBDictionary
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**vintage** | **NSString*** | | [optional]
**source** | **NSString*** | | [optional]
**_description** | **NSString*** | | [optional]
**countrySupportInfos** | [**NSArray<PBCountrySupport>***](PBCountrySupport.md) | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
|
PitneyBowes/LocationIntelligenceSDK-IOS
|
docs/PBDictionary.md
|
Markdown
|
apache-2.0
| 532
|
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="Javadoc API documentation for Fresco." />
<link rel="shortcut icon" type="image/x-icon" href="../../../../favicon.ico" />
<title>
OrientedDrawable - Fresco API
| Fresco
</title>
<link href="../../../../../assets/doclava-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../../../../../assets/customizations.css" rel="stylesheet" type="text/css" />
<script src="../../../../../assets/search_autocomplete.js" type="text/javascript"></script>
<script src="../../../../../assets/jquery-resizable.min.js" type="text/javascript"></script>
<script src="../../../../../assets/doclava-developer-docs.js" type="text/javascript"></script>
<script src="../../../../../assets/prettify.js" type="text/javascript"></script>
<script type="text/javascript">
setToRoot("../../../../", "../../../../../assets/");
</script>
<script src="../../../../../assets/doclava-developer-reference.js" type="text/javascript"></script>
<script src="../../../../../assets/navtree_data.js" type="text/javascript"></script>
<script src="../../../../../assets/customizations.js" type="text/javascript"></script>
<noscript>
<style type="text/css">
html,body{overflow:auto;}
#body-content{position:relative; top:0;}
#doc-content{overflow:visible;border-left:3px solid #666;}
#side-nav{padding:0;}
#side-nav .toggle-list ul {display:block;}
#resize-packages-nav{border-bottom:3px solid #666;}
</style>
</noscript>
</head>
<body class="">
<div id="header">
<div id="headerLeft">
<span id="masthead-title"><a href="../../../../packages.html">Fresco</a></span>
</div>
<div id="headerRight">
<div id="search" >
<div id="searchForm">
<form accept-charset="utf-8" class="gsc-search-box"
onsubmit="return submit_search()">
<table class="gsc-search-box" cellpadding="0" cellspacing="0"><tbody>
<tr>
<td class="gsc-input">
<input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off"
title="search developer docs" name="q"
value="search developer docs"
onFocus="search_focus_changed(this, true)"
onBlur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../')"
onkeyup="return search_changed(event, false, '../../../../')" />
<div id="search_filtered_div" class="no-display">
<table id="search_filtered" cellspacing=0>
</table>
</div>
</td>
<!-- <td class="gsc-search-button">
<input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" />
</td>
<td class="gsc-clear-button">
<div title="clear results" class="gsc-clear-button"> </div>
</td> -->
</tr></tbody>
</table>
</form>
</div><!-- searchForm -->
</div><!-- search -->
</div>
</div><!-- header -->
<div class="g-section g-tpl-240" id="body-content">
<div class="g-unit g-first side-nav-resizable" id="side-nav">
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav">
<div id="index-links">
<a href="../../../../packages.html" >Packages</a> |
<a href="../../../../classes.html" >Classes</a>
</div>
<ul>
<li class="api apilevel-">
<a href="../../../../com/facebook/animated/gif/package-summary.html">com.facebook.animated.gif</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/animated/webp/package-summary.html">com.facebook.animated.webp</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/binaryresource/package-summary.html">com.facebook.binaryresource</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/cache/common/package-summary.html">com.facebook.cache.common</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/cache/disk/package-summary.html">com.facebook.cache.disk</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/activitylistener/package-summary.html">com.facebook.common.activitylistener</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/disk/package-summary.html">com.facebook.common.disk</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/executors/package-summary.html">com.facebook.common.executors</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/file/package-summary.html">com.facebook.common.file</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/internal/package-summary.html">com.facebook.common.internal</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/lifecycle/package-summary.html">com.facebook.common.lifecycle</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/logging/package-summary.html">com.facebook.common.logging</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/media/package-summary.html">com.facebook.common.media</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/memory/package-summary.html">com.facebook.common.memory</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/references/package-summary.html">com.facebook.common.references</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/soloader/package-summary.html">com.facebook.common.soloader</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/statfs/package-summary.html">com.facebook.common.statfs</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/streams/package-summary.html">com.facebook.common.streams</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/time/package-summary.html">com.facebook.common.time</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/util/package-summary.html">com.facebook.common.util</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/webp/package-summary.html">com.facebook.common.webp</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/datasource/package-summary.html">com.facebook.datasource</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawable/base/package-summary.html">com.facebook.drawable.base</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/backends/pipeline/package-summary.html">com.facebook.drawee.backends.pipeline</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/backends/volley/package-summary.html">com.facebook.drawee.backends.volley</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/components/package-summary.html">com.facebook.drawee.components</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/controller/package-summary.html">com.facebook.drawee.controller</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/debug/package-summary.html">com.facebook.drawee.debug</a></li>
<li class="selected api apilevel-">
<a href="../../../../com/facebook/drawee/drawable/package-summary.html">com.facebook.drawee.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/generic/package-summary.html">com.facebook.drawee.generic</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/gestures/package-summary.html">com.facebook.drawee.gestures</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/interfaces/package-summary.html">com.facebook.drawee.interfaces</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/span/package-summary.html">com.facebook.drawee.span</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/view/package-summary.html">com.facebook.drawee.view</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/backend/package-summary.html">com.facebook.fresco.animation.backend</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/bitmap/package-summary.html">com.facebook.fresco.animation.bitmap</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/bitmap/cache/package-summary.html">com.facebook.fresco.animation.bitmap.cache</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/bitmap/preparation/package-summary.html">com.facebook.fresco.animation.bitmap.preparation</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/bitmap/wrapper/package-summary.html">com.facebook.fresco.animation.bitmap.wrapper</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/drawable/package-summary.html">com.facebook.fresco.animation.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/drawable/animator/package-summary.html">com.facebook.fresco.animation.drawable.animator</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/factory/package-summary.html">com.facebook.fresco.animation.factory</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/frame/package-summary.html">com.facebook.fresco.animation.frame</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imageformat/package-summary.html">com.facebook.imageformat</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/animated/base/package-summary.html">com.facebook.imagepipeline.animated.base</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/animated/factory/package-summary.html">com.facebook.imagepipeline.animated.factory</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/animated/impl/package-summary.html">com.facebook.imagepipeline.animated.impl</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/animated/util/package-summary.html">com.facebook.imagepipeline.animated.util</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/backends/okhttp3/package-summary.html">com.facebook.imagepipeline.backends.okhttp3</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/backends/volley/package-summary.html">com.facebook.imagepipeline.backends.volley</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/bitmaps/package-summary.html">com.facebook.imagepipeline.bitmaps</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/cache/package-summary.html">com.facebook.imagepipeline.cache</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/common/package-summary.html">com.facebook.imagepipeline.common</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/core/package-summary.html">com.facebook.imagepipeline.core</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/datasource/package-summary.html">com.facebook.imagepipeline.datasource</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/decoder/package-summary.html">com.facebook.imagepipeline.decoder</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/drawable/package-summary.html">com.facebook.imagepipeline.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/image/package-summary.html">com.facebook.imagepipeline.image</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/listener/package-summary.html">com.facebook.imagepipeline.listener</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/memory/package-summary.html">com.facebook.imagepipeline.memory</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/nativecode/package-summary.html">com.facebook.imagepipeline.nativecode</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/platform/package-summary.html">com.facebook.imagepipeline.platform</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/postprocessors/package-summary.html">com.facebook.imagepipeline.postprocessors</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/producers/package-summary.html">com.facebook.imagepipeline.producers</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/request/package-summary.html">com.facebook.imagepipeline.request</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imageutils/package-summary.html">com.facebook.imageutils</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/webpsupport/package-summary.html">com.facebook.webpsupport</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/widget/text/span/package-summary.html">com.facebook.widget.text.span</a></li>
</ul><br/>
</div> <!-- end packages -->
</div> <!-- end resize-packages -->
<div id="classes-nav">
<ul>
<li><h2>Interfaces</h2>
<ul>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/CloneableDrawable.html">CloneableDrawable</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/DrawableParent.html">DrawableParent</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/Rounded.html">Rounded</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/ScalingUtils.ScaleType.html">ScalingUtils.ScaleType</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/ScalingUtils.StatefulScaleType.html">ScalingUtils.StatefulScaleType</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/TransformAwareDrawable.html">TransformAwareDrawable</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/TransformCallback.html">TransformCallback</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/VisibilityAwareDrawable.html">VisibilityAwareDrawable</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/VisibilityCallback.html">VisibilityCallback</a></li>
</ul>
</li>
<li><h2>Classes</h2>
<ul>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/ArrayDrawable.html">ArrayDrawable</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/AutoRotateDrawable.html">AutoRotateDrawable</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/DrawableProperties.html">DrawableProperties</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/DrawableUtils.html">DrawableUtils</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/FadeDrawable.html">FadeDrawable</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html">ForwardingDrawable</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/MatrixDrawable.html">MatrixDrawable</a></li>
<li class="selected api apilevel-"><a href="../../../../com/facebook/drawee/drawable/OrientedDrawable.html">OrientedDrawable</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/ProgressBarDrawable.html">ProgressBarDrawable</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/RoundedBitmapDrawable.html">RoundedBitmapDrawable</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/RoundedColorDrawable.html">RoundedColorDrawable</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/RoundedCornersDrawable.html">RoundedCornersDrawable</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/ScaleTypeDrawable.html">ScaleTypeDrawable</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/ScalingUtils.html">ScalingUtils</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/ScalingUtils.AbstractScaleType.html">ScalingUtils.AbstractScaleType</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/ScalingUtils.InterpolatingScaleType.html">ScalingUtils.InterpolatingScaleType</a></li>
</ul>
</li>
<li><h2>Enums</h2>
<ul>
<li class="api apilevel-"><a href="../../../../com/facebook/drawee/drawable/RoundedCornersDrawable.Type.html">RoundedCornersDrawable.Type</a></li>
</ul>
</li>
</ul><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none">
<div id="index-links">
<a href="../../../../packages.html" >Packages</a> |
<a href="../../../../classes.html" >Classes</a>
</div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
</div> <!-- end side-nav -->
<script>
if (!isMobile) {
//$("<a href='#' id='nav-swap' onclick='swapNav();return false;' style='font-size:10px;line-height:9px;margin-left:1em;text-decoration:none;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>").appendTo("#side-nav");
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("../../../../");
} else {
addLoadEvent(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
}
//$("#swapper").css({borderBottom:"2px solid #aaa"});
} else {
swapNav(); // tree view should be used on mobile
}
</script>
<div class="g-unit" id="doc-content">
<div id="api-info-block">
<div class="sum-details-links">
Summary:
<a href="#inhfields">Inherited Fields</a>
| <a href="#pubctors">Ctors</a>
| <a href="#pubmethods">Methods</a>
| <a href="#promethods">Protected Methods</a>
| <a href="#inhmethods">Inherited Methods</a>
| <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a>
</div><!-- end sum-details-links -->
<div class="api-level">
</div>
</div><!-- end api-info-block -->
<!-- ======== START OF CLASS DATA ======== -->
<div id="jd-header">
public
class
<h1>OrientedDrawable</h1>
extends <a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html">ForwardingDrawable</a><br/>
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-">
<table class="jd-inheritance-table">
<tr>
<td colspan="4" class="jd-inheritance-class-cell">java.lang.Object</td>
</tr>
<tr>
<td class="jd-inheritance-space"> ↳</td>
<td colspan="3" class="jd-inheritance-class-cell">android.graphics.drawable.Drawable</td>
</tr>
<tr>
<td class="jd-inheritance-space"> </td>
<td class="jd-inheritance-space"> ↳</td>
<td colspan="2" class="jd-inheritance-class-cell"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html">com.facebook.drawee.drawable.ForwardingDrawable</a></td>
</tr>
<tr>
<td class="jd-inheritance-space"> </td>
<td class="jd-inheritance-space"> </td>
<td class="jd-inheritance-space"> ↳</td>
<td colspan="1" class="jd-inheritance-class-cell">com.facebook.drawee.drawable.OrientedDrawable</td>
</tr>
</table>
<div class="jd-descr">
<h2>Class Overview</h2>
<p>Drawable that automatically rotates the underlying drawable with a pivot in the center of the
drawable bounds based on a rotation angle.
</p>
</div><!-- jd-descr -->
<div class="jd-descr">
<h2>Summary</h2>
<!-- =========== FIELD SUMMARY =========== -->
<table id="inhfields" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Fields</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-fields-com.facebook.drawee.drawable.ForwardingDrawable" class="jd-expando-trigger closed"
><img id="inherited-fields-com.facebook.drawee.drawable.ForwardingDrawable-trigger"
src="../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>From class
<a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html">com.facebook.drawee.drawable.ForwardingDrawable</a>
<div id="inherited-fields-com.facebook.drawee.drawable.ForwardingDrawable">
<div id="inherited-fields-com.facebook.drawee.drawable.ForwardingDrawable-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-fields-com.facebook.drawee.drawable.ForwardingDrawable-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
protected
<a href="../../../../com/facebook/drawee/drawable/TransformCallback.html">TransformCallback</a></td>
<td class="jd-linkcol"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#mTransformCallback">mTransformCallback</a></td>
<td class="jd-descrcol" width="100%"></td>
</tr>
</table>
</div>
</div>
</td></tr>
</table>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<table id="pubctors" class="jd-sumtable"><tr><th colspan="12">Public Constructors</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/OrientedDrawable.html#OrientedDrawable(android.graphics.drawable.Drawable, int)">OrientedDrawable</a></span>(Drawable drawable, int rotationAngle)
<div class="jd-descrdiv">Creates a new OrientedDrawable.</div>
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/OrientedDrawable.html#draw(android.graphics.Canvas)">draw</a></span>(Canvas canvas)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/OrientedDrawable.html#getIntrinsicHeight()">getIntrinsicHeight</a></span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/OrientedDrawable.html#getIntrinsicWidth()">getIntrinsicWidth</a></span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/OrientedDrawable.html#getTransform(android.graphics.Matrix)">getTransform</a></span>(Matrix transform)
<div class="jd-descrdiv">Called when the drawable needs to get all matrices applied to it.</div>
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="promethods" class="jd-sumtable"><tr><th colspan="12">Protected Methods</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/OrientedDrawable.html#onBoundsChange(android.graphics.Rect)">onBoundsChange</a></span>(Rect bounds)
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="inhmethods" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Methods</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-com.facebook.drawee.drawable.ForwardingDrawable" class="jd-expando-trigger closed"
><img id="inherited-methods-com.facebook.drawee.drawable.ForwardingDrawable-trigger"
src="../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From class
<a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html">com.facebook.drawee.drawable.ForwardingDrawable</a>
<div id="inherited-methods-com.facebook.drawee.drawable.ForwardingDrawable">
<div id="inherited-methods-com.facebook.drawee.drawable.ForwardingDrawable-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-com.facebook.drawee.drawable.ForwardingDrawable-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#draw(android.graphics.Canvas)">draw</a></span>(Canvas canvas)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
Drawable.ConstantState
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#getConstantState()">getConstantState</a></span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#getCurrent()">getCurrent</a></span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#getDrawable()">getDrawable</a></span>()
<div class="jd-descrdiv">Gets the child drawable.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#getIntrinsicHeight()">getIntrinsicHeight</a></span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#getIntrinsicWidth()">getIntrinsicWidth</a></span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#getOpacity()">getOpacity</a></span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#getPadding(android.graphics.Rect)">getPadding</a></span>(Rect padding)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#getParentTransform(android.graphics.Matrix)">getParentTransform</a></span>(Matrix transform)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#getRootBounds(android.graphics.RectF)">getRootBounds</a></span>(RectF bounds)
<div class="jd-descrdiv">Called when the drawable needs to get its root bounds.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#getTransform(android.graphics.Matrix)">getTransform</a></span>(Matrix transform)
<div class="jd-descrdiv">Called when the drawable needs to get all matrices applied to it.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#getTransformedBounds(android.graphics.RectF)">getTransformedBounds</a></span>(RectF outBounds)
<div class="jd-descrdiv">Gets the transformed bounds of this drawable.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#invalidateDrawable(android.graphics.drawable.Drawable)">invalidateDrawable</a></span>(Drawable who)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#isStateful()">isStateful</a></span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#mutate()">mutate</a></span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#onBoundsChange(android.graphics.Rect)">onBoundsChange</a></span>(Rect bounds)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#onLevelChange(int)">onLevelChange</a></span>(int level)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#onStateChange(int[])">onStateChange</a></span>(int[] state)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#scheduleDrawable(android.graphics.drawable.Drawable, java.lang.Runnable, long)">scheduleDrawable</a></span>(Drawable who, Runnable what, long when)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#setAlpha(int)">setAlpha</a></span>(int alpha)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#setColorFilter(android.graphics.ColorFilter)">setColorFilter</a></span>(ColorFilter colorFilter)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#setCurrent(android.graphics.drawable.Drawable)">setCurrent</a></span>(Drawable newDelegate)
<div class="jd-descrdiv">Sets a new drawable to be the delegate, and returns the old one (or null).</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#setCurrentWithoutInvalidate(android.graphics.drawable.Drawable)">setCurrentWithoutInvalidate</a></span>(Drawable newDelegate)
<div class="jd-descrdiv">As <code>setCurrent</code>, but without invalidating a drawable.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#setDither(boolean)">setDither</a></span>(boolean dither)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#setDrawable(android.graphics.drawable.Drawable)">setDrawable</a></span>(Drawable newDrawable)
<div class="jd-descrdiv">Sets the new child drawable.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#setFilterBitmap(boolean)">setFilterBitmap</a></span>(boolean filterBitmap)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#setHotspot(float, float)">setHotspot</a></span>(float x, float y)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#setTransformCallback(com.facebook.drawee.drawable.TransformCallback)">setTransformCallback</a></span>(<a href="../../../../com/facebook/drawee/drawable/TransformCallback.html">TransformCallback</a> transformCallback)
<div class="jd-descrdiv">Sets a transform callback.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#setVisible(boolean, boolean)">setVisible</a></span>(boolean visible, boolean restart)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/ForwardingDrawable.html#unscheduleDrawable(android.graphics.drawable.Drawable, java.lang.Runnable)">unscheduleDrawable</a></span>(Drawable who, Runnable what)
</td></tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-android.graphics.drawable.Drawable" class="jd-expando-trigger closed"
><img id="inherited-methods-android.graphics.drawable.Drawable-trigger"
src="../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From class
android.graphics.drawable.Drawable
<div id="inherited-methods-android.graphics.drawable.Drawable">
<div id="inherited-methods-android.graphics.drawable.Drawable-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-android.graphics.drawable.Drawable-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">applyTheme</span>(Resources.Theme arg0)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">canApplyTheme</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">clearColorFilter</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
Rect
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">copyBounds</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">copyBounds</span>(Rect arg0)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
static
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">createFromPath</span>(String arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
static
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">createFromResourceStream</span>(Resources arg0, TypedValue arg1, InputStream arg2, String arg3, BitmapFactory.Options arg4)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
static
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">createFromResourceStream</span>(Resources arg0, TypedValue arg1, InputStream arg2, String arg3)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
static
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">createFromStream</span>(InputStream arg0, String arg1)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
static
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">createFromXml</span>(Resources arg0, XmlPullParser arg1)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
static
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">createFromXml</span>(Resources arg0, XmlPullParser arg1, Resources.Theme arg2)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
static
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">createFromXmlInner</span>(Resources arg0, XmlPullParser arg1, AttributeSet arg2, Resources.Theme arg3)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
static
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">createFromXmlInner</span>(Resources arg0, XmlPullParser arg1, AttributeSet arg2)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
abstract
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">draw</span>(Canvas arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getAlpha</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
Rect
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getBounds</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
Drawable.Callback
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getCallback</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getChangingConfigurations</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
ColorFilter
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getColorFilter</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
Drawable.ConstantState
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getConstantState</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getCurrent</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
Rect
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getDirtyBounds</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getHotspotBounds</span>(Rect arg0)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getIntrinsicHeight</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getIntrinsicWidth</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getLayoutDirection</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getLevel</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getMinimumHeight</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getMinimumWidth</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
abstract
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getOpacity</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getOutline</span>(Outline arg0)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getPadding</span>(Rect arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
int[]
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getState</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
Region
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getTransparentRegion</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">inflate</span>(Resources arg0, XmlPullParser arg1, AttributeSet arg2, Resources.Theme arg3)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">inflate</span>(Resources arg0, XmlPullParser arg1, AttributeSet arg2)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">invalidateSelf</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">isAutoMirrored</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">isFilterBitmap</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">isStateful</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">isVisible</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">jumpToCurrentState</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">mutate</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">onBoundsChange</span>(Rect arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">onLayoutDirectionChanged</span>(int arg0)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">onLevelChange</span>(int arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">onStateChange</span>(int[] arg0)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
static
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">resolveOpacity</span>(int arg0, int arg1)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">scheduleSelf</span>(Runnable arg0, long arg1)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
abstract
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setAlpha</span>(int arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setAutoMirrored</span>(boolean arg0)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setBounds</span>(int arg0, int arg1, int arg2, int arg3)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setBounds</span>(Rect arg0)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setCallback</span>(Drawable.Callback arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setChangingConfigurations</span>(int arg0)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setColorFilter</span>(int arg0, PorterDuff.Mode arg1)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
abstract
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setColorFilter</span>(ColorFilter arg0)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setDither</span>(boolean arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setFilterBitmap</span>(boolean arg0)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setHotspot</span>(float arg0, float arg1)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setHotspotBounds</span>(int arg0, int arg1, int arg2, int arg3)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setLayoutDirection</span>(int arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setLevel</span>(int arg0)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setState</span>(int[] arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setTint</span>(int arg0)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setTintList</span>(ColorStateList arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setTintMode</span>(PorterDuff.Mode arg0)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">setVisible</span>(boolean arg0, boolean arg1)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">unscheduleSelf</span>(Runnable arg0)
</td></tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed"
><img id="inherited-methods-java.lang.Object-trigger"
src="../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From class
java.lang.Object
<div id="inherited-methods-java.lang.Object">
<div id="inherited-methods-java.lang.Object-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-java.lang.Object-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
Object
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">clone</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">equals</span>(Object arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">finalize</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
Class<?>
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getClass</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">hashCode</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">notify</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">notifyAll</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
String
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">toString</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">wait</span>(long arg0, int arg1)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">wait</span>(long arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">wait</span>()
</td></tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-android.graphics.drawable.Drawable.Callback" class="jd-expando-trigger closed"
><img id="inherited-methods-android.graphics.drawable.Drawable.Callback-trigger"
src="../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From interface
android.graphics.drawable.Drawable.Callback
<div id="inherited-methods-android.graphics.drawable.Drawable.Callback">
<div id="inherited-methods-android.graphics.drawable.Drawable.Callback-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-android.graphics.drawable.Drawable.Callback-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
abstract
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">invalidateDrawable</span>(Drawable arg0)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
abstract
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">scheduleDrawable</span>(Drawable arg0, Runnable arg1, long arg2)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
abstract
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">unscheduleDrawable</span>(Drawable arg0, Runnable arg1)
</td></tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-com.facebook.drawee.drawable.DrawableParent" class="jd-expando-trigger closed"
><img id="inherited-methods-com.facebook.drawee.drawable.DrawableParent-trigger"
src="../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From interface
<a href="../../../../com/facebook/drawee/drawable/DrawableParent.html">com.facebook.drawee.drawable.DrawableParent</a>
<div id="inherited-methods-com.facebook.drawee.drawable.DrawableParent">
<div id="inherited-methods-com.facebook.drawee.drawable.DrawableParent-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-com.facebook.drawee.drawable.DrawableParent-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
abstract
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/DrawableParent.html#getDrawable()">getDrawable</a></span>()
<div class="jd-descrdiv">Gets the child drawable.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
abstract
Drawable
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/DrawableParent.html#setDrawable(android.graphics.drawable.Drawable)">setDrawable</a></span>(Drawable newDrawable)
<div class="jd-descrdiv">Sets the new child drawable.</div>
</td></tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-com.facebook.drawee.drawable.TransformAwareDrawable" class="jd-expando-trigger closed"
><img id="inherited-methods-com.facebook.drawee.drawable.TransformAwareDrawable-trigger"
src="../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From interface
<a href="../../../../com/facebook/drawee/drawable/TransformAwareDrawable.html">com.facebook.drawee.drawable.TransformAwareDrawable</a>
<div id="inherited-methods-com.facebook.drawee.drawable.TransformAwareDrawable">
<div id="inherited-methods-com.facebook.drawee.drawable.TransformAwareDrawable-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-com.facebook.drawee.drawable.TransformAwareDrawable-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
abstract
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/TransformAwareDrawable.html#setTransformCallback(com.facebook.drawee.drawable.TransformCallback)">setTransformCallback</a></span>(<a href="../../../../com/facebook/drawee/drawable/TransformCallback.html">TransformCallback</a> transformCallback)
<div class="jd-descrdiv">Sets a transform callback.</div>
</td></tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-com.facebook.drawee.drawable.TransformCallback" class="jd-expando-trigger closed"
><img id="inherited-methods-com.facebook.drawee.drawable.TransformCallback-trigger"
src="../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From interface
<a href="../../../../com/facebook/drawee/drawable/TransformCallback.html">com.facebook.drawee.drawable.TransformCallback</a>
<div id="inherited-methods-com.facebook.drawee.drawable.TransformCallback">
<div id="inherited-methods-com.facebook.drawee.drawable.TransformCallback-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-com.facebook.drawee.drawable.TransformCallback-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
abstract
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/TransformCallback.html#getRootBounds(android.graphics.RectF)">getRootBounds</a></span>(RectF bounds)
<div class="jd-descrdiv">Called when the drawable needs to get its root bounds.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
abstract
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/drawee/drawable/TransformCallback.html#getTransform(android.graphics.Matrix)">getTransform</a></span>(Matrix transform)
<div class="jd-descrdiv">Called when the drawable needs to get all matrices applied to it.</div>
</td></tr>
</table>
</div>
</div>
</td></tr>
</table>
</div><!-- jd-descr (summary) -->
<!-- Details -->
<!-- XML Attributes -->
<!-- Enum Values -->
<!-- Constants -->
<!-- Fields -->
<!-- Public ctors -->
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<h2>Public Constructors</h2>
<a id="OrientedDrawable(android.graphics.drawable.Drawable, int)"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
</span>
<span class="sympad">OrientedDrawable</span>
<span class="normal">(Drawable drawable, int rotationAngle)</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Creates a new OrientedDrawable. The only rotation angles allowed are multiples of 90 or -1 if
the angle is unknown.
</p></div>
</div>
</div>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<!-- Protected ctors -->
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methdos -->
<h2>Public Methods</h2>
<a id="draw(android.graphics.Canvas)"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
void
</span>
<span class="sympad">draw</span>
<span class="normal">(Canvas canvas)</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<a id="getIntrinsicHeight()"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">getIntrinsicHeight</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<a id="getIntrinsicWidth()"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">getIntrinsicWidth</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<a id="getTransform(android.graphics.Matrix)"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
void
</span>
<span class="sympad">getTransform</span>
<span class="normal">(Matrix transform)</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Called when the drawable needs to get all matrices applied to it.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>transform</th>
<td>Matrix that is applied to the drawable by the parent drawables.
</td>
</tr>
</table>
</div>
</div>
</div>
<!-- ========= METHOD DETAIL ======== -->
<h2>Protected Methods</h2>
<a id="onBoundsChange(android.graphics.Rect)"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
protected
void
</span>
<span class="sympad">onBoundsChange</span>
<span class="normal">(Rect bounds)</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<a id="navbar_top"></a>
<div id="footer">
+Generated by <a href="http://code.google.com/p/doclava/">Doclava</a>.
+</div> <!-- end footer - @generated -->
</div> <!-- jd-content -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
<script type="text/javascript">
init(); /* initialize doclava-developer-docs.js */
</script>
</body>
</html>
|
weiwenqiang/GitHub
|
expert/fresco/docs/javadoc/reference/com/facebook/drawee/drawable/OrientedDrawable.html
|
HTML
|
apache-2.0
| 79,322
|
// DO NOT EDIT. Make changes to com.kaviju.accesscontrol.model.KAUserProfileRole.java instead.
package com.kaviju.accesscontrol.model.base;
import com.webobjects.eoaccess.*;
import com.webobjects.eocontrol.*;
import com.webobjects.foundation.*;
import java.math.*;
import java.util.*;
import org.apache.log4j.Logger;
import er.extensions.eof.*;
import er.extensions.foundation.*;
@SuppressWarnings("all")
public abstract class _KAUserProfileRole extends ERXGenericRecord {
public static final String ENTITY_NAME = "KAUserProfileRole";
// Attribute Keys
// Relationship Keys
public static final ERXKey<com.kaviju.accesscontrol.model.KAAccessListItem> LIST_ITEMS = new ERXKey<com.kaviju.accesscontrol.model.KAAccessListItem>("listItems");
public static final ERXKey<com.kaviju.accesscontrol.model.KARole> ROLE = new ERXKey<com.kaviju.accesscontrol.model.KARole>("role");
public static final ERXKey<com.kaviju.accesscontrol.model.KAUserProfile> USER_PROFILE = new ERXKey<com.kaviju.accesscontrol.model.KAUserProfile>("userProfile");
// Attributes
// Relationships
public static final String LIST_ITEMS_KEY = "listItems";
public static final String ROLE_KEY = "role";
public static final String USER_PROFILE_KEY = "userProfile";
private static Logger LOG = Logger.getLogger(_KAUserProfileRole.class);
public com.kaviju.accesscontrol.model.KAUserProfileRole localInstanceIn(EOEditingContext editingContext) {
com.kaviju.accesscontrol.model.KAUserProfileRole localInstance = (com.kaviju.accesscontrol.model.KAUserProfileRole)EOUtilities.localInstanceOfObject(editingContext, this);
if (localInstance == null) {
throw new IllegalStateException("You attempted to localInstance " + this + ", which has not yet committed.");
}
return localInstance;
}
public com.kaviju.accesscontrol.model.KARole role() {
return (com.kaviju.accesscontrol.model.KARole)storedValueForKey(_KAUserProfileRole.ROLE_KEY);
}
public void setRole(com.kaviju.accesscontrol.model.KARole value) {
takeStoredValueForKey(value, _KAUserProfileRole.ROLE_KEY);
}
public void setRoleRelationship(com.kaviju.accesscontrol.model.KARole value) {
if (_KAUserProfileRole.LOG.isDebugEnabled()) {
_KAUserProfileRole.LOG.debug("updating role from " + role() + " to " + value);
}
if (er.extensions.eof.ERXGenericRecord.InverseRelationshipUpdater.updateInverseRelationships()) {
setRole(value);
}
else if (value == null) {
com.kaviju.accesscontrol.model.KARole oldValue = role();
if (oldValue != null) {
removeObjectFromBothSidesOfRelationshipWithKey(oldValue, _KAUserProfileRole.ROLE_KEY);
}
} else {
addObjectToBothSidesOfRelationshipWithKey(value, _KAUserProfileRole.ROLE_KEY);
}
}
public com.kaviju.accesscontrol.model.KAUserProfile userProfile() {
return (com.kaviju.accesscontrol.model.KAUserProfile)storedValueForKey(_KAUserProfileRole.USER_PROFILE_KEY);
}
public void setUserProfile(com.kaviju.accesscontrol.model.KAUserProfile value) {
takeStoredValueForKey(value, _KAUserProfileRole.USER_PROFILE_KEY);
}
public void setUserProfileRelationship(com.kaviju.accesscontrol.model.KAUserProfile value) {
if (_KAUserProfileRole.LOG.isDebugEnabled()) {
_KAUserProfileRole.LOG.debug("updating userProfile from " + userProfile() + " to " + value);
}
if (er.extensions.eof.ERXGenericRecord.InverseRelationshipUpdater.updateInverseRelationships()) {
setUserProfile(value);
}
else if (value == null) {
com.kaviju.accesscontrol.model.KAUserProfile oldValue = userProfile();
if (oldValue != null) {
removeObjectFromBothSidesOfRelationshipWithKey(oldValue, _KAUserProfileRole.USER_PROFILE_KEY);
}
} else {
addObjectToBothSidesOfRelationshipWithKey(value, _KAUserProfileRole.USER_PROFILE_KEY);
}
}
public NSArray<com.kaviju.accesscontrol.model.KAAccessListItem> listItems() {
return (NSArray<com.kaviju.accesscontrol.model.KAAccessListItem>)storedValueForKey(_KAUserProfileRole.LIST_ITEMS_KEY);
}
public NSArray<com.kaviju.accesscontrol.model.KAAccessListItem> listItems(EOQualifier qualifier) {
return listItems(qualifier, null);
}
public NSArray<com.kaviju.accesscontrol.model.KAAccessListItem> listItems(EOQualifier qualifier, NSArray<EOSortOrdering> sortOrderings) {
NSArray<com.kaviju.accesscontrol.model.KAAccessListItem> results;
results = listItems();
if (qualifier != null) {
results = (NSArray<com.kaviju.accesscontrol.model.KAAccessListItem>)EOQualifier.filteredArrayWithQualifier(results, qualifier);
}
if (sortOrderings != null) {
results = (NSArray<com.kaviju.accesscontrol.model.KAAccessListItem>)EOSortOrdering.sortedArrayUsingKeyOrderArray(results, sortOrderings);
}
return results;
}
public void addToListItems(com.kaviju.accesscontrol.model.KAAccessListItem object) {
includeObjectIntoPropertyWithKey(object, _KAUserProfileRole.LIST_ITEMS_KEY);
}
public void removeFromListItems(com.kaviju.accesscontrol.model.KAAccessListItem object) {
excludeObjectFromPropertyWithKey(object, _KAUserProfileRole.LIST_ITEMS_KEY);
}
public void addToListItemsRelationship(com.kaviju.accesscontrol.model.KAAccessListItem object) {
if (_KAUserProfileRole.LOG.isDebugEnabled()) {
_KAUserProfileRole.LOG.debug("adding " + object + " to listItems relationship");
}
if (er.extensions.eof.ERXGenericRecord.InverseRelationshipUpdater.updateInverseRelationships()) {
addToListItems(object);
}
else {
addObjectToBothSidesOfRelationshipWithKey(object, _KAUserProfileRole.LIST_ITEMS_KEY);
}
}
public void removeFromListItemsRelationship(com.kaviju.accesscontrol.model.KAAccessListItem object) {
if (_KAUserProfileRole.LOG.isDebugEnabled()) {
_KAUserProfileRole.LOG.debug("removing " + object + " from listItems relationship");
}
if (er.extensions.eof.ERXGenericRecord.InverseRelationshipUpdater.updateInverseRelationships()) {
removeFromListItems(object);
}
else {
removeObjectFromBothSidesOfRelationshipWithKey(object, _KAUserProfileRole.LIST_ITEMS_KEY);
}
}
public com.kaviju.accesscontrol.model.KAAccessListItem createListItemsRelationship() {
EOClassDescription eoClassDesc = EOClassDescription.classDescriptionForEntityName( com.kaviju.accesscontrol.model.KAAccessListItem.ENTITY_NAME );
EOEnterpriseObject eo = eoClassDesc.createInstanceWithEditingContext(editingContext(), null);
editingContext().insertObject(eo);
addObjectToBothSidesOfRelationshipWithKey(eo, _KAUserProfileRole.LIST_ITEMS_KEY);
return (com.kaviju.accesscontrol.model.KAAccessListItem) eo;
}
public void deleteListItemsRelationship(com.kaviju.accesscontrol.model.KAAccessListItem object) {
removeObjectFromBothSidesOfRelationshipWithKey(object, _KAUserProfileRole.LIST_ITEMS_KEY);
editingContext().deleteObject(object);
}
public void deleteAllListItemsRelationships() {
Enumeration<com.kaviju.accesscontrol.model.KAAccessListItem> objects = listItems().immutableClone().objectEnumerator();
while (objects.hasMoreElements()) {
deleteListItemsRelationship(objects.nextElement());
}
}
public static com.kaviju.accesscontrol.model.KAUserProfileRole createKAUserProfileRole(EOEditingContext editingContext) {
com.kaviju.accesscontrol.model.KAUserProfileRole eo = (com.kaviju.accesscontrol.model.KAUserProfileRole) EOUtilities.createAndInsertInstance(editingContext, _KAUserProfileRole.ENTITY_NAME); return eo;
}
public static ERXFetchSpecification<com.kaviju.accesscontrol.model.KAUserProfileRole> fetchSpec() {
return new ERXFetchSpecification<com.kaviju.accesscontrol.model.KAUserProfileRole>(_KAUserProfileRole.ENTITY_NAME, null, null, false, true, null);
}
public static NSArray<com.kaviju.accesscontrol.model.KAUserProfileRole> fetchAllKAUserProfileRoles(EOEditingContext editingContext) {
return _KAUserProfileRole.fetchAllKAUserProfileRoles(editingContext, null);
}
public static NSArray<com.kaviju.accesscontrol.model.KAUserProfileRole> fetchAllKAUserProfileRoles(EOEditingContext editingContext, NSArray<EOSortOrdering> sortOrderings) {
return _KAUserProfileRole.fetchKAUserProfileRoles(editingContext, null, sortOrderings);
}
public static NSArray<com.kaviju.accesscontrol.model.KAUserProfileRole> fetchKAUserProfileRoles(EOEditingContext editingContext, EOQualifier qualifier, NSArray<EOSortOrdering> sortOrderings) {
ERXFetchSpecification<com.kaviju.accesscontrol.model.KAUserProfileRole> fetchSpec = new ERXFetchSpecification<com.kaviju.accesscontrol.model.KAUserProfileRole>(_KAUserProfileRole.ENTITY_NAME, qualifier, sortOrderings);
fetchSpec.setIsDeep(true);
NSArray<com.kaviju.accesscontrol.model.KAUserProfileRole> eoObjects = fetchSpec.fetchObjects(editingContext);
return eoObjects;
}
public static com.kaviju.accesscontrol.model.KAUserProfileRole fetchKAUserProfileRole(EOEditingContext editingContext, String keyName, Object value) {
return _KAUserProfileRole.fetchKAUserProfileRole(editingContext, new EOKeyValueQualifier(keyName, EOQualifier.QualifierOperatorEqual, value));
}
public static com.kaviju.accesscontrol.model.KAUserProfileRole fetchKAUserProfileRole(EOEditingContext editingContext, EOQualifier qualifier) {
NSArray<com.kaviju.accesscontrol.model.KAUserProfileRole> eoObjects = _KAUserProfileRole.fetchKAUserProfileRoles(editingContext, qualifier, null);
com.kaviju.accesscontrol.model.KAUserProfileRole eoObject;
int count = eoObjects.count();
if (count == 0) {
eoObject = null;
}
else if (count == 1) {
eoObject = eoObjects.objectAtIndex(0);
}
else {
throw new IllegalStateException("There was more than one KAUserProfileRole that matched the qualifier '" + qualifier + "'.");
}
return eoObject;
}
public static com.kaviju.accesscontrol.model.KAUserProfileRole fetchRequiredKAUserProfileRole(EOEditingContext editingContext, String keyName, Object value) {
return _KAUserProfileRole.fetchRequiredKAUserProfileRole(editingContext, new EOKeyValueQualifier(keyName, EOQualifier.QualifierOperatorEqual, value));
}
public static com.kaviju.accesscontrol.model.KAUserProfileRole fetchRequiredKAUserProfileRole(EOEditingContext editingContext, EOQualifier qualifier) {
com.kaviju.accesscontrol.model.KAUserProfileRole eoObject = _KAUserProfileRole.fetchKAUserProfileRole(editingContext, qualifier);
if (eoObject == null) {
throw new NoSuchElementException("There was no KAUserProfileRole that matched the qualifier '" + qualifier + "'.");
}
return eoObject;
}
public static com.kaviju.accesscontrol.model.KAUserProfileRole localInstanceIn(EOEditingContext editingContext, com.kaviju.accesscontrol.model.KAUserProfileRole eo) {
com.kaviju.accesscontrol.model.KAUserProfileRole localInstance = (eo == null) ? null : ERXEOControlUtilities.localInstanceOfObject(editingContext, eo);
if (localInstance == null && eo != null) {
throw new IllegalStateException("You attempted to localInstance " + eo + ", which has not yet committed.");
}
return localInstance;
}
}
|
Kaviju/KAAccessControl
|
Sources/com/kaviju/accesscontrol/model/base/_KAUserProfileRole.java
|
Java
|
apache-2.0
| 11,274
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="pt">
<head>
<!-- Generated by javadoc (version 1.7.0_79) on Mon Jun 22 15:50:33 BRT 2015 -->
<title>PacketStreamer.pushMessageSync_args</title>
<meta name="date" content="2015-06-22">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="PacketStreamer.pushMessageSync_args";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/PacketStreamer.pushMessageSync_args.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageAsync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" target="_top">Frames</a></li>
<li><a href="PacketStreamer.pushMessageSync_args.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested_class_summary">Nested</a> | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">net.floodlightcontroller.packetstreamer.thrift</div>
<h2 title="Class PacketStreamer.pushMessageSync_args" class="title">Class PacketStreamer.pushMessageSync_args</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>net.floodlightcontroller.packetstreamer.thrift.PacketStreamer.pushMessageSync_args</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable, java.lang.Cloneable, java.lang.Comparable<<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a>>, org.apache.thrift.TBase<<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a>,<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a>></dd>
</dl>
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer</a></dd>
</dl>
<hr>
<br>
<pre>public static class <span class="strong">PacketStreamer.pushMessageSync_args</span>
extends java.lang.Object
implements org.apache.thrift.TBase<<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a>,<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a>>, java.io.Serializable, java.lang.Cloneable</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../serialized-form.html#net.floodlightcontroller.packetstreamer.thrift.PacketStreamer.pushMessageSync_args">Serialized Form</a></dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested_class_summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation">
<caption><span>Nested Classes</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a></strong></code>
<div class="block">The set of fields this struct contains, along with convenience methods for finding and manipulating them.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.util.Map<<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a>,org.apache.thrift.meta_data.FieldMetaData></code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#metaDataMap">metaDataMap</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/Message.html" title="class in net.floodlightcontroller.packetstreamer.thrift">Message</a></code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#packet">packet</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#PacketStreamer.pushMessageSync_args()">PacketStreamer.pushMessageSync_args</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#PacketStreamer.pushMessageSync_args(net.floodlightcontroller.packetstreamer.thrift.Message)">PacketStreamer.pushMessageSync_args</a></strong>(<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/Message.html" title="class in net.floodlightcontroller.packetstreamer.thrift">Message</a> packet)</code> </td>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#PacketStreamer.pushMessageSync_args(net.floodlightcontroller.packetstreamer.thrift.PacketStreamer.pushMessageSync_args)">PacketStreamer.pushMessageSync_args</a></strong>(<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a> other)</code>
<div class="block">Performs a deep copy on <i>other</i>.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#clear()">clear</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#compareTo(net.floodlightcontroller.packetstreamer.thrift.PacketStreamer.pushMessageSync_args)">compareTo</a></strong>(<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a> other)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a></code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#deepCopy()">deepCopy</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#equals(java.lang.Object)">equals</a></strong>(java.lang.Object that)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#equals(net.floodlightcontroller.packetstreamer.thrift.PacketStreamer.pushMessageSync_args)">equals</a></strong>(<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a> that)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a></code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#fieldForId(int)">fieldForId</a></strong>(int fieldId)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.Object</code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#getFieldValue(net.floodlightcontroller.packetstreamer.thrift.PacketStreamer.pushMessageSync_args._Fields)">getFieldValue</a></strong>(<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a> field)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/Message.html" title="class in net.floodlightcontroller.packetstreamer.thrift">Message</a></code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#getPacket()">getPacket</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#hashCode()">hashCode</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#isSet(net.floodlightcontroller.packetstreamer.thrift.PacketStreamer.pushMessageSync_args._Fields)">isSet</a></strong>(<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a> field)</code>
<div class="block">Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#isSetPacket()">isSetPacket</a></strong>()</code>
<div class="block">Returns true if field packet is set (has been assigned a value) and false otherwise</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#read(org.apache.thrift.protocol.TProtocol)">read</a></strong>(org.apache.thrift.protocol.TProtocol iprot)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#setFieldValue(net.floodlightcontroller.packetstreamer.thrift.PacketStreamer.pushMessageSync_args._Fields,%20java.lang.Object)">setFieldValue</a></strong>(<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a> field,
java.lang.Object value)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a></code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#setPacket(net.floodlightcontroller.packetstreamer.thrift.Message)">setPacket</a></strong>(<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/Message.html" title="class in net.floodlightcontroller.packetstreamer.thrift">Message</a> packet)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#setPacketIsSet(boolean)">setPacketIsSet</a></strong>(boolean value)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#toString()">toString</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#unsetPacket()">unsetPacket</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#validate()">validate</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html#write(org.apache.thrift.protocol.TProtocol)">write</a></strong>(org.apache.thrift.protocol.TProtocol oprot)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>getClass, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="packet">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>packet</h4>
<pre>public <a href="../../../../net/floodlightcontroller/packetstreamer/thrift/Message.html" title="class in net.floodlightcontroller.packetstreamer.thrift">Message</a> packet</pre>
</li>
</ul>
<a name="metaDataMap">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>metaDataMap</h4>
<pre>public static final java.util.Map<<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a>,org.apache.thrift.meta_data.FieldMetaData> metaDataMap</pre>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="PacketStreamer.pushMessageSync_args()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>PacketStreamer.pushMessageSync_args</h4>
<pre>public PacketStreamer.pushMessageSync_args()</pre>
</li>
</ul>
<a name="PacketStreamer.pushMessageSync_args(net.floodlightcontroller.packetstreamer.thrift.Message)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>PacketStreamer.pushMessageSync_args</h4>
<pre>public PacketStreamer.pushMessageSync_args(<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/Message.html" title="class in net.floodlightcontroller.packetstreamer.thrift">Message</a> packet)</pre>
</li>
</ul>
<a name="PacketStreamer.pushMessageSync_args(net.floodlightcontroller.packetstreamer.thrift.PacketStreamer.pushMessageSync_args)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>PacketStreamer.pushMessageSync_args</h4>
<pre>public PacketStreamer.pushMessageSync_args(<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a> other)</pre>
<div class="block">Performs a deep copy on <i>other</i>.</div>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="deepCopy()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>deepCopy</h4>
<pre>public <a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a> deepCopy()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>deepCopy</code> in interface <code>org.apache.thrift.TBase<<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a>,<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a>></code></dd>
</dl>
</li>
</ul>
<a name="clear()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>clear</h4>
<pre>public void clear()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>clear</code> in interface <code>org.apache.thrift.TBase<<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a>,<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a>></code></dd>
</dl>
</li>
</ul>
<a name="getPacket()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getPacket</h4>
<pre>public <a href="../../../../net/floodlightcontroller/packetstreamer/thrift/Message.html" title="class in net.floodlightcontroller.packetstreamer.thrift">Message</a> getPacket()</pre>
</li>
</ul>
<a name="setPacket(net.floodlightcontroller.packetstreamer.thrift.Message)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setPacket</h4>
<pre>public <a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a> setPacket(<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/Message.html" title="class in net.floodlightcontroller.packetstreamer.thrift">Message</a> packet)</pre>
</li>
</ul>
<a name="unsetPacket()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>unsetPacket</h4>
<pre>public void unsetPacket()</pre>
</li>
</ul>
<a name="isSetPacket()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isSetPacket</h4>
<pre>public boolean isSetPacket()</pre>
<div class="block">Returns true if field packet is set (has been assigned a value) and false otherwise</div>
</li>
</ul>
<a name="setPacketIsSet(boolean)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setPacketIsSet</h4>
<pre>public void setPacketIsSet(boolean value)</pre>
</li>
</ul>
<a name="setFieldValue(net.floodlightcontroller.packetstreamer.thrift.PacketStreamer.pushMessageSync_args._Fields, java.lang.Object)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setFieldValue</h4>
<pre>public void setFieldValue(<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a> field,
java.lang.Object value)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>setFieldValue</code> in interface <code>org.apache.thrift.TBase<<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a>,<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a>></code></dd>
</dl>
</li>
</ul>
<a name="getFieldValue(net.floodlightcontroller.packetstreamer.thrift.PacketStreamer.pushMessageSync_args._Fields)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getFieldValue</h4>
<pre>public java.lang.Object getFieldValue(<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a> field)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>getFieldValue</code> in interface <code>org.apache.thrift.TBase<<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a>,<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a>></code></dd>
</dl>
</li>
</ul>
<a name="isSet(net.floodlightcontroller.packetstreamer.thrift.PacketStreamer.pushMessageSync_args._Fields)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isSet</h4>
<pre>public boolean isSet(<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a> field)</pre>
<div class="block">Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise</div>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>isSet</code> in interface <code>org.apache.thrift.TBase<<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a>,<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a>></code></dd>
</dl>
</li>
</ul>
<a name="equals(java.lang.Object)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>equals</h4>
<pre>public boolean equals(java.lang.Object that)</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>equals</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
<a name="equals(net.floodlightcontroller.packetstreamer.thrift.PacketStreamer.pushMessageSync_args)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>equals</h4>
<pre>public boolean equals(<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a> that)</pre>
</li>
</ul>
<a name="hashCode()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>hashCode</h4>
<pre>public int hashCode()</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>hashCode</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
<a name="compareTo(net.floodlightcontroller.packetstreamer.thrift.PacketStreamer.pushMessageSync_args)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>compareTo</h4>
<pre>public int compareTo(<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a> other)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>compareTo</code> in interface <code>java.lang.Comparable<<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a>></code></dd>
</dl>
</li>
</ul>
<a name="fieldForId(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>fieldForId</h4>
<pre>public <a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a> fieldForId(int fieldId)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>fieldForId</code> in interface <code>org.apache.thrift.TBase<<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a>,<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a>></code></dd>
</dl>
</li>
</ul>
<a name="read(org.apache.thrift.protocol.TProtocol)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>read</h4>
<pre>public void read(org.apache.thrift.protocol.TProtocol iprot)
throws org.apache.thrift.TException</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>read</code> in interface <code>org.apache.thrift.TBase<<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a>,<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a>></code></dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>org.apache.thrift.TException</code></dd></dl>
</li>
</ul>
<a name="write(org.apache.thrift.protocol.TProtocol)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>write</h4>
<pre>public void write(org.apache.thrift.protocol.TProtocol oprot)
throws org.apache.thrift.TException</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>write</code> in interface <code>org.apache.thrift.TBase<<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" title="class in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args</a>,<a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift">PacketStreamer.pushMessageSync_args._Fields</a>></code></dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>org.apache.thrift.TException</code></dd></dl>
</li>
</ul>
<a name="toString()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>toString</h4>
<pre>public java.lang.String toString()</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>toString</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
<a name="validate()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>validate</h4>
<pre>public void validate()
throws org.apache.thrift.TException</pre>
<dl><dt><span class="strong">Throws:</span></dt>
<dd><code>org.apache.thrift.TException</code></dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/PacketStreamer.pushMessageSync_args.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageAsync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args._Fields.html" title="enum in net.floodlightcontroller.packetstreamer.thrift"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html" target="_top">Frames</a></li>
<li><a href="PacketStreamer.pushMessageSync_args.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested_class_summary">Nested</a> | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
paulorvj/sdnvoip
|
doc/net/floodlightcontroller/packetstreamer/thrift/PacketStreamer.pushMessageSync_args.html
|
HTML
|
apache-2.0
| 36,722
|
namespace ToolSolution.Tools
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.tsmi = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiFolder = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiFile = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiFileList = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiMusic = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiImage = new System.Windows.Forms.ToolStripMenuItem();
this.应用程序类ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiQQ = new System.Windows.Forms.ToolStripMenuItem();
this.多媒体类ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiVideo = new System.Windows.Forms.ToolStripMenuItem();
this.网络类ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiGrabber = new System.Windows.Forms.ToolStripMenuItem();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.财务类ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiBill = new System.Windows.Forms.ToolStripMenuItem();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsmi,
this.应用程序类ToolStripMenuItem,
this.多媒体类ToolStripMenuItem,
this.网络类ToolStripMenuItem,
this.财务类ToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(784, 25);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.Text = "menuStrip1";
//
// tsmi
//
this.tsmi.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsmiFolder,
this.tsmiFile,
this.tsmiFileList,
this.tsmiMusic,
this.tsmiImage});
this.tsmi.Name = "tsmi";
this.tsmi.Size = new System.Drawing.Size(56, 21);
this.tsmi.Text = "文件类";
//
// tsmiFolder
//
this.tsmiFolder.Name = "tsmiFolder";
this.tsmiFolder.Size = new System.Drawing.Size(124, 22);
this.tsmiFolder.Text = "文件夹";
this.tsmiFolder.Click += new System.EventHandler(this.tsmiFolder_Click);
//
// tsmiFile
//
this.tsmiFile.Name = "tsmiFile";
this.tsmiFile.Size = new System.Drawing.Size(124, 22);
this.tsmiFile.Text = "文件通用";
this.tsmiFile.Click += new System.EventHandler(this.tsmiFile_Click);
//
// tsmiFileList
//
this.tsmiFileList.Name = "tsmiFileList";
this.tsmiFileList.Size = new System.Drawing.Size(124, 22);
this.tsmiFileList.Text = "文件列表";
this.tsmiFileList.Click += new System.EventHandler(this.tsmiFileList_Click);
//
// tsmiMusic
//
this.tsmiMusic.Name = "tsmiMusic";
this.tsmiMusic.Size = new System.Drawing.Size(124, 22);
this.tsmiMusic.Text = "音乐";
this.tsmiMusic.Click += new System.EventHandler(this.tsmiMusic_Click);
//
// tsmiImage
//
this.tsmiImage.Name = "tsmiImage";
this.tsmiImage.Size = new System.Drawing.Size(124, 22);
this.tsmiImage.Text = "图片";
this.tsmiImage.Click += new System.EventHandler(this.tsmiImage_Click);
//
// 应用程序类ToolStripMenuItem
//
this.应用程序类ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsmiQQ});
this.应用程序类ToolStripMenuItem.Name = "应用程序类ToolStripMenuItem";
this.应用程序类ToolStripMenuItem.Size = new System.Drawing.Size(80, 21);
this.应用程序类ToolStripMenuItem.Text = "应用程序类";
//
// tsmiQQ
//
this.tsmiQQ.Name = "tsmiQQ";
this.tsmiQQ.Size = new System.Drawing.Size(96, 22);
this.tsmiQQ.Text = "QQ";
this.tsmiQQ.Click += new System.EventHandler(this.tsmiQQ_Click);
//
// 多媒体类ToolStripMenuItem
//
this.多媒体类ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsmiVideo});
this.多媒体类ToolStripMenuItem.Name = "多媒体类ToolStripMenuItem";
this.多媒体类ToolStripMenuItem.Size = new System.Drawing.Size(68, 21);
this.多媒体类ToolStripMenuItem.Text = "多媒体类";
//
// tsmiVideo
//
this.tsmiVideo.Name = "tsmiVideo";
this.tsmiVideo.Size = new System.Drawing.Size(100, 22);
this.tsmiVideo.Text = "视频";
this.tsmiVideo.Click += new System.EventHandler(this.tsmiVideo_Click);
//
// 网络类ToolStripMenuItem
//
this.网络类ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsmiGrabber});
this.网络类ToolStripMenuItem.Name = "网络类ToolStripMenuItem";
this.网络类ToolStripMenuItem.Size = new System.Drawing.Size(56, 21);
this.网络类ToolStripMenuItem.Text = "网络类";
//
// tsmiGrabber
//
this.tsmiGrabber.Name = "tsmiGrabber";
this.tsmiGrabber.Size = new System.Drawing.Size(152, 22);
this.tsmiGrabber.Text = "网页抓取";
this.tsmiGrabber.Click += new System.EventHandler(this.tsmiGrabber_Click);
//
// statusStrip1
//
this.statusStrip1.Location = new System.Drawing.Point(0, 540);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(784, 22);
this.statusStrip1.TabIndex = 3;
this.statusStrip1.Text = "statusStrip1";
//
// 财务类ToolStripMenuItem
//
this.财务类ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsmiBill});
this.财务类ToolStripMenuItem.Name = "财务类ToolStripMenuItem";
this.财务类ToolStripMenuItem.Size = new System.Drawing.Size(56, 21);
this.财务类ToolStripMenuItem.Text = "财务类";
//
// tsmiBill
//
this.tsmiBill.Name = "tsmiBill";
this.tsmiBill.Size = new System.Drawing.Size(152, 22);
this.tsmiBill.Text = "个人账单";
this.tsmiBill.Click += new System.EventHandler(this.tsmiBill_Click);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(784, 562);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.menuStrip1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.IsMdiContainer = true;
this.MainMenuStrip = this.menuStrip1;
this.MaximizeBox = false;
this.Name = "MainForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Tools";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem tsmi;
private System.Windows.Forms.ToolStripMenuItem tsmiFileList;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripMenuItem tsmiMusic;
private System.Windows.Forms.ToolStripMenuItem 应用程序类ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tsmiQQ;
private System.Windows.Forms.ToolStripMenuItem 多媒体类ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tsmiVideo;
private System.Windows.Forms.ToolStripMenuItem tsmiImage;
private System.Windows.Forms.ToolStripMenuItem tsmiFile;
private System.Windows.Forms.ToolStripMenuItem tsmiFolder;
private System.Windows.Forms.ToolStripMenuItem 网络类ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tsmiGrabber;
private System.Windows.Forms.ToolStripMenuItem 财务类ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tsmiBill;
}
}
|
zhaowh0518/toolkit
|
ToolSolution/Tools/MainForm.Designer.cs
|
C#
|
apache-2.0
| 10,445
|
kitchen-in-travis-native Cookbook [](https://travis-ci.org/zuazo/kitchen-in-travis-native)
=================================
Proof of concept cookbook to run [test-kitchen](http://kitchen.ci/) inside [Travis CI](https://travis-ci.org/) using the [native Docker service](http://blog.travis-ci.com/2015-08-19-using-docker-on-travis-ci/) and [kitchen-docker](https://github.com/portertech/kitchen-docker).
You can use this in your cookbook by using a *.travis.yml* file similar to the following:
```yaml
rvm: 2.2
sudo: required
services: docker
env:
matrix:
- INSTANCE=default-ubuntu-1404
- INSTANCE=default-centos-66
before_install: curl -L https://www.getchef.com/chef/install.sh | sudo bash -s -- -P chefdk -v 0.18.30
install: chef exec bundle install
# https://github.com/zuazo/kitchen-in-travis-native/issues/1#issuecomment-142455888
before_script: sudo iptables -L DOCKER || sudo iptables -N DOCKER
script:
# Run test-kitchen with docker driver, for example:
- KITCHEN_LOCAL_YAML=.kitchen.docker.yml chef exec bundle exec kitchen verify ${INSTANCE}
```
Look [below](https://github.com/zuazo/kitchen-in-travis-native#how-to-implement-this-in-my-cookbook) for more complete examples.
The following files will help you understand how this works:
* [*.travis.yml*](https://github.com/zuazo/kitchen-in-travis-native/blob/master/.travis.yml)
* [*.kitchen.docker.yml*](https://github.com/zuazo/kitchen-in-travis-native/blob/master/.kitchen.docker.yml)
* [*Rakefile*](https://github.com/zuazo/kitchen-in-travis-native/blob/master/Rakefile)
This example cookbook only installs nginx. It also includes some [Serverspec](http://serverspec.org/) tests to check everything is working correctly.
## Related Projects
* [kitchen-in-travis](https://github.com/zuazo/kitchen-in-travis): Runs test-kitchen inside [Travis CI](https://travis-ci.org/) using [User Mode Linux](https://github.com/jpetazzo/sekexe), without using the new native Docker service. The build times are longer but more customizable. Recommended if you want to run tests against many instances. For example, to test multiple instances for each build.
* [kitchen-in-circleci](https://github.com/zuazo/kitchen-in-circleci): Runs test-kitchen inside [CircleCI](https://circleci.com/).
## Install the Requirements
First you need to install [Docker](https://docs.docker.com/installation/).
Then you can use [bundler](http://bundler.io/) to install the required ruby gems:
$ gem install bundle
$ bundle install
## Running the Tests in Your Workstation
$ bundle exec rake
This example will run kitchen **with Vagrant** in your workstation. You can use `$ bundle exec rake integration:docker[default-ubuntu-1404]` to run kitchen with Docker, as in Travis CI.
## Available Rake Tasks
$ bundle exec rake -T
rake integration:docker[instance] # Run integration tests with kitchen-docker
rake integration:vagrant # Run integration tests with kitchen-vagrant
## How to Implement This in My Cookbook
First, create a `.kitchen.docker.yml` file with the platforms you want to test:
```yaml
---
driver:
name: docker
privileged: true
platforms:
- name: centos-6.6
- name: ubuntu-14.04
run_list: recipe[apt]
# [...]
```
If not defined, it will get the platforms from the main `.kitchen.yml` by default.
You can get the list of the platforms officially supported by Docker [here](https://hub.docker.com/explore/).
Then, I recommend you to create a task in your *Rakefile*:
```ruby
# Rakefile
require 'bundler/setup'
# [...]
desc 'Run Test Kitchen integration tests'
namespace :integration do
desc 'Run integration tests with kitchen-docker'
task :docker, [:instance] do |_t, args|
args.with_defaults(instance: 'default-ubuntu-1404')
require 'kitchen'
Kitchen.logger = Kitchen.default_file_logger
loader = Kitchen::Loader::YAML.new(local_config: '.kitchen.docker.yml')
instances = Kitchen::Config.new(loader: loader).instances
# Travis CI Docker service does not support destroy:
instances.get(args.instance).verify
end
end
```
This will allow us to use `$ bundle exec rake integration:docker[INSTANCE]` to run tests against an instance. If you want more elaborate rake tasks, [see the `kitchen-in-travis` example](https://github.com/zuazo/kitchen-in-travis#how-to-run-tests-in-many-platforms).
The *.travis.yml* file example:
```yaml
rvm: 2.2
sudo: required
services: docker
env:
matrix:
- INSTANCE=default-ubuntu-1404
- INSTANCE=default-centos-66
before_install: curl -L https://www.getchef.com/chef/install.sh | sudo bash -s -- -P chefdk -v 0.18.30
install: chef exec bundle install --jobs=3 --retry=3
# https://github.com/zuazo/kitchen-in-travis-native/issues/1#issuecomment-142455888
before_script: sudo iptables -L DOCKER || sudo iptables -N DOCKER
script: travis_retry chef exec bundle exec rake integration:docker[${INSTANCE}]
```
If you are using a *Gemfile*, you should add the following to it:
```ruby
# Gemfile
gem 'berkshelf', '~> 5.1' # Comes with ChefDK 0.18.30
group :integration do
gem 'test-kitchen', '~> 1.13'
end
group :docker do
gem 'kitchen-docker', '~> 2.6'
end
```
## Real-world Examples
* [supermarket-omnibus](https://github.com/chef-cookbooks/supermarket-omnibus-cookbook) cookbook ([*.travis.yml*](https://github.com/chef-cookbooks/supermarket-omnibus-cookbook/blob/master/.travis.yml), [*.kitchen.docker.yml*](https://github.com/chef-cookbooks/supermarket-omnibus-cookbook/blob/master/.kitchen.docker.yml).
* [owncloud](https://github.com/zuazo/owncloud-cookbook) cookbook ([*.travis.yml*](https://github.com/zuazo/owncloud-cookbook/blob/master/.travis.yml), [*.kitchen.docker.yml*](https://github.com/zuazo/owncloud-cookbook/blob/master/.kitchen.docker.yml), [*Rakefile*](https://github.com/zuazo/owncloud-cookbook/blob/master/Rakefile)): Runs kitchen tests against many platforms. Includes Serverspec tests using [infrataster](https://github.com/ryotarai/infrataster).
* [mysql_tuning](https://github.com/zuazo/mysql_tuning-cookbook) cookbook ([*.travis.yml*](https://github.com/zuazo/mysql_tuning-cookbook/blob/master/.travis.yml), [*.kitchen.docker.yml*](https://github.com/zuazo/mysql_tuning-cookbook/blob/master/.kitchen.docker.yml), [*Rakefile*](https://github.com/zuazo/mysql_tuning-cookbook/blob/master/Rakefile)): Runs kitchen tests against many platforms. Includes Serverspec tests.
## Known Issues
### Privileged Containers
It's recommended to run the containers in privileged mode to avoid some weird errors when starting system services or when running Serverspec tests.
```yaml
---
driver:
name: docker
privileged: true
```
### The Test Cannot Exceed 50 Minutes
Each test can not take more than 50 minutes to run within Travis CI.
### Cannot Destroy Containers
Containers inside Travis CI Docker service can not be destroyed, so we need to `$ kitchen verify` instead of `$ kitchen test` to run the tests.
The Travis build error output:
```
Kitchen::ActionFailed: Failed to complete #destroy action: [Expected process to exit with [0], but received '1'
---- Begin output of sudo -E docker -H unix:///var/run/docker.sock stop 1a92da7 ----
STDOUT:
STDERR: Error response from daemon: Cannot stop container 1a92da7: [8] System error: permission denied
Error: failed to stop containers: [1a92da7]
---- End output of sudo -E docker -H unix:///var/run/docker.sock stop 1a92da7 ----
```
### Only One Instance for Each Build
As [containers can not be destroyed](#cannot-destroy-containers), you should run one instance for each build. So things like running all Ubuntu tests in a single build is not recommended.
Look at the examples in this documentation to learn how to do this.
### `bundle install` Error: *No output has been received in the last 10m*
This is a Travis build example output:
```
$ chef exec bundle install
[...]
Installing dep-selector-libgecode 1.0.2 with native extensions
No output has been received in the last 10m0s, this potentially indicates a stalled build or something wrong with the build itself.
```
This is because, for some strange reason, the compilation of certain gems takes too long inside Travis Docker builds. To avoid this error you can install a specific version of ChefDK and use the gems that come with it. This avoids the installation of some heavyweight gems like Berkshelf. For this, you need include in your *Gemfile* the same version of Berkshelf that comes with ChefDK.
For example:
```yaml
# .travis.yml
before_install: curl -L https://www.getchef.com/chef/install.sh | sudo bash -s -- -P chefdk -v 0.18.30
```
```ruby
# Gemfile
gem 'berkshelf', '~> 5.1' # Comes with ChefDK 0.18.30
```
The same applies for other gems you have in your Gemfile: Use the version that comes with ChefDK if possible. If you need gems that conflict with ChefDK, try [this alternatives](#related-projects).
If the error is not due to gems, but a command that can take a long time to run and is very quiet, you may need to run it with some flags to increase verbosity such as: `--verbose`, `--debug`, `--l debug`, ...
### Official CentOS 7 and Fedora Images
Cookbooks requiring [systemd](http://www.freedesktop.org/wiki/Software/systemd/) may not work correctly on CentOS 7 and Fedora containers. See [*Systemd removed in CentOS 7*](https://github.com/docker-library/docs/tree/master/centos#systemd-integration).
You can use alternative images that include systemd. These containers must run in **privileged** mode:
```yaml
# .kitchen.docker.yml
# Non-official images with systemd
- name: centos-7
driver_config:
# https://registry.hub.docker.com/u/milcom/centos7-systemd/dockerfile/
image: milcom/centos7-systemd
privileged: true
- name: fedora
driver_config:
image: fedora/systemd-systemd
privileged: true
```
### Problems with Upstart in Ubuntu
Some cookbooks requiring [Ubuntu Upstart](http://upstart.ubuntu.com/) may not work correctly.
You can use the official Ubuntu images with Upstart enabled:
```yaml
# .kichen.docker.yml
- name: ubuntu-14.10
run_list: recipe[apt]
driver_config:
image: ubuntu-upstart:14.10
```
### Install `netstat` Package
It's recommended to install `net-tools` on some containers if you want to test listening ports with Serverspec. This is because some images come without `netstat` installed.
This is required for example for the following Serverspec test:
```ruby
# test/integration/default/serverspec/default_spec.rb
describe port(80) do
it { should be_listening }
end
```
You can ensure that `netstat` is properly installed running the [`netstat`](https://supermarket.chef.io/cookbooks/netstat) cookbook:
```yaml
# .kitchen.docker.yml
- name: debian-6
run_list:
- recipe[apt]
- recipe[netstat]
```
## Feedback Is Welcome
Currently I'm using this for my own projects. It may not work correctly in many cases. If you use this or a similar approach successfully with other cookbooks, please [open an issue and let me know about your experience](https://github.com/zuazo/kitchen-in-travis-native/issues/new). Problems, discussions and ideas for improvement, of course, are also welcome.
## Acknowledgements
Special thanks to [Jonathan Hartman](https://github.com/RoboticCheese) for his work in the [`test-kitchen-test-chef`](https://github.com/RoboticCheese/test-kitchen-test-chef) cookbook example.
See [here](https://github.com/zuazo/docker-in-travis#acknowledgements) for more.
# License and Author
| | |
|:---------------------|:-----------------------------------------|
| **Author:** | [Xabier de Zuazo](https://github.com/zuazo) (<xabier@zuazo.org>)
| **Contributor:** | [Irving Popovetsky](https://github.com/irvingpop)
| **Contributor:** | [Tim Smith](https://github.com/tas50)
| **Copyright:** | Copyright (c) 2015, Xabier de Zuazo
| **License:** | Apache License, Version 2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
|
zuazo/kitchen-in-travis-native
|
README.md
|
Markdown
|
apache-2.0
| 12,589
|
<html>
<head>
<link rel="stylesheet" href="../../../../lib/hig.css">
<script type="text/javascript" src="../../../../lib/hig.js"></script>
<style>
body{
margin: 30px;
}
.box{
width: 200px;
height: 200px;
}
.group{
margin: 50px 0;
}
</style>
</head>
<body class='hig__colors__hig-gray-60--background'>
<div class='typo-holder-title'></div>
<div class='group'>
<div class='typo-holder-common'></div>
<div class='box hig__shadows__common'></div>
</div>
<div class='group'>
<div class='typo-holder-dropshadow'></div>
<div class='box hig__shadows__dropshadow'></div>
</div>
<div class='group'>
<div class='typo-holder-ir'></div>
<div class='box hig__shadows__inner-right'></div>
</div>
<div class='group'>
<div class='typo-holder-il'></div>
<div class='box hig__shadows__inner-left'></div>
</div>
<script>
new Hig.Typography({
"text": "HIG Shadows",
"type": "h2"
}).mount('.typo-holder-title');
new Hig.Typography({
"text": "Common",
"type": "h3"
}).mount('.typo-holder-common');
new Hig.Typography({
"text": "Dropshadow",
"type": "h3"
}).mount('.typo-holder-dropshadow');
new Hig.Typography({
"text": "Inner-right",
"type": "h3"
}).mount('.typo-holder-ir');
new Hig.Typography({
"text": "Inner-left",
"type": "h3"
}).mount('.typo-holder-il');
</script>
</body>
</html>
|
hyoshizumi/hig
|
packages/vanilla/src/basics/shadows/tests/tests-shadows.html
|
HTML
|
apache-2.0
| 1,945
|
<!DOCTYPE html>
<html lang="en">
<head>
<!--/* Each token will be replaced by their respective titles in the resulting page. */-->
<title layout:title-pattern="$DECORATOR_TITLE - $CONTENT_TITLE">searchahouse.com</title>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<!-- Bootstrap core CSS -->
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet" />
<!-- Custom styles for this template -->
<link href="http://getbootstrap.com/examples/dashboard/dashboard.css" rel="stylesheet" />
</head>
<body>
<!-- header -->
<div th:fragment="header">
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">searchahouse.com | ADMIN</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Dashboard</a></li>
<li><a href="#">Settings</a></li>
<li><a href="#">Profile</a></li>
<li><a href="#">Help</a></li>
</ul>
<form class="navbar-form navbar-right">
<input type="text" class="form-control" placeholder="Search..." />
</form>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<ul class="nav nav-sidebar">
<li th:classappend="${page == 'home' ? 'active' : ''}"><a href="#" th:href="@{/}">Home</a></li>
<li th:classappend="${page == 'agents' ? 'active' : ''}"><a href="#" th:href="@{/admin/listAllAgents}">Agents</a></li>
<li th:classappend="${page == 'properties' ? 'active' : ''}"><a href="#" th:href="@{/admin/listAllProperties}">Properties</a></li>
<li th:classappend="${page == 'leads' ? 'active' : ''}"><a href="#" th:href="@{/admin/listAllLeads}">Leads</a></li>
<li><a href="#">Help</a></li>
</ul>
</div>
</div>
</div>
</div><!-- /.header -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
|
gustavoorsi/searchahouse.com
|
searchahouse-admin/src/main/webapp/WEB-INF/views/thymeleaf/fragments/header.html
|
HTML
|
apache-2.0
| 3,059
|
package china.jiangkai.tool;
public class DateTool
{
private static DateTool dt = null;
public static final int YEAR_BASE = 360;
public static final int MONTH_BASE = 30;
public static final int WEEK_BASE = 10;
public static final int JANUARY = 0;
public static final int FEBRUARY = 1;
public static final int MARCH = 2;
public static final int APRIL = 3;
public static final int MAY = 4;
public static final int JUNE = 5;
public static final int JULY = 6;
public static final int AUGUST = 7;
public static final int SEPTEMBER = 8;
public static final int OCTOBER = 9;
public static final int NOVEMBER = 10;
public static final int DECEMBER = 11;
public static final int SPRING = 0;
public static final int SUMMER = 1;
public static final int AUTUMN = 2;
public static final int WINTER = 3;
public static final int EARLY_WEEK = 0;
public static final int MIDDLE_WEEK = 1;
public static final int LATE_WEEK = 2;
private static final String[] NUM_TO_STR_LIST =
{
"〇", "一", "二", "三", "四", "五", "六", "七", "八", "九",
};
private static final String[] MONTH_TO_STR_LIST =
{
"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月",
"十二月",
};
private static final String[] SEASON_TO_STR_LIST =
{
"春", "夏", "秋", "冬",
};
private static final String[] WEEK_TO_STR_LIST =
{
"上旬", "中旬", "下旬",
};
private DateTool()
{
}
public static DateTool getInstance()
{
if ( dt == null )
{
dt = new DateTool();
}
return dt;
}
public static int getCurrentYear( int days )
{
return (int)(days / YEAR_BASE);
}
public static int getCurrentMonth( int days )
{
return (int)((days % YEAR_BASE) / MONTH_BASE);
}
public static int getCurrentSeason( int days )
{
switch ( getCurrentMonth( days ) )
{
case MARCH:
case APRIL:
case MAY:
return 0;
case JUNE:
case JULY:
case AUGUST:
return 1;
case SEPTEMBER:
case OCTOBER:
case NOVEMBER:
return 2;
case DECEMBER:
case JANUARY:
case FEBRUARY:
return 3;
}
return -1;
}
public static int getCurrentWeek( int days )
{
return (int)((days % MONTH_BASE) / WEEK_BASE);
}
public static int getCurrentDay( int days )
{
return (int)(days % MONTH_BASE + 1);
}
public static String showCurrentYear( int days, int base )
{
int year = getCurrentYear( days ) + base;
StringBuilder sb = new StringBuilder();
while ( year > 0 )
{
sb.insert( 0, NUM_TO_STR_LIST[ year % 10 ] );
year = year / 10;
}
while ( sb.charAt( 0 ) == '〇' )
{
sb.deleteCharAt( 0 );
}
sb.append( "年" );
return sb.toString();
}
public static String showCurrentMonth( int days )
{
return MONTH_TO_STR_LIST[ getCurrentMonth( days ) ];
}
public static String showCurrentSeason( int days )
{
return SEASON_TO_STR_LIST[ getCurrentSeason( days ) ];
}
public static String showCurrentWeek( int days )
{
return WEEK_TO_STR_LIST[ getCurrentWeek( days ) ];
}
public static String showCurrentDay( int days )
{
int day = getCurrentDay( days );
StringBuilder sb = new StringBuilder();
int ten = day / 10;
switch ( ten )
{
case 0:
sb.append( NUM_TO_STR_LIST[ day ] );
sb.append( "日" );
break;
case 1:
sb.append( "十" );
if ( day > 10 )
{
sb.append( NUM_TO_STR_LIST[ day - 10 ] );
}
sb.append( "日" );
break;
default:
sb.append( NUM_TO_STR_LIST[ ten ] );
sb.append( "十" );
if ( day % 10 != 0 )
{
sb.append( NUM_TO_STR_LIST[ day % 10 ] );
}
sb.append( "日" );
break;
}
return sb.toString();
}
public static String showCurrentDate( int days, int base )
{
return showCurrentYear( days, base ) + " " + showCurrentMonth( days )
+ " " + showCurrentDay( days ) + " " + showCurrentSeason( days )
+ " " + showCurrentWeek( days );
}
}
|
tpxpascal/SuperBothel
|
SuperBothel/src/china/jiangkai/tool/DateTool.java
|
Java
|
apache-2.0
| 4,053
|
<?php
namespace Tests\Api;
use Chrisbjr\ApiGuard\Models\ApiKey;
use Sijot\Lease;
use Tests\TestCase;
use Illuminate\Foundation\Testing\{DatabaseMigrations, DatabaseTransactions};
/**
* Class LeaseTest
*
* @package Tests\Api
*/
class LeaseTest extends TestCase
{
use DatabaseMigrations, DatabaseTransactions;
/**
* @test
* @covers \Sijot\Http\Controllers\ApiV1\LeaseController::index()
*/
public function testIndexLeaseUnauthorized()
{
$this->get('api/lease', ['X-Authorization' => 'No Key'])
->assertStatus(401)
->assertJson(["error" => ["code" => "401", "http_code" => "GEN-UNAUTHORIZED", "message" => "Unauthorized."]]);
}
/**
* @test
* @covers \Sijot\Http\Controllers\ApiV1\LeaseController::index()
*/
public function testIndexLeaseAuthorized()
{
$api = factory(ApiKey::class)->create();
$this->get('api/lease', ['X-Authorization' => $api->key])->assertStatus(200);
}
/**
* @test
* @covers \Sijot\Http\Controllers\ApiV1\LeaseController::show()
*/
public function testShowLeaseUnauthorized()
{
$lease = factory(Lease::class)->create();
$this->get(route('lease.show', $lease))
->assertStatus(401)
->assertJson(["error" => ["code" => "401", "http_code" => "GEN-UNAUTHORIZED", "message" => "Unauthorized."]]);
}
/**
* @test
* @covers \Sijot\Http\Controllers\ApiV1\LeaseController::show()
*/
public function testShowLeaseAuthorized()
{
$lease = factory(Lease::class)->create();
$api = factory(ApiKey::class)->create();
$this->get(route('lease.show', $lease), ['X-Authorization' => $api->key])->assertStatus(200);
}
/**
* @test
* @covers \Sijot\Http\Controllers\ApiV1\LeaseController::store()
*/
public function testLeaseCreateAuthorizedValidationErrors()
{
$api = factory(ApiKey::class)->create();
$this->post('api/lease', [], ['X-Authorization' => $api->key, 'Accept' => 'application/json'])
->assertStatus(200);
}
/**
* @test
* @covers \Sijot\Http\Controllers\ApiV1\LeaseController::store()
*/
public function testLeaseCreateAuthorizedNoValidationErrors()
{
$api = factory(ApiKey::class)->create();
$input = [
'status_id' => 1,
'start_datum' => '2018-10-10',
'eind_datum' => '2018-11-11',
'contact_email' => 'name@domain.tld',
'groeps_naam' => 'My Local scouting group'
];
$this->post('api/lease', $input, ['X-Authorization' => $api->key])
->assertStatus(200)
->assertJson(["error" => ["code" => "GEN-CREATED", "http_code" => 200, "message" => trans('api.lease-create-success'),]]);
}
/**
* @test
* @covers \Sijot\Http\Controllers\ApiV1\LeaseController::store()
*/
public function testLeaseCreateUnauthorized()
{
$this->post('api/lease', [], ['X-Authorization' => ''])
->assertStatus(401)
->assertJson(["error" => ["code" => "401", "http_code" => "GEN-UNAUTHORIZED", "message" => "Unauthorized."]]);
}
/**
* @test
* @covers \Sijot\Http\Controllers\ApiV1\LeaseController::destroy()
*/
public function testLeaseDeleteAuthorized()
{
$lease = factory(Lease::class)->create();
$api = factory(ApiKey::class)->create();
$this->delete(route('lease.destroy', $lease), [], ['X-Authorization' => $api->key])
->assertStatus(200)
->assertJson(["error" => ["code" => "GEN-NOT-FOUND", "http_code" => 200, "message" => trans('api.lease-destroy-success')]]);
}
/**
* @test
* @covers \Sijot\Http\Controllers\ApiV1\LeaseController::destroy()
*/
public function testLeaseDeleteUnAuthorized()
{
$lease = factory(Lease::class)->create();
$this->delete(route('lease.destroy', ['id' => $lease->id]), [], ['X-Authorization' => 'No key'])
->assertStatus(401)
->assertJson(["error" => ["code" => "401", "http_code" => "GEN-UNAUTHORIZED", "message" => "Unauthorized."]]);
}
/**
* @test
* @covers \Sijot\Http\Controllers\ApiV1\LeaseController::destroy()
*/
public function testLeaseDeleteNoResource()
{
$api = factory(ApiKey::class)->create();
$this->delete(route('lease.destroy', ['id' => 4000]), [], ['X-Authorization' => $api->key])
->assertStatus(404)
->assertJson(["error" => ["code" => "GEN-NOT-FOUND", "http_code" => 404, "message" => "Resource Not Found",]]);
}
}
|
Scouts-Sint-Joris/SIJOT-3.x
|
tests/Api/LeaseTest.php
|
PHP
|
apache-2.0
| 4,713
|
# Combretum bracteosum Engl. & Diels SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
H. G. A. Engler & K. A. E. Prantl, Nat. Pflanzenfam. 3(7):125. 1893
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Combretaceae/Combretum/Combretum bracteosum/README.md
|
Markdown
|
apache-2.0
| 247
|
#!/bin/bash
# -*- mode:shell-script; coding:utf-8; -*-
#
# Created: <Wed Oct 21 16:58:12 2015>
# Last Updated: <2020-March-13 08:55:50>
#
payload="Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal."
function usage() {
local CMD=`basename $0`
echo "$CMD: "
echo " Invokes the hmac proxy."
echo " Uses the curl utility."
echo "usage: "
echo " $CMD [options] "
echo "options: "
echo " -o org Edge organization"
echo " -e env Edge environment"
echo " -k key client_id"
echo " -s secret client_secret (for computing HMAC)"
echo " -p payload specify the payload to send"
echo " -m hmac the hmac (base64) for that payload"
echo
echo
exit 1
}
echo
echo "This script invokes the hmac API Proxy."
echo "=============================================================================="
sleep 2
while getopts "ho:e:k:s:p:m:" opt; do
case $opt in
h) usage ;;
o) orgname=$OPTARG ;;
e) envname=$OPTARG ;;
k) key=$OPTARG ;;
s) secret=$OPTARG ;;
p) payload=$OPTARG ;;
m) hmac_base64=$OPTARG ;;
*) echo "unknown arg" && usage ;;
esac
done
echo
if [ "X$key" = "X" ]; then
echo "Specify an API key with the -k option"
echo
usage
exit 1
fi
if [ "X$secret" = "X" -a "X$hmac_base64" = "X" ]; then
echo "Specify either an API secret with the -s option, or an hmac with the -h option"
echo
usage
exit 1
fi
if [ "X$orgname" = "X" ]; then
echo "Specify an organization with the -o option"
echo
usage
exit 1
fi
if [ "X$envname" = "X" ]; then
echo "Specify an environment with the -e option"
echo
usage
exit 1
fi
if [ "X$hmac_base64" = "X" ]; then
hmac_base64=`echo -n "$payload" | openssl dgst -sha256 -binary -hmac "${secret}" | openssl enc -base64`
fi
endpoint=https://${orgname}-${envname}.apigee.net/hmac/with-apikey
echo curl -i -X POST \\
echo -d "${payload}" \\
echo -H "apikey: $key" \\
echo -H "hmac-base64: $hmac_base64" \\
echo $endpoint
curl -i -X POST \
-d "${payload}" \
-H "apikey: $key" \
-H "hmac-base64: $hmac_base64" \
$endpoint
|
apigee/iloveapis2015-hmac-httpsignature
|
hmac/client.sh
|
Shell
|
apache-2.0
| 2,204
|
---
title: "Queries"
nav-parent_id: sql
nav-pos: 1
---
<!--
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.
-->
* This will be replaced by the TOC
{:toc}
<div class="codetabs" data-hide-tabs="1" markdown="1">
<div data-lang="java/scala" markdown="1">
SELECT statements and VALUES statements are specified with the `sqlQuery()` method of the `TableEnvironment`. The method returns the result of the SELECT statement (or the VALUES statements) as a `Table`. A `Table` can be used in [subsequent SQL and Table API queries]({% link dev/table/common.md %}#mixing-table-api-and-sql), be [converted into a DataSet or DataStream]({% link dev/table/common.md %}#integration-with-datastream-and-dataset-api), or [written to a TableSink]({% link dev/table/common.md %}#emit-a-table). SQL and Table API queries can be seamlessly mixed and are holistically optimized and translated into a single program.
In order to access a table in a SQL query, it must be [registered in the TableEnvironment]({% link dev/table/common.md %}#register-tables-in-the-catalog). A table can be registered from a [TableSource]({% link dev/table/common.md %}#register-a-tablesource), [Table]({% link dev/table/common.md %}#register-a-table), [CREATE TABLE statement](#create-table), [DataStream, or DataSet]({% link dev/table/common.md %}#register-a-datastream-or-dataset-as-table). Alternatively, users can also [register catalogs in a TableEnvironment]({% link dev/table/catalogs.md %}) to specify the location of the data sources.
For convenience, `Table.toString()` automatically registers the table under a unique name in its `TableEnvironment` and returns the name. So, `Table` objects can be directly inlined into SQL queries as shown in the examples below.
**Note:** Queries that include unsupported SQL features cause a `TableException`. The supported features of SQL on batch and streaming tables are listed in the following sections.
</div>
<div data-lang="python" markdown="1">
SELECT statements and VALUES statements are specified with the `sql_query()` method of the `TableEnvironment`. The method returns the result of the SELECT statement (or the VALUES statements) as a `Table`. A `Table` can be used in [subsequent SQL and Table API queries]({% link dev/table/common.md %}#mixing-table-api-and-sql) or [written to a TableSink]({% link dev/table/common.md %}#emit-a-table). SQL and Table API queries can be seamlessly mixed and are holistically optimized and translated into a single program.
In order to access a table in a SQL query, it must be [registered in the TableEnvironment]({% link dev/table/common.md %}#register-tables-in-the-catalog). A table can be registered from a [TableSource]({% link dev/table/common.md %}#register-a-tablesource), [Table]({% link dev/table/common.md %}#register-a-table), [CREATE TABLE statement](#create-table). Alternatively, users can also [register catalogs in a TableEnvironment]({% link dev/table/catalogs.md %}) to specify the location of the data sources.
For convenience, `str(Table)` automatically registers the table under a unique name in its `TableEnvironment` and returns the name. So, `Table` objects can be directly inlined into SQL queries as shown in the examples below.
**Note:** Queries that include unsupported SQL features cause a `TableException`. The supported features of SQL on batch and streaming tables are listed in the following sections.
</div>
</div>
## Specifying a Query
The following examples show how to specify a SQL queries on registered and inlined tables.
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
{% highlight java %}
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
// ingest a DataStream from an external source
DataStream<Tuple3<Long, String, Integer>> ds = env.addSource(...);
// SQL query with an inlined (unregistered) table
Table table = tableEnv.fromDataStream(ds, $("user"), $("product"), $("amount"));
Table result = tableEnv.sqlQuery(
"SELECT SUM(amount) FROM " + table + " WHERE product LIKE '%Rubber%'");
// SQL query with a registered table
// register the DataStream as view "Orders"
tableEnv.createTemporaryView("Orders", ds, $("user"), $("product"), $("amount"));
// run a SQL query on the Table and retrieve the result as a new Table
Table result2 = tableEnv.sqlQuery(
"SELECT product, amount FROM Orders WHERE product LIKE '%Rubber%'");
// create and register a TableSink
final Schema schema = new Schema()
.field("product", DataTypes.STRING())
.field("amount", DataTypes.INT());
tableEnv.connect(new FileSystem().path("/path/to/file"))
.withFormat(...)
.withSchema(schema)
.createTemporaryTable("RubberOrders");
// run an INSERT SQL on the Table and emit the result to the TableSink
tableEnv.executeSql(
"INSERT INTO RubberOrders SELECT product, amount FROM Orders WHERE product LIKE '%Rubber%'");
{% endhighlight %}
</div>
<div data-lang="scala" markdown="1">
{% highlight scala %}
val env = StreamExecutionEnvironment.getExecutionEnvironment
val tableEnv = StreamTableEnvironment.create(env)
// read a DataStream from an external source
val ds: DataStream[(Long, String, Integer)] = env.addSource(...)
// SQL query with an inlined (unregistered) table
val table = ds.toTable(tableEnv, $"user", $"product", $"amount")
val result = tableEnv.sqlQuery(
s"SELECT SUM(amount) FROM $table WHERE product LIKE '%Rubber%'")
// SQL query with a registered table
// register the DataStream under the name "Orders"
tableEnv.createTemporaryView("Orders", ds, $"user", $"product", $"amount")
// run a SQL query on the Table and retrieve the result as a new Table
val result2 = tableEnv.sqlQuery(
"SELECT product, amount FROM Orders WHERE product LIKE '%Rubber%'")
// create and register a TableSink
val schema = new Schema()
.field("product", DataTypes.STRING())
.field("amount", DataTypes.INT())
tableEnv.connect(new FileSystem().path("/path/to/file"))
.withFormat(...)
.withSchema(schema)
.createTemporaryTable("RubberOrders")
// run an INSERT SQL on the Table and emit the result to the TableSink
tableEnv.executeSql(
"INSERT INTO RubberOrders SELECT product, amount FROM Orders WHERE product LIKE '%Rubber%'")
{% endhighlight %}
</div>
<div data-lang="python" markdown="1">
{% highlight python %}
env = StreamExecutionEnvironment.get_execution_environment()
table_env = StreamTableEnvironment.create(env)
# SQL query with an inlined (unregistered) table
# elements data type: BIGINT, STRING, BIGINT
table = table_env.from_elements(..., ['user', 'product', 'amount'])
result = table_env \
.sql_query("SELECT SUM(amount) FROM %s WHERE product LIKE '%%Rubber%%'" % table)
# create and register a TableSink
t_env.connect(FileSystem().path("/path/to/file")))
.with_format(Csv()
.field_delimiter(',')
.deriveSchema())
.with_schema(Schema()
.field("product", DataTypes.STRING())
.field("amount", DataTypes.BIGINT()))
.create_temporary_table("RubberOrders")
# run an INSERT SQL on the Table and emit the result to the TableSink
table_env \
.execute_sql("INSERT INTO RubberOrders SELECT product, amount FROM Orders WHERE product LIKE '%Rubber%'")
{% endhighlight %}
</div>
</div>
{% top %}
## Execute a Query
<div class="codetabs" data-hide-tabs="1" markdown="1">
<div data-lang="java/scala" markdown="1">
A SELECT statement or a VALUES statement can be executed to collect the content to local through the `TableEnvironment.executeSql()` method. The method returns the result of the SELECT statement (or the VALUES statement) as a `TableResult`. Similar to a SELECT statement, a `Table` object can be executed using the `Table.execute()` method to collect the content of the query to the local client.
`TableResult.collect()` method returns a closeable row iterator. The select job will not be finished unless all result data has been collected. We should actively close the job to avoid resource leak through the `CloseableIterator#close()` method.
We can also print the select result to client console through the `TableResult.print()` method. The result data in `TableResult` can be accessed only once. Thus, `collect()` and `print()` must not be called after each other.
`TableResult.collect()` and `TableResult.print()` have slightly different behaviors under different checkpointing settings (to enable checkpointing for a streaming job, see <a href="{% link deployment/config.md %}#checkpointing">checkpointing config</a>).
* For batch jobs or streaming jobs without checkpointing, `TableResult.collect()` and `TableResult.print()` have neither exactly-once nor at-least-once guarantee. Query results are immediately accessible by the clients once they're produced, but exceptions will be thrown when the job fails and restarts.
* For streaming jobs with exactly-once checkpointing, `TableResult.collect()` and `TableResult.print()` guarantee an end-to-end exactly-once record delivery. A result will be accessible by clients only after its corresponding checkpoint completes.
* For streaming jobs with at-least-once checkpointing, `TableResult.collect()` and `TableResult.print()` guarantee an end-to-end at-least-once record delivery. Query results are immediately accessible by the clients once they're produced, but it is possible for the same result to be delivered multiple times.
</div>
<div data-lang="python" markdown="1">
A SELECT statement or a VALUES statement can be executed to collect the content to local through the `TableEnvironment.execute_sql()` method. The method returns the result of the SELECT statement (or the VALUES statement) as a `TableResult`. Similar to a SELECT statement, a `Table` object can be executed using the `Table.execute()` method to collect the content of the query to the local client.
`TableResult.collect()` method returns a closeable row iterator. The select job will not be finished unless all result data has been collected. We should actively close the job to avoid resource leak through the `CloseableIterator#close()` method.
We can also print the select result to client console through the `TableResult.print()` method. The result data in `TableResult` can be accessed only once. Thus, `collect()` and `print()` must not be called after each other.
`TableResult.collect()` and `TableResult.print()` have slightly different behaviors under different checkpointing settings (to enable checkpointing for a streaming job, see <a href="{% link deployment/config.md %}#checkpointing">checkpointing config</a>).
* For batch jobs or streaming jobs without checkpointing, `TableResult.collect()` and `TableResult.print()` have neither exactly-once nor at-least-once guarantee. Query results are immediately accessible by the clients once they're produced, but exceptions will be thrown when the job fails and restarts.
* For streaming jobs with exactly-once checkpointing, `TableResult.collect()` and `TableResult.print()` guarantee an end-to-end exactly-once record delivery. A result will be accessible by clients only after its corresponding checkpoint completes.
* For streaming jobs with at-least-once checkpointing, `TableResult.collect()` and `TableResult.print()` guarantee an end-to-end at-least-once record delivery. Query results are immediately accessible by the clients once they're produced, but it is possible for the same result to be delivered multiple times.
</div>
</div>
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
{% highlight java %}
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env, settings);
tableEnv.executeSql("CREATE TABLE Orders (`user` BIGINT, product STRING, amount INT) WITH (...)");
// execute SELECT statement
TableResult tableResult1 = tableEnv.executeSql("SELECT * FROM Orders");
// use try-with-resources statement to make sure the iterator will be closed automatically
try (CloseableIterator<Row> it = tableResult1.collect()) {
while(it.hasNext()) {
Row row = it.next();
// handle row
}
}
// execute Table
TableResult tableResult2 = tableEnv.sqlQuery("SELECT * FROM Orders").execute();
tableResult2.print();
{% endhighlight %}
</div>
<div data-lang="scala" markdown="1">
{% highlight scala %}
val env = StreamExecutionEnvironment.getExecutionEnvironment()
val tableEnv = StreamTableEnvironment.create(env, settings)
// enable checkpointing
tableEnv.getConfig.getConfiguration.set(
ExecutionCheckpointingOptions.CHECKPOINTING_MODE, CheckpointingMode.EXACTLY_ONCE)
tableEnv.getConfig.getConfiguration.set(
ExecutionCheckpointingOptions.CHECKPOINTING_INTERVAL, Duration.ofSeconds(10))
tableEnv.executeSql("CREATE TABLE Orders (`user` BIGINT, product STRING, amount INT) WITH (...)")
// execute SELECT statement
val tableResult1 = tableEnv.executeSql("SELECT * FROM Orders")
val it = tableResult1.collect()
try while (it.hasNext) {
val row = it.next
// handle row
}
finally it.close() // close the iterator to avoid resource leak
// execute Table
val tableResult2 = tableEnv.sqlQuery("SELECT * FROM Orders").execute()
tableResult2.print()
{% endhighlight %}
</div>
<div data-lang="python" markdown="1">
{% highlight python %}
env = StreamExecutionEnvironment.get_execution_environment()
table_env = StreamTableEnvironment.create(env, settings)
# enable checkpointing
table_env.get_config().get_configuration().set_string("execution.checkpointing.mode", "EXACTLY_ONCE")
table_env.get_config().get_configuration().set_string("execution.checkpointing.interval", "10s")
table_env.execute_sql("CREATE TABLE Orders (`user` BIGINT, product STRING, amount INT) WITH (...)")
# execute SELECT statement
table_result1 = table_env.execute_sql("SELECT * FROM Orders")
table_result1.print()
# execute Table
table_result2 = table_env.sql_query("SELECT * FROM Orders").execute()
table_result2.print()
{% endhighlight %}
</div>
</div>
{% top %}
## Syntax
Flink parses SQL using [Apache Calcite](https://calcite.apache.org/docs/reference.html), which supports standard ANSI SQL.
The following BNF-grammar describes the superset of supported SQL features in batch and streaming queries. The [Operations](#operations) section shows examples for the supported features and indicates which features are only supported for batch or streaming queries.
{% highlight sql %}
query:
values
| {
select
| selectWithoutFrom
| query UNION [ ALL ] query
| query EXCEPT query
| query INTERSECT query
}
[ ORDER BY orderItem [, orderItem ]* ]
[ LIMIT { count | ALL } ]
[ OFFSET start { ROW | ROWS } ]
[ FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } ONLY]
orderItem:
expression [ ASC | DESC ]
select:
SELECT [ ALL | DISTINCT ]
{ * | projectItem [, projectItem ]* }
FROM tableExpression
[ WHERE booleanExpression ]
[ GROUP BY { groupItem [, groupItem ]* } ]
[ HAVING booleanExpression ]
[ WINDOW windowName AS windowSpec [, windowName AS windowSpec ]* ]
selectWithoutFrom:
SELECT [ ALL | DISTINCT ]
{ * | projectItem [, projectItem ]* }
projectItem:
expression [ [ AS ] columnAlias ]
| tableAlias . *
tableExpression:
tableReference [, tableReference ]*
| tableExpression [ NATURAL ] [ LEFT | RIGHT | FULL ] JOIN tableExpression [ joinCondition ]
joinCondition:
ON booleanExpression
| USING '(' column [, column ]* ')'
tableReference:
tablePrimary
[ matchRecognize ]
[ [ AS ] alias [ '(' columnAlias [, columnAlias ]* ')' ] ]
tablePrimary:
[ TABLE ] tablePath [ dynamicTableOptions ] [systemTimePeriod] [[AS] correlationName]
| LATERAL TABLE '(' functionName '(' expression [, expression ]* ')' ')'
| UNNEST '(' expression ')'
tablePath:
[ [ catalogName . ] schemaName . ] tableName
systemTimePeriod:
FOR SYSTEM_TIME AS OF dateTimeExpression
dynamicTableOptions:
/*+ OPTIONS(key=val [, key=val]*) */
key:
stringLiteral
val:
stringLiteral
values:
VALUES expression [, expression ]*
groupItem:
expression
| '(' ')'
| '(' expression [, expression ]* ')'
| CUBE '(' expression [, expression ]* ')'
| ROLLUP '(' expression [, expression ]* ')'
| GROUPING SETS '(' groupItem [, groupItem ]* ')'
windowRef:
windowName
| windowSpec
windowSpec:
[ windowName ]
'('
[ ORDER BY orderItem [, orderItem ]* ]
[ PARTITION BY expression [, expression ]* ]
[
RANGE numericOrIntervalExpression {PRECEDING}
| ROWS numericExpression {PRECEDING}
]
')'
matchRecognize:
MATCH_RECOGNIZE '('
[ PARTITION BY expression [, expression ]* ]
[ ORDER BY orderItem [, orderItem ]* ]
[ MEASURES measureColumn [, measureColumn ]* ]
[ ONE ROW PER MATCH ]
[ AFTER MATCH
( SKIP TO NEXT ROW
| SKIP PAST LAST ROW
| SKIP TO FIRST variable
| SKIP TO LAST variable
| SKIP TO variable )
]
PATTERN '(' pattern ')'
[ WITHIN intervalLiteral ]
DEFINE variable AS condition [, variable AS condition ]*
')'
measureColumn:
expression AS alias
pattern:
patternTerm [ '|' patternTerm ]*
patternTerm:
patternFactor [ patternFactor ]*
patternFactor:
variable [ patternQuantifier ]
patternQuantifier:
'*'
| '*?'
| '+'
| '+?'
| '?'
| '??'
| '{' { [ minRepeat ], [ maxRepeat ] } '}' ['?']
| '{' repeat '}'
{% endhighlight %}
Flink SQL uses a lexical policy for identifier (table, attribute, function names) similar to Java:
- The case of identifiers is preserved whether or not they are quoted.
- After which, identifiers are matched case-sensitively.
- Unlike Java, back-ticks allow identifiers to contain non-alphanumeric characters (e.g. <code>"SELECT a AS `my field` FROM t"</code>).
String literals must be enclosed in single quotes (e.g., `SELECT 'Hello World'`). Duplicate a single quote for escaping (e.g., `SELECT 'It''s me.'`). Unicode characters are supported in string literals. If explicit unicode code points are required, use the following syntax:
- Use the backslash (`\`) as escaping character (default): `SELECT U&'\263A'`
- Use a custom escaping character: `SELECT U&'#263A' UESCAPE '#'`
{% top %}
## Operations
### Scan, Projection, and Filter
<div markdown="1">
<table class="table table-bordered">
<thead>
<tr>
<th class="text-left" style="width: 20%">Operation</th>
<th class="text-center">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<strong>Scan / Select / As</strong><br>
<span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span>
</td>
<td>
{% highlight sql %}
SELECT * FROM Orders
SELECT a, c AS d FROM Orders
{% endhighlight %}
</td>
</tr>
<tr>
<td>
<strong>Where / Filter</strong><br>
<span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span>
</td>
<td>
{% highlight sql %}
SELECT * FROM Orders WHERE b = 'red'
SELECT * FROM Orders WHERE a % 2 = 0
{% endhighlight %}
</td>
</tr>
<tr>
<td>
<strong>User-defined Scalar Functions (Scalar UDF)</strong><br>
<span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span>
</td>
<td>
<p>UDFs must be registered in the TableEnvironment. See the <a href="{% link dev/table/functions/udfs.md %}">UDF documentation</a> for details on how to specify and register scalar UDFs.</p>
{% highlight sql %}
SELECT PRETTY_PRINT(user) FROM Orders
{% endhighlight %}
</td>
</tr>
</tbody>
</table>
</div>
{% top %}
### Aggregations
<div markdown="1">
<table class="table table-bordered">
<thead>
<tr>
<th class="text-left" style="width: 20%">Operation</th>
<th class="text-center">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<strong>GroupBy Aggregation</strong><br>
<span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span><br>
<span class="label label-info">Result Updating</span>
</td>
<td>
<p><b>Note:</b> GroupBy on a streaming table produces an updating result. See the <a href="{% link dev/table/streaming/dynamic_tables.md %}">Dynamic Tables Streaming Concepts</a> page for details.
</p>
{% highlight sql %}
SELECT a, SUM(b) as d
FROM Orders
GROUP BY a
{% endhighlight %}
</td>
</tr>
<tr>
<td>
<strong>GroupBy Window Aggregation</strong><br>
<span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span>
</td>
<td>
<p>Use a group window to compute a single result row per group. See <a href="#group-windows">Group Windows</a> section for more details.</p>
{% highlight sql %}
SELECT user, SUM(amount)
FROM Orders
GROUP BY TUMBLE(rowtime, INTERVAL '1' DAY), user
{% endhighlight %}
</td>
</tr>
<tr>
<td>
<strong>Over Window aggregation</strong><br>
<span class="label label-primary">Streaming</span>
</td>
<td>
<p><b>Note:</b> All aggregates must be defined over the same window, i.e., same partitioning, sorting, and range. Currently, only windows with PRECEDING (UNBOUNDED and bounded) to CURRENT ROW range are supported. Ranges with FOLLOWING are not supported yet. ORDER BY must be specified on a single <a href="{% link dev/table/streaming/time_attributes.md %}">time attribute</a></p>
{% highlight sql %}
SELECT COUNT(amount) OVER (
PARTITION BY user
ORDER BY proctime
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
FROM Orders
SELECT COUNT(amount) OVER w, SUM(amount) OVER w
FROM Orders
WINDOW w AS (
PARTITION BY user
ORDER BY proctime
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
{% endhighlight %}
</td>
</tr>
<tr>
<td>
<strong>Distinct</strong><br>
<span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span> <br>
<span class="label label-info">Result Updating</span>
</td>
<td>
{% highlight sql %}
SELECT DISTINCT users FROM Orders
{% endhighlight %}
<p><b>Note:</b> For streaming queries the required state to compute the query result might grow infinitely depending on the number of distinct fields. Please provide a query configuration with valid retention interval to prevent excessive state size. See <a href="{% link dev/table/streaming/query_configuration.md %}">Query Configuration</a> for details.</p>
</td>
</tr>
<tr>
<td>
<strong>Grouping sets, Rollup, Cube</strong><br>
<span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span>
<span class="label label-info">Result Updating</span>
</td>
<td>
{% highlight sql %}
SELECT SUM(amount)
FROM Orders
GROUP BY GROUPING SETS ((user), (product))
{% endhighlight %}
<p><b>Note:</b> Streaming mode Grouping sets, Rollup and Cube are only supported in Blink planner.</p>
</td>
</tr>
<tr>
<td>
<strong>Having</strong><br>
<span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span>
</td>
<td>
{% highlight sql %}
SELECT SUM(amount)
FROM Orders
GROUP BY users
HAVING SUM(amount) > 50
{% endhighlight %}
</td>
</tr>
<tr>
<td>
<strong>User-defined Aggregate Functions (UDAGG)</strong><br>
<span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span>
</td>
<td>
<p>UDAGGs must be registered in the TableEnvironment. See the <a href="{% link dev/table/functions/udfs.md %}">UDF documentation</a> for details on how to specify and register UDAGGs.</p>
{% highlight sql %}
SELECT MyAggregate(amount)
FROM Orders
GROUP BY users
{% endhighlight %}
</td>
</tr>
</tbody>
</table>
</div>
{% top %}
### Joins
<div markdown="1">
<table class="table table-bordered">
<thead>
<tr>
<th class="text-left" style="width: 20%">Operation</th>
<th class="text-center">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Inner Equi-join</strong><br>
<span class="label label-primary">Batch</span>
<span class="label label-primary">Streaming</span>
</td>
<td>
<p>Currently, only equi-joins are supported, i.e., joins that have at least one conjunctive condition with an equality predicate. Arbitrary cross or theta joins are not supported.</p>
<p><b>Note:</b> The order of joins is not optimized. Tables are joined in the order in which they are specified in the FROM clause. Make sure to specify tables in an order that does not yield a cross join (Cartesian product) which are not supported and would cause a query to fail.</p>
{% highlight sql %}
SELECT *
FROM Orders INNER JOIN Product ON Orders.productId = Product.id
{% endhighlight %}
<p><b>Note:</b> For streaming queries the required state to compute the query result might grow infinitely depending on the number of distinct input rows. Please provide a query configuration with valid retention interval to prevent excessive state size. See <a href="{% link dev/table/streaming/query_configuration.md %}">Query Configuration</a> for details.</p>
</td>
</tr>
<tr>
<td><strong>Outer Equi-join</strong><br>
<span class="label label-primary">Batch</span>
<span class="label label-primary">Streaming</span>
<span class="label label-info">Result Updating</span>
</td>
<td>
<p>Currently, only equi-joins are supported, i.e., joins that have at least one conjunctive condition with an equality predicate. Arbitrary cross or theta joins are not supported.</p>
<p><b>Note:</b> The order of joins is not optimized. Tables are joined in the order in which they are specified in the FROM clause. Make sure to specify tables in an order that does not yield a cross join (Cartesian product) which are not supported and would cause a query to fail.</p>
{% highlight sql %}
SELECT *
FROM Orders LEFT JOIN Product ON Orders.productId = Product.id
SELECT *
FROM Orders RIGHT JOIN Product ON Orders.productId = Product.id
SELECT *
FROM Orders FULL OUTER JOIN Product ON Orders.productId = Product.id
{% endhighlight %}
<p><b>Note:</b> For streaming queries the required state to compute the query result might grow infinitely depending on the number of distinct input rows. Please provide a query configuration with valid retention interval to prevent excessive state size. See <a href="{% link dev/table/streaming/query_configuration.md %}">Query Configuration</a> for details.</p>
</td>
</tr>
<tr>
<td><strong>Inner/Outer Interval Join</strong><br>
<span class="label label-primary">Batch</span>
<span class="label label-primary">Streaming</span>
</td>
<td>
<p><b>Note:</b> Interval joins are a subset of regular joins that can be processed in a streaming fashion. Both inner and outer joins are supported.</p>
<p>A interval join requires at least one equi-join predicate and a join condition that bounds the time on both sides. Such a condition can be defined by two appropriate range predicates (<code><, <=, >=, ></code>), a <code>BETWEEN</code> predicate, or a single equality predicate that compares <a href="{% link dev/table/streaming/time_attributes.md %}">time attributes</a> of the same type (i.e., processing time or event time) of both input tables.</p>
<p>For example, the following predicates are valid interval join conditions:</p>
<ul>
<li><code>ltime = rtime</code></li>
<li><code>ltime >= rtime AND ltime < rtime + INTERVAL '10' MINUTE</code></li>
<li><code>ltime BETWEEN rtime - INTERVAL '10' SECOND AND rtime + INTERVAL '5' SECOND</code></li>
</ul>
{% highlight sql %}
SELECT *
FROM Orders o, Shipments s
WHERE o.id = s.orderId AND
o.ordertime BETWEEN s.shiptime - INTERVAL '4' HOUR AND s.shiptime
{% endhighlight %}
The example above will join all orders with their corresponding shipments if the order was shipped four hours after the order was received.
</td>
</tr>
<tr>
<td>
<strong>Expanding arrays into a relation</strong><br>
<span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span>
</td>
<td>
<p>Unnesting WITH ORDINALITY is not supported yet.</p>
{% highlight sql %}
-- Array elements are basic type.
SELECT users, tag
FROM Orders CROSS JOIN UNNEST(tags) AS t (tag)
-- Array elements are ROW type. (eg. tags ARRAY<ROW<tag_id INT, tag_name STRING>>)
SELECT users, tag_id, tag_name
FROM Orders CROSS JOIN UNNEST(tags) AS t (tag_id, tag_name)
{% endhighlight %}
</td>
</tr>
<tr>
<td>
<strong>Join with Table Function (UDTF)</strong><br>
<span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span>
</td>
<td>
<p>Joins a table with the results of a table function. Each row of the left (outer) table is joined with all rows produced by the corresponding call of the table function.</p>
<p>User-defined table functions (UDTFs) must be registered before. See the <a href="{% link dev/table/functions/udfs.md %}">UDF documentation</a> for details on how to specify and register UDTFs. </p>
<p><b>Inner Join</b></p>
<p>A row of the left (outer) table is dropped, if its table function call returns an empty result.</p>
{% highlight sql %}
SELECT users, tag
FROM Orders, LATERAL TABLE(unnest_udtf(tags)) AS t(tag)
-- from 1.11, we can also do it like below:
SELECT users, tag
FROM Orders, LATERAL TABLE(unnest_udtf(tags))
{% endhighlight %}
<p><b>Left Outer Join</b></p>
<p>If a table function call returns an empty result, the corresponding outer row is preserved and the result padded with null values.</p>
{% highlight sql %}
SELECT users, tag
FROM Orders LEFT JOIN LATERAL TABLE(unnest_udtf(tags)) AS t(tag) ON TRUE
-- from 1.11, we can also do it like below:
SELECT users, tag
FROM Orders LEFT JOIN LATERAL TABLE(unnest_udtf(tags)) ON TRUE
{% endhighlight %}
<p><b>Note:</b> Currently, only literal <code>TRUE</code> is supported as predicate for a left outer join against a lateral table.</p>
</td>
</tr>
<tr>
<td>
<strong>Join with Temporal Table</strong><br>
<span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span>
</td>
<td>
<p><a href="{% link dev/table/streaming/legacy.md %}">Temporal Tables</a> are tables that track changes over time.
A <a href="{% link dev/table/streaming/legacy.md %}#temporal-table">Temporal Table</a> provides access to the versions of a temporal table at a specific point in time.</p>
<p>Processing-time temporal join and event-time temporal join are supported, inner join and left join are supported.</p>
<p>The event-time temporal join is not suppored in <span class="label label-primary">Batch</span></p>
<p>The following example assumes that <strong>LatestRates</strong> is a <a href="{% link dev/table/streaming/legacy.md %}#temporal-table">Temporal Table</a> which is materialized with the latest rate.</p>
{% highlight sql %}
SELECT
o.amount, o.currency, r.rate, o.amount * r.rate
FROM
Orders AS o
JOIN LatestRates FOR SYSTEM_TIME AS OF o.proctime AS r
ON r.currency = o.currency
{% endhighlight %}
<p>The RHS table can be named with an alias using optional clause <code>[[<strong>AS</strong>] correlationName]</code>, note that the <code><strong>AS</strong></code> keyword is also optional.</p>
<p>For more information please check the more detailed <a href="{% link dev/table/streaming/legacy.md %}">Temporal Tables</a> concept description.</p>
<p>Only supported in Blink planner.</p>
</td>
</tr>
<tr>
<td>
<strong>Join with Temporal Table Function</strong><br>
<span class="label label-primary">Streaming</span>
</td>
<td>
<p><a href="{% link dev/table/streaming/legacy.md %}">Temporal tables</a> are tables that track changes over time.</p>
<p>A <a href="{% link dev/table/streaming/legacy.md %}#temporal-table-functions">Temporal table function</a> provides access to the state of a temporal table at a specific point in time.
The syntax to join a table with a temporal table function is the same as in <i>Join with Table Function</i>.</p>
<p><b>Note:</b> Currently only inner joins with temporal tables are supported.</p>
<p>Assuming <i>Rates</i> is a <a href="{% link dev/table/streaming/legacy.md %}#temporal-table-functions">temporal table function</a>, the join can be expressed in SQL as follows:</p>
{% highlight sql %}
SELECT
o_amount, r_rate
FROM
Orders,
LATERAL TABLE (Rates(o_proctime))
WHERE
r_currency = o_currency
{% endhighlight %}
<p>For more information please check the more detailed <a href="{% link dev/table/streaming/legacy.md %}">temporal tables concept description</a>.</p>
</td>
</tr>
</tbody>
</table>
</div>
{% top %}
### Set Operations
<div markdown="1">
<table class="table table-bordered">
<thead>
<tr>
<th class="text-left" style="width: 20%">Operation</th>
<th class="text-center">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<strong>Union</strong><br>
<span class="label label-primary">Batch</span>
</td>
<td>
{% highlight sql %}
SELECT *
FROM (
(SELECT user FROM Orders WHERE a % 2 = 0)
UNION
(SELECT user FROM Orders WHERE b = 0)
)
{% endhighlight %}
</td>
</tr>
<tr>
<td>
<strong>UnionAll</strong><br>
<span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span>
</td>
<td>
{% highlight sql %}
SELECT *
FROM (
(SELECT user FROM Orders WHERE a % 2 = 0)
UNION ALL
(SELECT user FROM Orders WHERE b = 0)
)
{% endhighlight %}
</td>
</tr>
<tr>
<td>
<strong>Intersect / Except</strong><br>
<span class="label label-primary">Batch</span>
</td>
<td>
{% highlight sql %}
SELECT *
FROM (
(SELECT user FROM Orders WHERE a % 2 = 0)
INTERSECT
(SELECT user FROM Orders WHERE b = 0)
)
{% endhighlight %}
{% highlight sql %}
SELECT *
FROM (
(SELECT user FROM Orders WHERE a % 2 = 0)
EXCEPT
(SELECT user FROM Orders WHERE b = 0)
)
{% endhighlight %}
</td>
</tr>
<tr>
<td>
<strong>In</strong><br>
<span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span>
</td>
<td>
<p>Returns true if an expression exists in a given table sub-query. The sub-query table must consist of one column. This column must have the same data type as the expression.</p>
{% highlight sql %}
SELECT user, amount
FROM Orders
WHERE product IN (
SELECT product FROM NewProducts
)
{% endhighlight %}
<p><b>Note:</b> For streaming queries the operation is rewritten in a join and group operation. The required state to compute the query result might grow infinitely depending on the number of distinct input rows. Please provide a query configuration with valid retention interval to prevent excessive state size. See <a href="{% link dev/table/streaming/query_configuration.md %}">Query Configuration</a> for details.</p>
</td>
</tr>
<tr>
<td>
<strong>Exists</strong><br>
<span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span>
</td>
<td>
<p>Returns true if the sub-query returns at least one row. Only supported if the operation can be rewritten in a join and group operation.</p>
{% highlight sql %}
SELECT user, amount
FROM Orders
WHERE product EXISTS (
SELECT product FROM NewProducts
)
{% endhighlight %}
<p><b>Note:</b> For streaming queries the operation is rewritten in a join and group operation. The required state to compute the query result might grow infinitely depending on the number of distinct input rows. Please provide a query configuration with valid retention interval to prevent excessive state size. See <a href="{% link dev/table/streaming/query_configuration.md %}">Query Configuration</a> for details.</p>
</td>
</tr>
</tbody>
</table>
</div>
{% top %}
### OrderBy & Limit
<div markdown="1">
<table class="table table-bordered">
<thead>
<tr>
<th class="text-left" style="width: 20%">Operation</th>
<th class="text-center">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<strong>Order By</strong><br>
<span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span>
</td>
<td>
<b>Note:</b> The result of streaming queries must be primarily sorted on an ascending <a href="{% link dev/table/streaming/time_attributes.md %}">time attribute</a>. Additional sorting attributes are supported.
{% highlight sql %}
SELECT *
FROM Orders
ORDER BY orderTime
{% endhighlight %}
</td>
</tr>
<tr>
<td><strong>Limit</strong><br>
<span class="label label-primary">Batch</span>
</td>
<td>
<b>Note:</b> The LIMIT clause requires an ORDER BY clause.
{% highlight sql %}
SELECT *
FROM Orders
ORDER BY orderTime
LIMIT 3
{% endhighlight %}
</td>
</tr>
</tbody>
</table>
</div>
{% top %}
### Top-N
<span class="label label-danger">Attention</span> Top-N is only supported in Blink planner.
Top-N queries ask for the N smallest or largest values ordered by columns. Both smallest and largest values sets are considered Top-N queries. Top-N queries are useful in cases where the need is to display only the N bottom-most or the N top-
most records from batch/streaming table on a condition. This result set can be used for further analysis.
Flink uses the combination of a OVER window clause and a filter condition to express a Top-N query. With the power of OVER window `PARTITION BY` clause, Flink also supports per group Top-N. For example, the top five products per category that have the maximum sales in realtime. Top-N queries are supported for SQL on batch and streaming tables.
The following shows the syntax of the TOP-N statement:
{% highlight sql %}
SELECT [column_list]
FROM (
SELECT [column_list],
ROW_NUMBER() OVER ([PARTITION BY col1[, col2...]]
ORDER BY col1 [asc|desc][, col2 [asc|desc]...]) AS rownum
FROM table_name)
WHERE rownum <= N [AND conditions]
{% endhighlight %}
**Parameter Specification:**
- `ROW_NUMBER()`: Assigns an unique, sequential number to each row, starting with one, according to the ordering of rows within the partition. Currently, we only support `ROW_NUMBER` as the over window function. In the future, we will support `RANK()` and `DENSE_RANK()`.
- `PARTITION BY col1[, col2...]`: Specifies the partition columns. Each partition will have a Top-N result.
- `ORDER BY col1 [asc|desc][, col2 [asc|desc]...]`: Specifies the ordering columns. The ordering directions can be different on different columns.
- `WHERE rownum <= N`: The `rownum <= N` is required for Flink to recognize this query is a Top-N query. The N represents the N smallest or largest records will be retained.
- `[AND conditions]`: It is free to add other conditions in the where clause, but the other conditions can only be combined with `rownum <= N` using `AND` conjunction.
<span class="label label-danger">Attention in Streaming Mode</span> The TopN query is <span class="label label-info">Result Updating</span>. Flink SQL will sort the input data stream according to the order key, so if the top N records have been changed, the changed ones will be sent as retraction/update records to downstream.
It is recommended to use a storage which supports updating as the sink of Top-N query. In addition, if the top N records need to be stored in external storage, the result table should have the same unique key with the Top-N query.
The unique keys of Top-N query is the combination of partition columns and rownum column. Top-N query can also derive the unique key of upstream. Take following job as an example, say `product_id` is the unique key of the `ShopSales`, then the unique keys of the Top-N query are [`category`, `rownum`] and [`product_id`].
The following examples show how to specify SQL queries with Top-N on streaming tables. This is an example to get "the top five products per category that have the maximum sales in realtime" we mentioned above.
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
{% highlight java %}
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
// ingest a DataStream from an external source
DataStream<Tuple4<String, String, String, Long>> ds = env.addSource(...);
// register the DataStream as table "ShopSales"
tableEnv.createTemporaryView("ShopSales", ds, $("product_id"), $("category"), $("product_name"), $("sales"));
// select top-5 products per category which have the maximum sales.
Table result1 = tableEnv.sqlQuery(
"SELECT * " +
"FROM (" +
" SELECT *," +
" ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) as row_num" +
" FROM ShopSales)" +
"WHERE row_num <= 5");
{% endhighlight %}
</div>
<div data-lang="scala" markdown="1">
{% highlight scala %}
val env = StreamExecutionEnvironment.getExecutionEnvironment
val tableEnv = TableEnvironment.getTableEnvironment(env)
// read a DataStream from an external source
val ds: DataStream[(String, String, String, Long)] = env.addSource(...)
// register the DataStream under the name "ShopSales"
tableEnv.createTemporaryView("ShopSales", ds, $"product_id", $"category", $"product_name", $"sales")
// select top-5 products per category which have the maximum sales.
val result1 = tableEnv.sqlQuery(
"""
|SELECT *
|FROM (
| SELECT *,
| ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) as row_num
| FROM ShopSales)
|WHERE row_num <= 5
""".stripMargin)
{% endhighlight %}
</div>
</div>
#### No Ranking Output Optimization
As described above, the `rownum` field will be written into the result table as one field of the unique key, which may lead to a lot of records being written to the result table. For example, when the record (say `product-1001`) of ranking 9 is updated and its rank is upgraded to 1, all the records from ranking 1 ~ 9 will be output to the result table as update messages. If the result table receives too many data, it will become the bottleneck of the SQL job.
The optimization way is omitting rownum field in the outer SELECT clause of the Top-N query. This is reasonable because the number of the top N records is usually not large, thus the consumers can sort the records themselves quickly. Without rownum field, in the example above, only the changed record (`product-1001`) needs to be sent to downstream, which can reduce much IO to the result table.
The following example shows how to optimize the above Top-N example in this way:
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
{% highlight java %}
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
// ingest a DataStream from an external source
DataStream<Tuple4<String, String, String, Long>> ds = env.addSource(...);
// register the DataStream as table "ShopSales"
tableEnv.createTemporaryView("ShopSales", ds, $("product_id"), $("category"), $("product_name"), $("sales"));
// select top-5 products per category which have the maximum sales.
Table result1 = tableEnv.sqlQuery(
"SELECT product_id, category, product_name, sales " + // omit row_num field in the output
"FROM (" +
" SELECT *," +
" ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) as row_num" +
" FROM ShopSales)" +
"WHERE row_num <= 5");
{% endhighlight %}
</div>
<div data-lang="scala" markdown="1">
{% highlight scala %}
val env = StreamExecutionEnvironment.getExecutionEnvironment
val tableEnv = TableEnvironment.getTableEnvironment(env)
// read a DataStream from an external source
val ds: DataStream[(String, String, String, Long)] = env.addSource(...)
// register the DataStream under the name "ShopSales"
tableEnv.createTemporaryView("ShopSales", ds, $"product_id", $"category", $"product_name", $"sales")
// select top-5 products per category which have the maximum sales.
val result1 = tableEnv.sqlQuery(
"""
|SELECT product_id, category, product_name, sales -- omit row_num field in the output
|FROM (
| SELECT *,
| ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) as row_num
| FROM ShopSales)
|WHERE row_num <= 5
""".stripMargin)
{% endhighlight %}
</div>
</div>
<span class="label label-danger">Attention in Streaming Mode</span> In order to output the above query to an external storage and have a correct result, the external storage must have the same unique key with the Top-N query. In the above example query, if the `product_id` is the unique key of the query, then the external table should also has `product_id` as the unique key.
{% top %}
### Deduplication
<span class="label label-danger">Attention</span> Deduplication is only supported in Blink planner.
Deduplication is removing rows that duplicate over a set of columns, keeping only the first one or the last one. In some cases, the upstream ETL jobs are not end-to-end exactly-once, this may result in there are duplicate records in the sink in case of failover. However, the duplicate records will affect the correctness of downstream analytical jobs (e.g. `SUM`, `COUNT`). So a deduplication is needed before further analysis.
Flink uses `ROW_NUMBER()` to remove duplicates just like the way of Top-N query. In theory, deduplication is a special case of Top-N which the N is one and order by the processing time or event time.
The following shows the syntax of the Deduplication statement:
{% highlight sql %}
SELECT [column_list]
FROM (
SELECT [column_list],
ROW_NUMBER() OVER ([PARTITION BY col1[, col2...]]
ORDER BY time_attr [asc|desc]) AS rownum
FROM table_name)
WHERE rownum = 1
{% endhighlight %}
**Parameter Specification:**
- `ROW_NUMBER()`: Assigns an unique, sequential number to each row, starting with one.
- `PARTITION BY col1[, col2...]`: Specifies the partition columns, i.e. the deduplicate key.
- `ORDER BY time_attr [asc|desc]`: Specifies the ordering column, it must be a [time attribute]({% link dev/table/streaming/time_attributes.md %}). Currently Flink supports [processing time attribute]({% link dev/table/streaming/time_attributes.md %}#processing-time) and [event time atttribute]({% link dev/table/streaming/time_attributes.md %}#event-time). Ordering by ASC means keeping the first row, ordering by DESC means keeping the last row.
- `WHERE rownum = 1`: The `rownum = 1` is required for Flink to recognize this query is deduplication.
The following examples show how to specify SQL queries with Deduplication on streaming tables.
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
{% highlight java %}
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
// ingest a DataStream from an external source
DataStream<Tuple4<String, String, String, Integer>> ds = env.addSource(...);
// register the DataStream as table "Orders"
tableEnv.createTemporaryView("Orders", ds, $("order_id"), $("user"), $("product"), $("number"), $("proctime").proctime());
// remove duplicate rows on order_id and keep the first occurrence row,
// because there shouldn't be two orders with the same order_id.
Table result1 = tableEnv.sqlQuery(
"SELECT order_id, user, product, number " +
"FROM (" +
" SELECT *," +
" ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY proctime ASC) as row_num" +
" FROM Orders)" +
"WHERE row_num = 1");
{% endhighlight %}
</div>
<div data-lang="scala" markdown="1">
{% highlight scala %}
val env = StreamExecutionEnvironment.getExecutionEnvironment
val tableEnv = TableEnvironment.getTableEnvironment(env)
// read a DataStream from an external source
val ds: DataStream[(String, String, String, Int)] = env.addSource(...)
// register the DataStream under the name "Orders"
tableEnv.createTemporaryView("Orders", ds, $"order_id", $"user", $"product", $"number", $"proctime".proctime)
// remove duplicate rows on order_id and keep the first occurrence row,
// because there shouldn't be two orders with the same order_id.
val result1 = tableEnv.sqlQuery(
"""
|SELECT order_id, user, product, number
|FROM (
| SELECT *,
| ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY proctime DESC) as row_num
| FROM Orders)
|WHERE row_num = 1
""".stripMargin)
{% endhighlight %}
</div>
</div>
{% top %}
Deduplication can keep the time attribute of input stream, this is very helpful when the downstream operation is window aggregation or join operation.
Both processing-time deduplication and event-time deduplication support working on mini-batch mode, this is more performance friendly, please see also [mini-batch configuration]({% link dev/table/config.md %}#table-exec-mini-batch-enabled) for how to enable mini-batch mode..
### Group Windows
Group windows are defined in the `GROUP BY` clause of a SQL query. Just like queries with regular `GROUP BY` clauses, queries with a `GROUP BY` clause that includes a group window function compute a single result row per group. The following group windows functions are supported for SQL on batch and streaming tables.
<table class="table table-bordered">
<thead>
<tr>
<th class="text-left" style="width: 30%">Group Window Function</th>
<th class="text-left">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>TUMBLE(time_attr, interval)</code></td>
<td>Defines a tumbling time window. A tumbling time window assigns rows to non-overlapping, continuous windows with a fixed duration (<code>interval</code>). For example, a tumbling window of 5 minutes groups rows in 5 minutes intervals. Tumbling windows can be defined on event-time (stream + batch) or processing-time (stream).</td>
</tr>
<tr>
<td><code>HOP(time_attr, interval, interval)</code></td>
<td>Defines a hopping time window (called sliding window in the Table API). A hopping time window has a fixed duration (second <code>interval</code> parameter) and hops by a specified hop interval (first <code>interval</code> parameter). If the hop interval is smaller than the window size, hopping windows are overlapping. Thus, rows can be assigned to multiple windows. For example, a hopping window of 15 minutes size and 5 minute hop interval assigns each row to 3 different windows of 15 minute size, which are evaluated in an interval of 5 minutes. Hopping windows can be defined on event-time (stream + batch) or processing-time (stream).</td>
</tr>
<tr>
<td><code>SESSION(time_attr, interval)</code></td>
<td>Defines a session time window. Session time windows do not have a fixed duration but their bounds are defined by a time <code>interval</code> of inactivity, i.e., a session window is closed if no event appears for a defined gap period. For example a session window with a 30 minute gap starts when a row is observed after 30 minutes inactivity (otherwise the row would be added to an existing window) and is closed if no row is added within 30 minutes. Session windows can work on event-time (stream + batch) or processing-time (stream).</td>
</tr>
</tbody>
</table>
#### Time Attributes
For SQL queries on streaming tables, the `time_attr` argument of the group window function must refer to a valid time attribute that specifies the processing time or event time of rows. See the [documentation of time attributes]({% link dev/table/streaming/time_attributes.md %}) to learn how to define time attributes.
For SQL on batch tables, the `time_attr` argument of the group window function must be an attribute of type `TIMESTAMP`.
#### Selecting Group Window Start and End Timestamps
The start and end timestamps of group windows as well as time attributes can be selected with the following auxiliary functions:
<table class="table table-bordered">
<thead>
<tr>
<th class="text-left" style="width: 40%">Auxiliary Function</th>
<th class="text-left">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code>TUMBLE_START(time_attr, interval)</code><br/>
<code>HOP_START(time_attr, interval, interval)</code><br/>
<code>SESSION_START(time_attr, interval)</code><br/>
</td>
<td><p>Returns the timestamp of the inclusive lower bound of the corresponding tumbling, hopping, or session window.</p></td>
</tr>
<tr>
<td>
<code>TUMBLE_END(time_attr, interval)</code><br/>
<code>HOP_END(time_attr, interval, interval)</code><br/>
<code>SESSION_END(time_attr, interval)</code><br/>
</td>
<td><p>Returns the timestamp of the <i>exclusive</i> upper bound of the corresponding tumbling, hopping, or session window.</p>
<p><b>Note:</b> The exclusive upper bound timestamp <i>cannot</i> be used as a <a href="{% link dev/table/streaming/time_attributes.md %}">rowtime attribute</a> in subsequent time-based operations, such as <a href="#joins">interval joins</a> and <a href="#aggregations">group window or over window aggregations</a>.</p></td>
</tr>
<tr>
<td>
<code>TUMBLE_ROWTIME(time_attr, interval)</code><br/>
<code>HOP_ROWTIME(time_attr, interval, interval)</code><br/>
<code>SESSION_ROWTIME(time_attr, interval)</code><br/>
</td>
<td><p>Returns the timestamp of the <i>inclusive</i> upper bound of the corresponding tumbling, hopping, or session window.</p>
<p>The resulting attribute is a <a href="{% link dev/table/streaming/time_attributes.md %}">rowtime attribute</a> that can be used in subsequent time-based operations such as <a href="#joins">interval joins</a> and <a href="#aggregations">group window or over window aggregations</a>.</p></td>
</tr>
<tr>
<td>
<code>TUMBLE_PROCTIME(time_attr, interval)</code><br/>
<code>HOP_PROCTIME(time_attr, interval, interval)</code><br/>
<code>SESSION_PROCTIME(time_attr, interval)</code><br/>
</td>
<td><p>Returns a <a href="{% link dev/table/streaming/time_attributes.md %}#processing-time">proctime attribute</a> that can be used in subsequent time-based operations such as <a href="#joins">interval joins</a> and <a href="#aggregations">group window or over window aggregations</a>.</p></td>
</tr>
</tbody>
</table>
*Note:* Auxiliary functions must be called with exactly same arguments as the group window function in the `GROUP BY` clause.
The following examples show how to specify SQL queries with group windows on streaming tables.
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
{% highlight java %}
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
// ingest a DataStream from an external source
DataStream<Tuple3<Long, String, Integer>> ds = env.addSource(...);
// register the DataStream as table "Orders"
tableEnv.createTemporaryView("Orders", ds, $("user"), $("product"), $("amount"), $("proctime").proctime(), $("rowtime").rowtime());
// compute SUM(amount) per day (in event-time)
Table result1 = tableEnv.sqlQuery(
"SELECT user, " +
" TUMBLE_START(rowtime, INTERVAL '1' DAY) as wStart, " +
" SUM(amount) FROM Orders " +
"GROUP BY TUMBLE(rowtime, INTERVAL '1' DAY), user");
// compute SUM(amount) per day (in processing-time)
Table result2 = tableEnv.sqlQuery(
"SELECT user, SUM(amount) FROM Orders GROUP BY TUMBLE(proctime, INTERVAL '1' DAY), user");
// compute every hour the SUM(amount) of the last 24 hours in event-time
Table result3 = tableEnv.sqlQuery(
"SELECT product, SUM(amount) FROM Orders GROUP BY HOP(rowtime, INTERVAL '1' HOUR, INTERVAL '1' DAY), product");
// compute SUM(amount) per session with 12 hour inactivity gap (in event-time)
Table result4 = tableEnv.sqlQuery(
"SELECT user, " +
" SESSION_START(rowtime, INTERVAL '12' HOUR) AS sStart, " +
" SESSION_ROWTIME(rowtime, INTERVAL '12' HOUR) AS snd, " +
" SUM(amount) " +
"FROM Orders " +
"GROUP BY SESSION(rowtime, INTERVAL '12' HOUR), user");
{% endhighlight %}
</div>
<div data-lang="scala" markdown="1">
{% highlight scala %}
val env = StreamExecutionEnvironment.getExecutionEnvironment
val tableEnv = StreamTableEnvironment.create(env)
// read a DataStream from an external source
val ds: DataStream[(Long, String, Int)] = env.addSource(...)
// register the DataStream under the name "Orders"
tableEnv.createTemporaryView("Orders", ds, $"user", $"product", $"amount", $"proctime".proctime, $"rowtime".rowtime)
// compute SUM(amount) per day (in event-time)
val result1 = tableEnv.sqlQuery(
"""
|SELECT
| user,
| TUMBLE_START(rowtime, INTERVAL '1' DAY) as wStart,
| SUM(amount)
| FROM Orders
| GROUP BY TUMBLE(rowtime, INTERVAL '1' DAY), user
""".stripMargin)
// compute SUM(amount) per day (in processing-time)
val result2 = tableEnv.sqlQuery(
"SELECT user, SUM(amount) FROM Orders GROUP BY TUMBLE(proctime, INTERVAL '1' DAY), user")
// compute every hour the SUM(amount) of the last 24 hours in event-time
val result3 = tableEnv.sqlQuery(
"SELECT product, SUM(amount) FROM Orders GROUP BY HOP(rowtime, INTERVAL '1' HOUR, INTERVAL '1' DAY), product")
// compute SUM(amount) per session with 12 hour inactivity gap (in event-time)
val result4 = tableEnv.sqlQuery(
"""
|SELECT
| user,
| SESSION_START(rowtime, INTERVAL '12' HOUR) AS sStart,
| SESSION_END(rowtime, INTERVAL '12' HOUR) AS sEnd,
| SUM(amount)
| FROM Orders
| GROUP BY SESSION(rowtime(), INTERVAL '12' HOUR), user
""".stripMargin)
{% endhighlight %}
</div>
</div>
{% top %}
### Pattern Recognition
<div markdown="1">
<table class="table table-bordered">
<thead>
<tr>
<th class="text-left" style="width: 20%">Operation</th>
<th class="text-center">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<strong>MATCH_RECOGNIZE</strong><br>
<span class="label label-primary">Streaming</span>
</td>
<td>
<p>Searches for a given pattern in a streaming table according to the <code>MATCH_RECOGNIZE</code> <a href="https://standards.iso.org/ittf/PubliclyAvailableStandards/c065143_ISO_IEC_TR_19075-5_2016.zip">ISO standard</a>. This makes it possible to express complex event processing (CEP) logic in SQL queries.</p>
<p>For a more detailed description, see the dedicated page for <a href="{% link dev/table/streaming/match_recognize.md %}">detecting patterns in tables</a>.</p>
{% highlight sql %}
SELECT T.aid, T.bid, T.cid
FROM MyTable
MATCH_RECOGNIZE (
PARTITION BY userid
ORDER BY proctime
MEASURES
A.id AS aid,
B.id AS bid,
C.id AS cid
PATTERN (A B C)
DEFINE
A AS name = 'a',
B AS name = 'b',
C AS name = 'c'
) AS T
{% endhighlight %}
</td>
</tr>
</tbody>
</table>
</div>
{% top %}
|
aljoscha/flink
|
docs/dev/table/sql/queries.md
|
Markdown
|
apache-2.0
| 60,883
|
-- Upgrade MetaStore schema from 3.2.0 to 4.0.0
-- HIVE-19416
ALTER TABLE "APP"."TBLS" ADD WRITE_ID bigint DEFAULT 0;
ALTER TABLE "APP"."PARTITIONS" ADD WRITE_ID bigint DEFAULT 0;
-- HIVE-20793
ALTER TABLE "APP"."WM_RESOURCEPLAN" ADD NS VARCHAR(128);
UPDATE "APP"."WM_RESOURCEPLAN" SET NS = 'default' WHERE NS IS NULL;
DROP INDEX "APP"."UNIQUE_WM_RESOURCEPLAN";
CREATE UNIQUE INDEX "APP"."UNIQUE_WM_RESOURCEPLAN" ON "APP"."WM_RESOURCEPLAN" ("NS", "NAME");
-- HIVE-21063
CREATE UNIQUE INDEX "APP"."NOTIFICATION_LOG_EVENT_ID" ON "APP"."NOTIFICATION_LOG" ("EVENT_ID");
-- HIVE-22046 (DEFAULT HIVE)
ALTER TABLE "APP"."TAB_COL_STATS" ADD ENGINE VARCHAR(128);
UPDATE "APP"."TAB_COL_STATS" SET ENGINE = 'hive' WHERE ENGINE IS NULL;
ALTER TABLE "APP"."PART_COL_STATS" ADD ENGINE VARCHAR(128);
UPDATE "APP"."PART_COL_STATS" SET ENGINE = 'hive' WHERE ENGINE IS NULL;
CREATE TABLE "APP"."SCHEDULED_QUERIES" (
"SCHEDULED_QUERY_ID" bigint primary key not null,
"SCHEDULE_NAME" varchar(256) not null,
"ENABLED" CHAR(1) NOT NULL DEFAULT 'N',
"CLUSTER_NAMESPACE" varchar(256) not null,
"USER" varchar(128) not null,
"SCHEDULE" varchar(256) not null,
"QUERY" varchar(4000) not null,
"NEXT_EXECUTION" integer
);
CREATE INDEX NEXTEXECUTIONINDEX ON APP.SCHEDULED_QUERIES (ENABLED,CLUSTER_NAMESPACE,NEXT_EXECUTION);
CREATE UNIQUE INDEX UNIQUE_SCHEDULED_QUERIES_NAME ON APP.SCHEDULED_QUERIES (SCHEDULE_NAME,CLUSTER_NAMESPACE);
CREATE TABLE APP.SCHEDULED_EXECUTIONS (
SCHEDULED_EXECUTION_ID bigint primary key not null,
EXECUTOR_QUERY_ID VARCHAR(256),
SCHEDULED_QUERY_ID bigint not null,
START_TIME integer not null,
END_TIME INTEGER,
LAST_UPDATE_TIME INTEGER,
ERROR_MESSAGE VARCHAR(2000),
STATE VARCHAR(256),
CONSTRAINT SCHEDULED_EXECUTIONS_SCHQ_FK FOREIGN KEY (SCHEDULED_QUERY_ID) REFERENCES APP.SCHEDULED_QUERIES(SCHEDULED_QUERY_ID) ON DELETE CASCADE
);
CREATE INDEX LASTUPDATETIMEINDEX ON APP.SCHEDULED_EXECUTIONS (LAST_UPDATE_TIME);
CREATE INDEX SCHEDULED_EXECUTIONS_SCHQID ON APP.SCHEDULED_EXECUTIONS (SCHEDULED_QUERY_ID);
CREATE UNIQUE INDEX SCHEDULED_EXECUTIONS_UNIQUE_ID ON APP.SCHEDULED_EXECUTIONS (SCHEDULED_EXECUTION_ID);
-- HIVE-22729
ALTER TABLE COMPACTION_QUEUE ADD CQ_ERROR_MESSAGE clob;
ALTER TABLE COMPLETED_COMPACTIONS ADD CC_ERROR_MESSAGE clob;
-- HIVE-22728
ALTER TABLE "APP"."KEY_CONSTRAINTS" DROP CONSTRAINT "CONSTRAINTS_PK";
ALTER TABLE "APP"."KEY_CONSTRAINTS" ADD CONSTRAINT "CONSTRAINTS_PK" PRIMARY KEY ("PARENT_TBL_ID", "CONSTRAINT_NAME", "POSITION");
-- HIVE-21487
CREATE INDEX COMPLETED_COMPACTIONS_RES ON COMPLETED_COMPACTIONS (CC_DATABASE,CC_TABLE,CC_PARTITION);
-- HIVE-22872
ALTER TABLE "SCHEDULED_QUERIES" ADD "ACTIVE_EXECUTION_ID" bigint;
-- HIVE-22995
ALTER TABLE "APP"."DBS" ADD COLUMN "DB_MANAGED_LOCATION_URI" VARCHAR(4000);
-- HIVE-23107
ALTER TABLE COMPACTION_QUEUE ADD CQ_NEXT_TXN_ID bigint;
DROP TABLE MIN_HISTORY_LEVEL;
-- HIVE-23048
INSERT INTO TXNS (TXN_ID, TXN_STATE, TXN_STARTED, TXN_LAST_HEARTBEAT, TXN_USER, TXN_HOST)
SELECT COALESCE(MAX(CTC_TXNID),0), 'c', 0, 0, '_', '_' FROM COMPLETED_TXN_COMPONENTS;
INSERT INTO TXNS (TXN_ID, TXN_STATE, TXN_STARTED, TXN_LAST_HEARTBEAT, TXN_USER, TXN_HOST)
VALUES (1000000000, 'c', 0, 0, '_', '_');
ALTER TABLE TXNS ADD COLUMN TXN_ID_TMP bigint;
UPDATE TXNS SET TXN_ID_TMP=TXN_ID;
ALTER TABLE TXNS DROP COLUMN TXN_ID;
ALTER TABLE TXNS ADD COLUMN TXN_ID BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY (START WITH 1000000001, INCREMENT BY 1);
UPDATE TXNS SET TXN_ID=TXN_ID_TMP;
ALTER TABLE TXNS DROP COLUMN TXN_ID_TMP;
RENAME TABLE NEXT_TXN_ID TO TXN_LOCK_TBL;
RENAME COLUMN TXN_LOCK_TBL.NTXN_NEXT TO TXN_LOCK;
--HIVE-23516
CREATE TABLE "APP"."REPLICATION_METRICS" (
"RM_SCHEDULED_EXECUTION_ID" bigint NOT NULL,
"RM_POLICY" varchar(256) NOT NULL,
"RM_DUMP_EXECUTION_ID" bigint NOT NULL,
"RM_METADATA" varchar(4000),
"RM_PROGRESS" varchar(4000),
PRIMARY KEY("RM_SCHEDULED_EXECUTION_ID")
);
CREATE INDEX "POLICY_IDX" ON "APP"."REPLICATION_METRICS" ("RM_POLICY");
CREATE INDEX "DUMP_IDX" ON "APP"."REPLICATION_METRICS" ("RM_DUMP_EXECUTION_ID");
-- This needs to be the last thing done. Insert any changes above this line.
UPDATE "APP".VERSION SET SCHEMA_VERSION='4.0.0', VERSION_COMMENT='Hive release version 4.0.0' where VER_ID=1;
|
vineetgarg02/hive
|
standalone-metastore/metastore-server/src/main/sql/derby/upgrade-3.2.0-to-4.0.0.derby.sql
|
SQL
|
apache-2.0
| 4,318
|
---
layout: global
title: CREATE TABLE LIKE
displayTitle: CREATE TABLE LIKE
license: |
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.
---
### Description
The `CREATE TABLE` statement defines a new table using the definition/metadata of an existing table or view.
### Syntax
{% highlight sql %}
CREATE TABLE [IF NOT EXISTS] table_identifier LIKE source_table_identifier
USING data_source
[ ROW FORMAT row_format ]
[ STORED AS file_format ]
[ TBLPROPERTIES ( key1=val1, key2=val2, ... ) ]
[ LOCATION path ]
{% endhighlight %}
### Parameters
<dl>
<dt><code><em>table_identifier</em></code></dt>
<dd>
Specifies a table name, which may be optionally qualified with a database name.<br><br>
<b>Syntax:</b> [ TBLPROPERTIES ( key1=val1, key2=val2, ... ) ]
<code>
[ database_name. ] table_name
</code>
</dd>
</dl>
<dl>
<dt><code><em>USING data_source</em></code></dt>
<dd>Data Source is the input format used to create the table. Data source can be CSV, TXT, ORC, JDBC, PARQUET, etc.</dd>
</dl>
<dl>
<dt><code><em>ROW FORMAT</em></code></dt>
<dd>SERDE is used to specify a custom SerDe or the DELIMITED clause in order to use the native SerDe.</dd>
</dl>
<dl>
<dt><code><em>STORED AS</em></code></dt>
<dd>File format for table storage, could be TEXTFILE, ORC, PARQUET,etc.</dd>
</dl>
<dl>
<dt><code><em>TBLPROPERTIES</em></code></dt>
<dd>Table properties that have to be set are specified, such as `created.by.user`, `owner`, etc.
</dd>
</dl>
<dl>
<dt><code><em>LOCATION</em></code></dt>
<dd>Path to the directory where table data is stored,Path to the directory where table data is stored, which could be a path on distributed storage like HDFS, etc. Location to create an external table.</dd>
</dl>
### Examples
{% highlight sql %}
-- Create table using an existing table
CREATE TABLE Student_Dupli like Student;
-- Create table like using a data source
CREATE TABLE Student_Dupli like Student USING CSV;
-- Table is created as external table at the location specified
CREATE TABLE Student_Dupli like Student location '/root1/home';
-- Create table like using a rowformat
CREATE TABLE Student_Dupli like Student
ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
STORED AS TEXTFILE
TBLPROPERTIES ('owner'='xxxx');
{% endhighlight %}
### Related Statements
* [CREATE TABLE USING DATASOURCE](sql-ref-syntax-ddl-create-table-datasource.html)
* [CREATE TABLE USING HIVE FORMAT](sql-ref-syntax-ddl-create-table-hiveformat.html)
|
kevinyu98/spark
|
docs/sql-ref-syntax-ddl-create-table-like.md
|
Markdown
|
apache-2.0
| 3,256
|
package fr.ensicaen.simulator.model.mediator.listener;
import fr.ensicaen.simulator.model.mediator.Mediator;
public interface MediatorListener {
/**
* Invoquée lorsque le mediator est utilisé pour envoyer des donnees.
*/
public void onSendData(Mediator m, boolean response, String data);
}
|
jmarginier/simulator
|
simulator/src/main/java/fr/ensicaen/simulator/model/mediator/listener/MediatorListener.java
|
Java
|
apache-2.0
| 302
|
import {CommandLineBinding} from "./CommandLineBinding";
import {
CommandInputArraySchema,
CommandInputEnumSchema,
CommandInputMapSchema,
CommandInputRecordSchema,
CommandInputSchema
} from "./CommandInputSchema";
import {Datatype} from "./Datatype";
export interface CommandInputRecordField {
name: string;
type?: Datatype | CommandInputSchema | CommandInputArraySchema | CommandInputMapSchema
| CommandInputEnumSchema | CommandInputRecordSchema | string | Array<Datatype
| CommandInputSchema | CommandInputArraySchema | CommandInputMapSchema
| CommandInputEnumSchema | CommandInputRecordSchema | string>;
inputBinding?: CommandLineBinding;
description?: string;
label?: string;
}
|
rabix/cwl-ts
|
src/mappings/d2sb/CommandInputRecordField.ts
|
TypeScript
|
apache-2.0
| 746
|
/*
* 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.ivy.plugins.resolver;
import java.io.File;
import java.net.MalformedURLException;
import org.apache.ivy.core.event.EventManager;
import org.apache.ivy.core.module.descriptor.DefaultDependencyDescriptor;
import org.apache.ivy.core.module.id.ModuleRevisionId;
import org.apache.ivy.core.resolve.ResolveData;
import org.apache.ivy.core.resolve.ResolveEngine;
import org.apache.ivy.core.resolve.ResolveOptions;
import org.apache.ivy.core.resolve.ResolvedModuleRevision;
import org.apache.ivy.core.settings.IvySettings;
import org.apache.ivy.core.sort.SortEngine;
import org.apache.ivy.util.CacheCleaner;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class Maven2LocalTest {
private IvySettings settings;
private ResolveEngine engine;
private ResolveData data;
private File cache;
@Before
public void setUp() {
settings = new IvySettings();
engine = new ResolveEngine(settings, new EventManager(), new SortEngine(settings));
cache = new File("build/cache");
data = new ResolveData(engine, new ResolveOptions());
cache.mkdirs();
settings.setDefaultCache(cache);
}
@After
public void tearDown() {
CacheCleaner.deleteDir(cache);
}
@Test
public void testUseMetadataForListing() throws Exception {
IBiblioResolver resolver = maven2Resolver();
ResolvedModuleRevision m = resolver.getDependency(new DefaultDependencyDescriptor(
ModuleRevisionId.newInstance("org.apache", "test-metadata", "latest.integration"),
false), data);
assertNotNull(m);
// should trust the metadata (latest=1.1) instead of listing revisions (latest=1.2)
assertEquals(ModuleRevisionId.newInstance("org.apache", "test-metadata", "1.1"), m.getId());
}
@Test
public void testNotUseMetadataForListing() throws Exception {
IBiblioResolver resolver = maven2Resolver();
resolver.setUseMavenMetadata(false);
ResolvedModuleRevision m = resolver.getDependency(new DefaultDependencyDescriptor(
ModuleRevisionId.newInstance("org.apache", "test-metadata", "latest.integration"),
false), data);
assertNotNull(m);
// should trust listing revisions (latest=1.2) instead of the metadata (latest=1.1)
assertEquals(ModuleRevisionId.newInstance("org.apache", "test-metadata", "1.2"), m.getId());
}
private IBiblioResolver maven2Resolver() throws MalformedURLException {
IBiblioResolver resolver = new IBiblioResolver();
resolver.setSettings(settings);
resolver.setName("maven2");
resolver.setM2compatible(true);
resolver.setRoot(new File("test/repositories/m2").toURI().toURL().toExternalForm());
return resolver;
}
}
|
jaikiran/ant-ivy
|
test/java/org/apache/ivy/plugins/resolver/Maven2LocalTest.java
|
Java
|
apache-2.0
| 3,763
|
/*
* Copyright © 2009 HotPads (admin@hotpads.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 io.datarouter.aws.secretsmanager;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.services.secretsmanager.AWSSecretsManager;
import com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder;
import com.amazonaws.services.secretsmanager.model.CreateSecretRequest;
import com.amazonaws.services.secretsmanager.model.DeleteSecretRequest;
import com.amazonaws.services.secretsmanager.model.GetSecretValueRequest;
import com.amazonaws.services.secretsmanager.model.GetSecretValueResult;
import com.amazonaws.services.secretsmanager.model.ListSecretsRequest;
import com.amazonaws.services.secretsmanager.model.ListSecretsResult;
import com.amazonaws.services.secretsmanager.model.ResourceExistsException;
import com.amazonaws.services.secretsmanager.model.ResourceNotFoundException;
import com.amazonaws.services.secretsmanager.model.SecretListEntry;
import com.amazonaws.services.secretsmanager.model.UpdateSecretRequest;
import io.datarouter.secret.client.Secret;
import io.datarouter.secret.client.SecretClient;
import io.datarouter.secret.exception.SecretExistsException;
import io.datarouter.secret.exception.SecretNotFoundException;
/**
* Notes:
*
* clientRequestToken (usually UUID) is used for idempotency of secret manipulation AND becomes the versionID of
* the secret after changes. not sure if it would be better to try to use that or use version stage for explicit
* versioning tracking/manipulation. the latter is intended for rotation, rather than just explicit versioning. but the
* form is a randomly generated UUID, so I don't know if it makes sense to manually use it instead.
*/
public class AwsSecretClient implements SecretClient{
private final AWSSecretsManager client;
public AwsSecretClient(AWSCredentialsProvider awsCredentialsProvider, String region){
client = AWSSecretsManagerClientBuilder.standard()
.withCredentials(awsCredentialsProvider)
.withRegion(region)
.build();
}
@Override
public final void create(Secret secret){
var request = new CreateSecretRequest()
.withName(secret.getName())
.withSecretString(secret.getValue());
try{
client.createSecret(request);
}catch(ResourceExistsException e){
throw new SecretExistsException(secret.getName(), e);
}
}
@Override
public final Secret read(String name){
var request = new GetSecretValueRequest()
.withSecretId(name);
// NOTES:
// only specify one of the following (optional)
// .withVersionId("")// manual version
// .withVersionStage("")// related to AWS rotation
try{
GetSecretValueResult result = client.getSecretValue(request);
return new Secret(name, result.getSecretString());
}catch(ResourceNotFoundException e){
throw new SecretNotFoundException(name, e);
}
}
@Override
public final List<String> listNames(Optional<String> prefix){
List<String> secretNames = new ArrayList<>();
String nextToken = null;
do{
var request = new ListSecretsRequest().withNextToken(nextToken);
ListSecretsResult result = client.listSecrets(request);
nextToken = result.getNextToken();
result.getSecretList().stream()
.map(SecretListEntry::getName)
.filter(name -> prefix.map(
current -> current.length() < name.length() && name.startsWith(current))
.orElse(true))
.forEach(secretNames::add);
}while(nextToken != null);
return secretNames;
}
@Override
public final void update(Secret secret){
// this can update various stuff (like description and kms key) AND updates the version stage to AWSCURRENT.
// for rotation, use PutSecretValue, which only updates the version stages and value of a secret explicitly
var request = new UpdateSecretRequest()
.withSecretId(secret.getName())
.withSecretString(secret.getValue());
try{
client.updateSecret(request);
}catch(ResourceExistsException e){
throw new SecretExistsException("Requested update already exists.", secret.getName(), e);
}catch(ResourceNotFoundException e){
throw new SecretNotFoundException(secret.getName(), e);
}
}
@Override
public final void delete(String name){
var request = new DeleteSecretRequest()
.withSecretId(name);
// additional options:
// .withForceDeleteWithoutRecovery(true)//might be useful at some point?
// .withRecoveryWindowInDays(0L);//7-30 days to undelete. default 30
try{
client.deleteSecret(request);
}catch(ResourceNotFoundException e){
throw new SecretNotFoundException(name, e);
}
}
/**
* validates secret name according to the following rules, specified by {@link CreateSecretRequest}:
* The secret name must be ASCII letters, digits, or the following characters : /_+=.@-
* Don't end your secret name with a hyphen followed by six characters.
*/
@Override
public final void validateName(String name){
validateNameStatic(name);
}
public static final void validateNameStatic(String name){
if(name == null || name.length() == 0){
throw new RuntimeException("validation failed name=" + name);
}
boolean allCharactersAllowed = name.toLowerCase().chars()
.allMatch(character -> {
//numbers
if(character > 47 && character < 58){
return true;
}
//lower case letters
if(character > 96 && character < 123){
return true;
}
if(character == '/'
|| character == '_'
|| character == '+'
|| character == '='
|| character == '.'
|| character == '@'
|| character == '-'){
return true;
}
return false;
});
if(!allCharactersAllowed || name.length() > 6 && name.charAt(name.length() - 7) == '-'){
throw new RuntimeException("validation failed name=" + name);
}
}
}
|
hotpads/datarouter
|
datarouter-aws-secrets-manager/src/main/java/io/datarouter/aws/secretsmanager/AwsSecretClient.java
|
Java
|
apache-2.0
| 6,382
|
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "google/apis/accesscontextmanager_v1beta"
|
googleapis/google-api-ruby-client
|
generated/google-apis-accesscontextmanager_v1beta/lib/google-apis-accesscontextmanager_v1beta.rb
|
Ruby
|
apache-2.0
| 626
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AccessToken.cs" company="DigitalGlobe">
// Copyright 2015 DigitalGlobe
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <summary>
// The access token.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
// ReSharper disable InconsistentNaming
namespace NetworkConnections
{
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// The access token.
/// </summary>
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Reviewed.")]
public class AccessToken
{
/// <summary>
/// Gets or sets the access token.
/// </summary>
public string access_token { get; set; }
/// <summary>
/// Gets or sets the token type.
/// </summary>
public string token_type { get; set; }
/// <summary>
/// Gets or sets the refresh token.
/// </summary>
public string refresh_token { get; set; }
/// <summary>
/// Gets or sets the expires in.
/// </summary>
public int expires_in { get; set; }
/// <summary>
/// Gets or sets the scope.
/// </summary>
public string scope { get; set; }
}
}
|
DigitalGlobe/DGConnect-ESRI
|
NetworkConnections/AccessToken.cs
|
C#
|
apache-2.0
| 2,033
|
#!/usr/bin/env python
"""
Rules
for *.py files
* if the changed file is __init__.py, and there is a side-band test/ dir, then test the entire test/functional directory
the reason for this is that the init files are usually organizing collections
and those can affect many different apis if they break
* if the filename is test_*.py then include it
* if the filename is *.py, then check to see if it has an associated test_FILENAME file
and if so, include it in the test
* summarize all of the above so that a test_FILENAME that is a subpath of the first bullet
is not tested twice
for non-*.py files
* if the file is in a test/functional directory, test the whole directory
"""
import subprocess
import os
import shutil
import argparse
def cleanup_tox_directory():
if os.path.exists('.tox'):
shutil.rmtree('.tox')
def examine_python_rules(line):
fname, fext = os.path.splitext(line)
filename = os.path.basename(line)
dirname = os.path.dirname(line)
test_filename = 'test_' + filename
functional_test_file = '{0}/test/functional/{1}'.format(dirname, test_filename)
functional_test_dir = '{0}/test/functional/'.format(dirname)
if filename == '__init__.py' and os.path.exists(functional_test_dir):
return functional_test_dir
elif filename.startswith('test_') and filename.endswith('.py'):
return line
elif fext == '.py' and os.path.exists(functional_test_file):
return functional_test_file
elif 'test/functional' in line and filename == '__init__.py':
print(" * Skipping {0} because it is not a test file".format(line))
elif filename == '__init__.py' and not os.path.exists(functional_test_dir):
print(" * {0} does not have a side-band test directory!".format(line))
else:
print(" * {0} did not match any rules!".format(line))
def examine_non_python_rules(line):
if 'test/functional' in line:
return os.path.dirname(line)
def determine_files_to_test(product, commit):
results = []
build_all = [
'setup.py', 'f5/bigip/contexts.py', 'f5/bigip/mixins.py',
'f5/bigip/resource.py', 'f5sdk_plugins/fixtures.py',
'f5/bigip/__init__.py'
]
output_file = "pytest.{0}.jenkins.txt".format(product)
p1 = subprocess.Popen(
['git', '--no-pager', 'diff', '--name-only', 'origin/development', commit],
stdout=subprocess.PIPE,
)
p2 = subprocess.Popen(
['egrep', '-v', '(^requirements\.|^setup.py)'],
stdin=p1.stdout,
stdout=subprocess.PIPE,
)
p3 = subprocess.Popen(
['egrep', '(^f5\/{0}\/)'.format(product)],
stdin=p2.stdout,
stdout=subprocess.PIPE,
)
out, err = p3.communicate()
out = out.splitlines()
out = filter(None, out)
if not out:
return
for line in out:
fname, fext = os.path.splitext(line)
if not os.path.exists(line):
print "{0} was not found. Maybe this is a rename?".format(line)
continue
if line in build_all:
cleanup_tox_directory()
results.append('f5/{0}'.format(product))
elif fext == '.py':
result = examine_python_rules(line)
if result:
results.append(result)
else:
result = examine_non_python_rules(line)
if result:
results.append(result)
if results:
results = set(results)
results = compress_testable_files(results)
fh = open(output_file, 'w')
fh.writelines("%s\n" % l for l in results)
fh.close()
def compress_testable_files(files):
lines = sorted(files)
for idx, item in enumerate(lines):
file, ext = os.path.splitext(item)
if not ext and not file.endswith('/'):
item += '/'
tmp = [x for x in lines if item in x and item != x]
for _ in tmp:
lines.remove(_)
return lines
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-c','--commit', help='Git commit to check', required=True)
args = parser.parse_args()
for product in ['iworkflow', 'bigip', 'bigiq']:
determine_files_to_test(product, args.commit)
|
F5Networks/f5-common-python
|
devtools/bin/create-test-list.py
|
Python
|
apache-2.0
| 4,268
|
/*
* Copyright (C) 2012-2014 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _GAZEBO_SONAR_PLUGIN_HH_
#define _GAZEBO_SONAR_PLUGIN_HH_
#include "gazebo/common/Plugin.hh"
#include "gazebo/sensors/SensorTypes.hh"
#include "gazebo/sensors/SonarSensor.hh"
#include "gazebo/gazebo.hh"
namespace gazebo
{
/// \brief A sonar sensor plugin
class SonarPlugin : public SensorPlugin
{
/// \brief Constructor
public: SonarPlugin();
/// \brief Destructor
public: virtual ~SonarPlugin();
/// \brief Load the plugin
/// \param[in] _parent Pointer to the parent sensor.
/// \param[in] _sdf SDF element for the plugin.
public: void Load(sensors::SensorPtr _parent, sdf::ElementPtr _sdf);
/// \brief Update callback. Overload this function in a child class.
/// \param[in] _msg The sonar ping message.
protected: virtual void OnUpdate(msgs::SonarStamped _msg);
/// \brief The parent sensor
protected: sensors::SonarSensorPtr parentSensor;
/// \brief The connection tied to SonarSensor's update event
private: event::ConnectionPtr connection;
};
}
#endif
|
jonbinney/gazebo_ros_wrapper
|
plugins/SonarPlugin.hh
|
C++
|
apache-2.0
| 1,669
|
package com.icooding.cms.service;
import java.util.List;
import com.icooding.cms.model.Forum;
public interface ForumService {
/**
* 搜索根节点
* @return
*/
public List<Forum> searchRoot();
public void save(Forum forum);
public Forum update(Forum forum);
public void delete(Forum forum);
public Forum find(int id);
/**
* 检查版块名称是否存在
* @param forumName
* @return
*/
public boolean checkForumName(String forumName);
/**
* 搜索所有子节点
* @return
*/
public List<Forum> searchChildPoint();
public List<Forum> findAll();
}
|
jaguar-zc/icooding
|
icooding-cms/icooding-blog/src/main/java/com/icooding/cms/service/ForumService.java
|
Java
|
apache-2.0
| 598
|
/**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.core;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.opengamma.util.test.AbstractFudgeBuilderTestCase;
import com.opengamma.util.test.TestGroup;
/**
* Unit tests for {@link MappingsFudgeBuilder}.
*/
@Test(groups = TestGroup.UNIT)
public class MappingsFudgeBuilderTest extends AbstractFudgeBuilderTestCase {
/**
* Tests an encoding/decoding cycle.
*/
@Test
public void roundTrip() {
final Mappings mappings = new Mappings(ImmutableMap.of("foo", "bar", "baz", "boz"));
assertEncodeDecodeCycle(Mappings.class, mappings);
}
}
|
McLeodMoores/starling
|
projects/core/src/test/java/com/opengamma/core/MappingsFudgeBuilderTest.java
|
Java
|
apache-2.0
| 757
|
package bowtie.core.internal;
import bowtie.core.Result;
import bowtie.core.internal.util.MergedIterable;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* User: dan
* Date: 1/27/14
* Time: 9:02 PM
* To change this template use File | Settings | File Templates.
*/
public class FSTable {
private final Conf conf;
private final String tableName;
Index index;
private final DataFileReader dataFileReader;
public FSTable(final Conf conf, final String tableName, final Index index, final DataFileReader dataFileReader) {
this.conf = conf;
this.tableName = tableName;
this.index = index;
this.dataFileReader = dataFileReader;
}
public Iterable<Result> scan(final byte[] inclStart, final byte[] exclStop) throws IOException {
final List<Iterable<Result>> possibleHitIterables = new ArrayList<Iterable<Result>>();
for (final Index.Entry possibleHit : index.getFilesPossiblyContainingKeyRange(inclStart, exclStop)) {
possibleHitIterables.add(dataFileReader.scanInFile(inclStart, exclStop, possibleHit));
}
return new MergedIterable<Result>(ResultImpl.KEY_BASED_RESULT_COMPARATOR, possibleHitIterables);
}
public Result get(final byte[] key) throws IOException {
final Iterator<Result> scanHits = scan(key, null).iterator();
return scanHits.hasNext()
? scanHits.next()
: new ResultImpl(key, null, ResultImpl.LATEST_FS_TIMESTAMP);
}
public void close() throws IOException {
index.close();
}
public void compactMinor() throws IOException {
index.compactMinor();
deletedUnindexedDataFiles();
}
public void compactMajor() throws IOException {
final List<Index.Entry> compactedEntries = index.compact(index.getAllEntries());
index.rewriteIndexFile(compactedEntries);
index = Index.forFile(conf, tableName, index.getFilePath());
deletedUnindexedDataFiles();
}
private void deletedUnindexedDataFiles() throws IOException {
final Set<String> fileNames = new HashSet<String>();
for (final Index.Entry indexEntry : index.getAllEntries()) {
fileNames.add(indexEntry.getFileName());
}
for (final File dataFile : new File(conf.getDataDir(tableName)).listFiles()) {
if (!fileNames.contains(dataFile.getName())) {
FileUtils.forceDelete(dataFile);
}
}
}
}
|
dbaneman/bowtie
|
src/main/java/bowtie/core/internal/FSTable.java
|
Java
|
apache-2.0
| 2,586
|
// Copyright (c) 2021 Tigera, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package resources
import (
log "github.com/sirupsen/logrus"
libapiv3 "github.com/projectcalico/calico/libcalico-go/lib/apis/v3"
cnet "github.com/projectcalico/calico/libcalico-go/lib/net"
)
// FindNodeAddress returns node address of the specified type. Type can be one of
// CalicoNodeIP, InternalIP or ExternalIP
func FindNodeAddress(node *libapiv3.Node, ipType string) (*cnet.IP, *cnet.IPNet) {
for _, addr := range node.Spec.Addresses {
if addr.Type == ipType {
ip, cidr, err := cnet.ParseCIDROrIP(addr.Address)
if err == nil {
if ip.To4() == nil {
continue
}
log.WithFields(log.Fields{"ip": ip, "cidr": cidr}).Debug("Parsed IPv4 address")
return ip, cidr
} else {
log.WithError(err).WithField("IPv4Address", addr.Address).Warn("Failed to parse IPv4Address")
}
}
}
return nil, nil
}
|
projectcalico/calico
|
libcalico-go/lib/resources/node.go
|
GO
|
apache-2.0
| 1,449
|
/*
* -\-\-
* Spotify Apollo Slack Module
* --
* Copyright (C) 2013 - 2015 Spotify AB
* --
* 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.spotify.apollo.slack;
import java.io.Closeable;
public interface Slack extends Closeable {
/**
* Post a message to slack.
* @param message the message to post.
* @return {@code true} if the message was posted successfully.
*/
boolean post(String message);
}
|
rouzwawi/apollo
|
modules/slack/src/main/java/com/spotify/apollo/slack/Slack.java
|
Java
|
apache-2.0
| 956
|
//
// Copyright 2010-2017 Deveel
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
namespace Deveel.Data.Sql.Methods {
public sealed class IterateContext : Context {
internal IterateContext(MethodContext parent, long offset, SqlObject accumulation, SqlObject current)
: base(parent, $"Iterate({offset})") {
Result = Accumulation = accumulation;
Offset = offset;
Current = current;
}
public MethodContext MethodContext => (MethodContext) ParentContext;
public long Offset { get; }
public SqlObject Accumulation { get; }
public SqlObject Current { get; }
public bool IsFirst => Accumulation == null;
internal SqlObject Result { get; private set; }
internal bool Iterate { get; private set; } = true;
public void SetResult(SqlObject value, bool iterate = true) {
Result = value;
Iterate = iterate;
}
}
}
|
deveel/deveeldb.core
|
src/DeveelDb.Core/Data/Sql/Methods/IterateContext.cs
|
C#
|
apache-2.0
| 1,413
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<title>Uses of Class org.jsimpledb.cli.cmd.AbstractKVCommand (Java Class Library API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.jsimpledb.cli.cmd.AbstractKVCommand (Java Class Library API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/jsimpledb/cli/cmd/AbstractKVCommand.html" title="class in org.jsimpledb.cli.cmd">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/jsimpledb/cli/cmd/class-use/AbstractKVCommand.html" target="_top">Frames</a></li>
<li><a href="AbstractKVCommand.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.jsimpledb.cli.cmd.AbstractKVCommand" class="title">Uses of Class<br>org.jsimpledb.cli.cmd.AbstractKVCommand</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/jsimpledb/cli/cmd/AbstractKVCommand.html" title="class in org.jsimpledb.cli.cmd">AbstractKVCommand</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.jsimpledb.cli.cmd">org.jsimpledb.cli.cmd</a></td>
<td class="colLast">
<div class="block">JSimpleDB CLI <a href="../../../../../org/jsimpledb/cli/cmd/Command.html" title="annotation in org.jsimpledb.cli.cmd"><code>Command</code></a> related classes, including pre-defined commands.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.jsimpledb.cli.cmd">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/jsimpledb/cli/cmd/AbstractKVCommand.html" title="class in org.jsimpledb.cli.cmd">AbstractKVCommand</a> in <a href="../../../../../org/jsimpledb/cli/cmd/package-summary.html">org.jsimpledb.cli.cmd</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../org/jsimpledb/cli/cmd/AbstractKVCommand.html" title="class in org.jsimpledb.cli.cmd">AbstractKVCommand</a> in <a href="../../../../../org/jsimpledb/cli/cmd/package-summary.html">org.jsimpledb.cli.cmd</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../org/jsimpledb/cli/cmd/KVGetCommand.html" title="class in org.jsimpledb.cli.cmd">KVGetCommand</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../org/jsimpledb/cli/cmd/KVLoadCommand.html" title="class in org.jsimpledb.cli.cmd">KVLoadCommand</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../org/jsimpledb/cli/cmd/KVPutCommand.html" title="class in org.jsimpledb.cli.cmd">KVPutCommand</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../org/jsimpledb/cli/cmd/KVRemoveCommand.html" title="class in org.jsimpledb.cli.cmd">KVRemoveCommand</a></strong></code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/jsimpledb/cli/cmd/AbstractKVCommand.html" title="class in org.jsimpledb.cli.cmd">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/jsimpledb/cli/cmd/class-use/AbstractKVCommand.html" target="_top">Frames</a></li>
<li><a href="AbstractKVCommand.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
tempbottle/jsimpledb
|
publish/reports/javadoc/org/jsimpledb/cli/cmd/class-use/AbstractKVCommand.html
|
HTML
|
apache-2.0
| 6,907
|
# draerika1
|
ricaoandre/draerika1
|
README.md
|
Markdown
|
apache-2.0
| 12
|
package de.kauz.starcitizen.informer.model;
import android.graphics.Bitmap;
/**
* An RSS item containing a title, link and imageUrl.
*
* @author MadKauz
*
*/
public class RssItem {
private String title;
private String link;
private String imgUrl;
private Bitmap img;
private String description;
private boolean isAlreadyDownloading = false;
/**
* A new RSS item which consists of a title, outgoing link and image url.
* @param title
* @param link
* @param imgUrl
*/
public RssItem(String title, String link, String imgUrl) {
this.title = title;
this.link = link;
this.imgUrl = imgUrl;
}
/**
*
* @return
*/
public String getTitle() {
return this.title;
}
/**
*
* @return
*/
public String getLink() {
return this.link;
}
/**
*
* @return
*/
public String getImgUrl() {
return this.imgUrl;
}
/**
*
* @return
*/
public Bitmap getImg() {
return this.img;
}
/**
*
* @param imgUrl
*/
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
/**
*
* @param result
*/
public void setImg(Bitmap result) {
this.img = result;
}
/**
* @return the isAlreadyDownloading
*/
public boolean isAlreadyDownloading() {
return isAlreadyDownloading;
}
/**
* @param isAlreadyDownloading
* the isAlreadyDownloading to set
*/
public void setAlreadyDownloading(boolean isAlreadyDownloading) {
this.isAlreadyDownloading = isAlreadyDownloading;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
MadKauz/starcitizeninfoclient
|
starCitizenInformer/src/main/java/de/kauz/starcitizen/informer/model/RssItem.java
|
Java
|
apache-2.0
| 1,622
|
const path = require('path');
const express = require('express');
const open = require('open');
const serveIndex = require('serve-index');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const product = process.argv[2];
var dirname = product === 'openlayers' ? 'ol' : product
const app = (module.exports = express());
if (product) {
const config = require(`./webpack.config.${product}.js`);
const configBase = require(`./webpack.config.base.js`);
const entry = [`./src/${product}/${product === 'openlayers' ? 'namespace.js' : 'index.js'}`];
const filename = `iclient-${dirname}`;
config.output.filename = `${filename}-es6.min.js`;
config.output.path = path.resolve(`${__dirname}/../dist/${dirname}`);
if (['leaflet', 'openlayers'].includes(product)) {
entry.push(`./src/${product}/css/index.js`);
config.plugins = configBase.plugins(product, `${filename}.min`);
}
config.mode = 'development';
config.entry = entry;
config.devtool = 'inline-cheap-module-source-map';
const compiler = webpack(config);
const instance = webpackDevMiddleware(compiler, {
publicPath: `/dist/${dirname}`,
stats: {
colors: true
}
});
app.use(instance);
instance.waitUntilValid(() => {
open(`http://localhost:8082/examples/${product}`);
});
}
const server = app.listen(8082, () => {
const host = server.address().address;
const port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
app.use(express.static('web'));
app.use('/examples/template/header.html', express.static('web/template/header.html'));
app.use('/examples', express.static('examples'), serveIndex('examples'));
app.use('/examples-bug', express.static('examples-bug'), serveIndex('examples-bug'));
app.use('/dist', express.static('dist'), serveIndex('dist'));
app.use('/build', express.static('build'), serveIndex('build'));
app.use('/docs', express.static('docs'), serveIndex('docs'));
app.use('/web', express.static('web'), serveIndex('web'));
app.use('/en/examples/template/header.html', express.static('web/en/web/template/header.html'));
app.use('/en/examples', express.static('examples'), serveIndex('examples'));
app.use('/en/docs', express.static('docs'), serveIndex('docs'));
app.use('/en/dist', express.static('dist'), serveIndex('dist'));
app.use('/en/build', express.static('build'), serveIndex('build'));
app.use('/en', express.static('web/en'), serveIndex('web/en'));
if (!product) {
open(`http://localhost:8082`);
}
|
SuperMap/iClient9
|
build/server.js
|
JavaScript
|
apache-2.0
| 2,616
|
<?php
require_once dirname(dirname(__FILE__)) . '/base/Vbout.php';
require_once dirname(dirname(__FILE__)) . '/base/VboutException.php';
class ApplicationWS extends Vbout
{
protected function init()
{
$this->api_url = '/app/';
}
public function getBusinessInfo()
{
$result = array();
try {
$business = $this->me();
if ($business != null && isset($business['data'])) {
$result = array_merge($result, $business['data']['business']);
}
} catch (VboutException $ex) {
$result = $ex->getData();
}
return $result;
}
}
|
irajab/VboutAPI
|
src/services/ApplicationWS.php
|
PHP
|
apache-2.0
| 609
|
package com.github.xdcrafts.swarm.javaz.future;
import com.github.xdcrafts.swarm.javaz.common.applicative.IApplicative;
import com.github.xdcrafts.swarm.javaz.common.monad.IMonad;
import com.github.xdcrafts.swarm.javaz.common.tuple.Tuple;
import com.github.xdcrafts.swarm.javaz.option.IOption;
import com.github.xdcrafts.swarm.javaz.trym.ITryM;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import static com.github.xdcrafts.swarm.javaz.future.FutureOps.future;
import static com.github.xdcrafts.swarm.javaz.option.OptionOps.none;
import static com.github.xdcrafts.swarm.javaz.option.OptionOps.some;
import static com.github.xdcrafts.swarm.javaz.trym.TryMOps.fail;
import static com.github.xdcrafts.swarm.javaz.trym.TryMOps.success;
/**
* Implementation of IFuture.
* @param <T> value type
*/
@SuppressWarnings("unchecked")
public class Future<T> implements IFuture<T> {
private final Executor executor;
private final CompletableFuture<T> sourceFuture;
private final CompletableFuture<T> body;
private final AtomicReference<IOption<ITryM<T>>> result = new AtomicReference<>(none());
public Future(final Executor executor, final CompletableFuture<T> future) {
this.executor = executor;
this.sourceFuture = future;
this.body = future.whenComplete((r, t) -> {
if (r != null) {
result.set(some(success(r)));
} else if (t != null) {
Throwable cause = t;
while (cause.getCause() != null) {
cause = cause.getCause();
}
result.set(some(fail(cause)));
}
});
}
@Override
public boolean complete(T value) {
return complete(success(value));
}
@Override
public boolean complete(Throwable t) {
return complete(fail(t));
}
@Override
public boolean complete(ITryM<T> t) {
return t.isSuccess()
? this.sourceFuture.complete(t.value()) : this.sourceFuture.completeExceptionally(t.throwable());
}
@Override
public void onSuccess(Consumer<T> onSuccess) {
this.body.whenCompleteAsync((r, t) ->
this.result.get().foreach((tryM) -> tryM.foreach(onSuccess))
);
}
@Override
public void onFailure(Consumer<Throwable> onFailure) {
this.body.whenCompleteAsync((r, t) ->
this.result.get().foreach((tryM) -> tryM.foreachFailure(onFailure))
);
}
@Override
public void onComplete(Consumer<ITryM<T>> onComplete) {
this.body.whenCompleteAsync((r, t) -> onComplete.accept(result.get().get()));
}
@Override
public boolean isCompleted() {
return this.body.isDone();
}
@Override
public IFuture<T> recover(Function<Throwable, T> recover) {
return future(this.executor, this.body.exceptionally(recover::apply));
}
@Override
public IFuture<T> recoverWith(Function<Throwable, IFuture<T>> recover) {
final Future<T> future = future(this.executor);
onFailure((t) -> recover.apply(t).onComplete(future::complete));
onSuccess(future::complete);
return future;
}
@Override
public IOption<ITryM<T>> value() {
return this.result.get();
}
@Override
public ITryM<T> get() {
try {
this.body.get();
return this.result.get().get();
} catch (Throwable e) {
if (this.body.isCompletedExceptionally()) {
return this.result.get().get();
} else {
return fail(e);
}
}
}
@Override
public ITryM<T> get(long timeout, TimeUnit timeUnit) {
try {
this.body.get(timeout, timeUnit);
return this.result.get().get();
} catch (Throwable e) {
if (this.body.isCompletedExceptionally()) {
return this.result.get().get();
} else {
return fail(e);
}
}
}
@Override
public <U> IFuture<Tuple<T, U>> zip(IFuture<U> another) {
return flatMap((t) -> another.map((u) -> Tuple.t(t, u)));
}
@Override
public <U, MM extends IMonad<U, IFuture<?>>> Future<U> flatMap(Function<T, MM> function) {
final Future<U> future = future(this.executor);
final Function<T, Future<U>> toApply = (Function<T, Future<U>>) function;
onComplete((tryM) -> {
if (tryM.isSuccess()) {
toApply.apply(tryM.value()).onComplete(future::complete);
} else {
future.complete(tryM.throwable());
}
});
return future;
}
@Override
public <U, MM extends IApplicative<Function<T, U>, IFuture<?>>> IFuture<U> applicativeMap(MM applicativeFunction) {
final IFuture<Function<T, U>> applicative = (Future<Function<T, U>>) applicativeFunction;
final IFuture<U> future = future(this.executor);
applicative.onComplete((tryM) -> {
if (tryM.isSuccess()) {
onComplete((iTryM) -> {
if (iTryM.isSuccess()) {
future.complete(tryM.value().apply(iTryM.value()));
} else {
future.complete(iTryM.throwable());
}
});
} else {
future.complete(tryM.throwable());
}
});
return future;
}
@Override
public <U> IFuture<U> map(Function<T, U> function) {
return future(this.executor, this.body.handleAsync((r, t) -> {
if (r != null) {
return function.apply(r);
} else if (t.getClass().equals(CompletionException.class)) {
throw (CompletionException) t;
} else {
throw new RuntimeException(t);
}
}));
}
@Override
public CompletableFuture<T> toCompletableFuture() {
return this.body;
}
}
|
xdcrafts/swarm
|
src/main/java/com/github/xdcrafts/swarm/javaz/future/Future.java
|
Java
|
apache-2.0
| 6,432
|
/**
*
*/
package com.trc.process;
import java.util.List;
/**
* @author Ramesh Thalathoty
*
*/
public class Table {
private String name;
private String className;
private List<String> primaryColumns;
public String getClassName() {
return className;
}
public List<String> getPrimaryColumns() {
return primaryColumns;
}
public void setPrimaryColumns(List<String> primaryColumns) {
this.primaryColumns = primaryColumns;
}
private List<Column> columns;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
setClassName();
}
public List<Column> getColumns() {
return columns;
}
public void setColumns(List<Column> columns) {
this.columns = columns;
}
private void setClassName() {
StringBuilder sbCharacter = new StringBuilder();
char c = name.charAt(0);
sbCharacter.append(new Character(c).toString().toUpperCase().charAt(0));
className = name.toLowerCase();
for (int i = 1; i < className.length(); i++) {
char c1 = className.charAt(i);
if (i >= 1 && className.charAt(i - 1) == '_') {
c1 = new Character(c1).toString().toUpperCase().charAt(0);
}
sbCharacter.append(c1);
}
className = sbCharacter.toString().replace("_", "");
}
}
|
trcdutt/DAOAutomation
|
src/main/java/com/trc/process/Table.java
|
Java
|
apache-2.0
| 1,303
|
__author__ = 'thauser'
from argh import arg
import logging
from pnc_cli import utils
from pnc_cli.swagger_client.apis import BuildconfigurationsetsApi
from pnc_cli.swagger_client.apis import BuildconfigsetrecordsApi
sets_api = BuildconfigurationsetsApi(utils.get_api_client())
bcsr_api = BuildconfigsetrecordsApi(utils.get_api_client())
@arg("-p", "--page-size", help="Limit the amount of build records returned")
@arg("-s", "--sort", help="Sorting RSQL")
@arg("-q", help="RSQL query")
def list_build_configuration_set_records(page_size=200, sort="", q=""):
"""
List all build configuration set records.
"""
response = utils.checked_api_call(bcsr_api, 'get_all', page_size=page_size, sort=sort, q=q)
if response:
return response.content
@arg("id", help="ID of build configuration set record to retrieve.")
def get_build_configuration_set_record(id):
"""
Get a specific BuildConfigSetRecord
"""
response = utils.checked_api_call(bcsr_api, 'get_specific', id=id)
if not response:
logging.error("A BuildConfigurationSetRecord with ID {} does not exist.".format(id))
return
return response.content
@arg("id", help="ID of BuildConfigSetRecord to retrieve build records from.")
@arg("-p", "--page-size", help="Limit the amount of build records returned")
@arg("-s", "--sort", help="Sorting RSQL")
@arg("-q", help="RSQL query")
def list_records_for_build_config_set(id, page_size=200, sort="", q=""):
"""
Get a list of BuildRecords for the given BuildConfigSetRecord
"""
bcrs_check = utils.checked_api_call(sets_api, 'get_all', q="id==" + id)
if not bcrs_check:
logging.error("A BuildConfigurationSet with ID {} does not exist.".format(id))
return
response = utils.checked_api_call(bcsr_api, 'get_build_records', id=id, page_size=page_size, sort=sort, q=q)
if response:
return response.content
|
jianajavier/pnc-cli
|
pnc_cli/buildconfigsetrecords.py
|
Python
|
apache-2.0
| 1,916
|
/*
*
* * Copyright 2010-2016 OrientDB LTD (http://orientdb.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.
* *
* * For more information: http://orientdb.com
*
*/
package com.orientechnologies.orient.core.sql.operator;
import com.orientechnologies.orient.core.collate.OCollate;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.query.OQueryRuntimeValueMulti;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.record.binary.OBinaryField;
import com.orientechnologies.orient.core.serialization.serializer.record.binary.ODocumentSerializer;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterCondition;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterItemFieldAll;
/**
* Base equality operator. It's an abstract class able to compare the equality between two values.
*
* @author Luca Garulli (l.garulli--(at)--orientdb.com)
*/
public abstract class OQueryOperatorEquality extends OQueryOperator {
protected OQueryOperatorEquality(
final String iKeyword, final int iPrecedence, final boolean iLogical) {
super(iKeyword, iPrecedence, false);
}
protected OQueryOperatorEquality(
final String iKeyword,
final int iPrecedence,
final boolean iLogical,
final int iExpectedRightWords) {
super(iKeyword, iPrecedence, false, iExpectedRightWords);
}
protected OQueryOperatorEquality(
final String iKeyword,
final int iPrecedence,
final boolean iLogical,
final int iExpectedRightWords,
final boolean iExpectsParameters) {
super(iKeyword, iPrecedence, iLogical, iExpectedRightWords, iExpectsParameters);
}
protected abstract boolean evaluateExpression(
final OIdentifiable iRecord,
final OSQLFilterCondition iCondition,
final Object iLeft,
final Object iRight,
OCommandContext iContext);
public boolean evaluate(
final OBinaryField iFirstField,
final OBinaryField iSecondField,
final OCommandContext iContext,
final ODocumentSerializer serializer) {
final Object left = serializer.deserializeValue(iFirstField.bytes, iFirstField.type, null);
final Object right = serializer.deserializeValue(iSecondField.bytes, iFirstField.type, null);
return evaluateExpression(null, null, left, right, iContext);
}
@Override
public Object evaluateRecord(
final OIdentifiable iRecord,
ODocument iCurrentResult,
final OSQLFilterCondition iCondition,
final Object iLeft,
final Object iRight,
OCommandContext iContext,
final ODocumentSerializer serializer) {
if (iLeft instanceof OBinaryField && iRight instanceof OBinaryField)
// BINARY COMPARISON
return evaluate((OBinaryField) iLeft, (OBinaryField) iRight, iContext, serializer);
else if (iLeft instanceof OQueryRuntimeValueMulti) {
// LEFT = MULTI
final OQueryRuntimeValueMulti left = (OQueryRuntimeValueMulti) iLeft;
if (left.getValues().length == 0) return false;
if (left.getDefinition().getRoot().startsWith(OSQLFilterItemFieldAll.NAME)) {
// ALL VALUES
for (int i = 0; i < left.getValues().length; ++i) {
Object v = left.getValues()[i];
Object r = iRight;
final OCollate collate = left.getCollate(i);
if (collate != null) {
v = collate.transform(v);
r = collate.transform(iRight);
}
if (v == null || !evaluateExpression(iRecord, iCondition, v, r, iContext)) return false;
}
return true;
} else {
// ANY VALUES
for (int i = 0; i < left.getValues().length; ++i) {
Object v = left.getValues()[i];
Object r = iRight;
final OCollate collate = left.getCollate(i);
if (collate != null) {
v = collate.transform(v);
r = collate.transform(iRight);
}
if (v != null && evaluateExpression(iRecord, iCondition, v, r, iContext)) return true;
}
return false;
}
} else if (iRight instanceof OQueryRuntimeValueMulti) {
// RIGHT = MULTI
final OQueryRuntimeValueMulti right = (OQueryRuntimeValueMulti) iRight;
if (right.getValues().length == 0) return false;
if (right.getDefinition().getRoot().startsWith(OSQLFilterItemFieldAll.NAME)) {
// ALL VALUES
for (int i = 0; i < right.getValues().length; ++i) {
Object v = right.getValues()[i];
Object l = iLeft;
final OCollate collate = right.getCollate(i);
if (collate != null) {
v = collate.transform(v);
l = collate.transform(iLeft);
}
if (v == null || !evaluateExpression(iRecord, iCondition, l, v, iContext)) return false;
}
return true;
} else {
// ANY VALUES
for (int i = 0; i < right.getValues().length; ++i) {
Object v = right.getValues()[i];
Object l = iLeft;
final OCollate collate = right.getCollate(i);
if (collate != null) {
v = collate.transform(v);
l = collate.transform(iLeft);
}
if (v != null && evaluateExpression(iRecord, iCondition, l, v, iContext)) return true;
}
return false;
}
} else {
// SINGLE SIMPLE ITEM
return evaluateExpression(iRecord, iCondition, iLeft, iRight, iContext);
}
}
}
|
orientechnologies/orientdb
|
core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorEquality.java
|
Java
|
apache-2.0
| 6,169
|
use ::Disruption;
use rustc_serialize::{Encodable};
use rustc_serialize::json::{self};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use time::PreciseTime;
use hyper::Client;
pub fn disruption_to_usize(d: &Option<&(Disruption, usize)>) -> usize {
match *d {
None => 0,
Some(&(Disruption::Node(_), _)) => 1,
Some(&(Disruption::Query(_), _)) => 2,
Some(&(Disruption::Metric(_), _)) => 3
}
}
pub fn send_bulk<T: Encodable>(url: &str, client: &Arc<Client>, bulk: Vec<T>) {
::ACTIVE_THREADS.fetch_add(1, Ordering::SeqCst);
debug!("......");
let mut s = String::new();
let size = bulk.len();
for b in bulk {
s.push_str("{\"index\":{}}\n");
s.push_str(&json::encode(&b).unwrap());
s.push_str("\n");
}
debug!(" >>>>> Bulk: {} mb ({} elements)", s.len() / 1024 / 1024, size);
let start = PreciseTime::now();
let _ = client.post(url)
.body(&s)
.send()
.unwrap();
let end = PreciseTime::now();
let _ = PreciseTime::to(&start, end);
::ACTIVE_THREADS.fetch_sub(1, Ordering::SeqCst);
}
|
polyfractal/playground
|
hotcloud/src/util.rs
|
Rust
|
apache-2.0
| 1,189
|
# Setup Process / Steps Followed
Starting a new ActionHero project couldn't be easier. Let's start by
installing the command line tool
npm install -g actionhero
which you only need to do once. And we'll also make a folder for our
project:
mkdir thumbsvc
cd thumbsvc
actionhero generate
npm install
Now, QuickTime screen recording takes a lot of CPU and really drags
down npm install. I'm going to pause the video to let npm complete
so we don't have to sit through this.
ActionHero isn't the only library we want for our project. I also installed
sequelize for data storage, with the sqlite plugin. That will let us
develop locally without worrying about database servers, but upgrade to
MySQL or Postgres later with just a config change.
I installed GraphicsMagick to process our images, Bluebird because even
though ES6 has native Promises I still occasionally use Bluebird's
extended features, and node-request for retrieving images from remote
servers. Fair warning, this last module, find-remove, is synchronous-only
and not actively maintained by its author. I'm using it to save time
in this video, but would not recommend it for a production service.
npm install --save actionhero sequelize sqlite3 gm bluebird request find-remove
npm install --save-dev chai dirty-chai
Finally, I also intalled chai and dirty chai, in dev-only, for unit testing.
This video will target Node 7.x and higher, which supports ecmascript 6.
However, ActionHero itself officially supports Node versions back to 4.x,
so you can absolutely use an older version if you prefer.
I've taken the time to set up my IDE for this project, so let's take a
look at its structure. As you can see, `actionhero generate` gave us
everything we need to get started, but only five of these folders are
really critical right now:
actions are where we put our API call handlers
config is where we adjust our server settings
initializers is for our middleware, such as our database and image processing code
tasks is where we'll put our scheduled cache cleanup code
and finally tests is obviously where our tests go.
We want to start by stubbing out our API, and we could do this manually
in the actions folder. But ActionHero also lets us generate these from
the command line, so we could do it this way as well:
actionhero generate action --name=createVariant
actionhero generate action --name=apiKey
actionhero generate action --name=db
actionhero generate action --name=image
actionhero generate action --name=tracking
So far so good.
actionhero generate task --name=expireFiles --queue=default
actionhero generate initializer --name=apiKey
actionhero generate initializer --name=db
actionhero generate initializer --name=image
actionhero generate initializer --name=tracking
There are a few more useful commands we can run as well:
actionhero actions list
actionhero console
actionhero tasks enqueue --name=XYZ --args=JSONARGS
|
crrobinson14/sits
|
PROCESS.md
|
Markdown
|
apache-2.0
| 3,009
|
package com.example.quentin.expensemanager.Realm;
import android.content.Context;
import android.content.SharedPreferences;
import com.example.quentin.expensemanager.CurrencyConverter.CurrencyConverter;
import com.example.quentin.expensemanager.R;
import java.util.Date;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmQuery;
import io.realm.RealmResults;
/**
* Created by Quentin on 2016-09-26.
*/
public class RealmHelper {
private Realm mRealm;
private Context mContext;
private int transactionID;
public RealmHelper(Context context){
mContext = context;
SharedPreferences sharedPrefs = mContext
.getSharedPreferences(mContext.getString(R.string.latest_transaction_id),mContext.MODE_PRIVATE);
transactionID = sharedPrefs.getInt(mContext.getString(R.string.latest_transaction_id),0);
InitializeRealm();
}
public void InitializeRealm(){
RealmConfiguration config = new RealmConfiguration.Builder(mContext)
.name(mContext.getString(R.string.realm_name))
.build();
mRealm = Realm.getInstance(config);
}
public void AddAccount(String name){
mRealm.beginTransaction();
mRealm.copyToRealmOrUpdate(new Account(name));
mRealm.commitTransaction();
}
public void AddTransaction(String account, String note,String currency, double amount,Date date){
RealmQuery<Account> query = mRealm.where(Account.class);
query.equalTo(mContext.getString(R.string.account_field_name),account);
RealmResults<Account> result = query.findAll();
mRealm.beginTransaction();
Transaction transaction = mRealm.copyToRealmOrUpdate(new Transaction(transactionID,currency,note,amount,date,account));
result.first().getTransactions().add(transaction);
result.first().setBalance(result.first().getBalance()+amount);
if (amount > 0) {
result.first().setOutgoing(result.first().getOutgoing() + amount);
}
else{
result.first().setIncoming(result.first().getIncoming() + amount);
}
mRealm.commitTransaction();
transactionID++;
SharedPreferences sharedPrefs = mContext
.getSharedPreferences(mContext.getString(R.string.latest_transaction_id),mContext.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt(mContext.getString(R.string.latest_transaction_id),transactionID);
editor.apply();
}
public Account GetAccount(String account){
RealmQuery<Account> query = mRealm.where(Account.class);
query.equalTo(mContext.getString(R.string.account_field_name),account);
RealmResults<Account> result = query.findAll();
return result.first();
}
public void DeleteAccount(String account){
RealmQuery<Account> query = mRealm.where(Account.class);
query.equalTo(mContext.getString(R.string.account_field_name),account);
RealmResults<Account> result = query.findAll();
mRealm.beginTransaction();
result.first().deleteFromRealm();
mRealm.commitTransaction();
}
public void DeleteTransaction(int id){
mRealm.beginTransaction();
RealmQuery<Transaction> query = mRealm.where(Transaction.class);
RealmResults<Transaction> result = query.findAll();
RealmQuery<Account> accountQuery = mRealm.where(Account.class);
accountQuery.equalTo(mContext.getString(R.string.account_field_name),result.first().getAccountName());
RealmResults<Account> accountResult = accountQuery.findAll();
int length = accountResult.first().getTransactions().size();
for (int x = 0;x<length;x++){
if (accountResult.first().getTransactions().get(x).getId() == id){
mRealm.beginTransaction();
accountResult.first().getTransactions().remove(x);
mRealm.commitTransaction();
break;
}
}
result.first().deleteFromRealm();
mRealm.commitTransaction();
}
}
|
quencheu96/Expense-Manager
|
ExpenseManager/app/src/main/java/com/example/quentin/expensemanager/Realm/RealmHelper.java
|
Java
|
apache-2.0
| 4,164
|
#include "NFCMasterNet_HttpJsonModule.h"
#include "NFComm/NFMessageDefine/NFProtocolDefine.hpp"
#if NF_PLATFORM == NF_PLATFORM_WIN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <io.h>
#include <fcntl.h>
#ifndef S_ISDIR
#define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR)
#endif
#else
#include <sys/stat.h>
#include <sys/socket.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#endif
bool NFCMasterNet_HttpJsonModule::Init()
{
m_pHttpNetModule = new NFIHttpServerModule(pPluginManager);
return true;
}
bool NFCMasterNet_HttpJsonModule::Shut()
{
delete m_pHttpNetModule;
m_pHttpNetModule = nullptr;
return true;
}
bool NFCMasterNet_HttpJsonModule::AfterInit()
{
m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();
m_pMasterServerModule = pPluginManager->FindModule<NFIMasterNet_ServerModule>();
m_pLogicClassModule = pPluginManager->FindModule<NFIClassModule>();
m_pElementModule = pPluginManager->FindModule<NFIElementModule>();
m_pHttpNetModule->AddReceiveCallBack("json", this, &NFCMasterNet_HttpJsonModule::OnCommandQuery);
m_pHttpNetModule->AddNetCommonReceiveCallBack(this, &NFCMasterNet_HttpJsonModule::OnCommonQuery);
int nJsonPort = 80;
int nWebServerAppID = 0;
NF_SHARE_PTR<NFIClass> xLogicClass = m_pLogicClassModule->GetElement(NFrame::HttpServer::ThisName());
if (xLogicClass)
{
NFList<std::string>& strIdList = xLogicClass->GetIdList();
std::string strId;
for (bool bRet = strIdList.First(strId); bRet; bRet = strIdList.Next(strId))
{
nJsonPort = m_pElementModule->GetPropertyInt(strId, NFrame::HttpServer::WebPort());
nWebServerAppID = m_pElementModule->GetPropertyInt(strId, NFrame::HttpServer::ServerID());
m_strWebRootPath = m_pElementModule->GetPropertyString(strId, NFrame::HttpServer::WebRootPath());
}
}
//webserver only run one instance for NF
if (pPluginManager->GetAppID() != nWebServerAppID)
{
return true;
}
m_pHttpNetModule->InitServer(nJsonPort);
return true;
}
bool NFCMasterNet_HttpJsonModule::Execute()
{
m_pHttpNetModule->Execute();
return true;
}
void NFCMasterNet_HttpJsonModule::OnCommandQuery(struct evhttp_request *req, const std::string& strCommand, const std::string& strUrl)
{
std::string str = m_pMasterServerModule->GetServersStatus();
NFCHttpNet::SendMsg(req, str.c_str());
}
void NFCMasterNet_HttpJsonModule::OnCommonQuery(struct evhttp_request *req, const std::string& strCommand, const std::string& strUrl)
{
//Add response type
std::map<std::string, std::string> typeMap;
typeMap["txt"] = "text/plain";
typeMap["txt"] = "text/plain";
typeMap["c"] = "text/plain";
typeMap["h"] = "text/plain";
typeMap["html"] = "text/html";
typeMap["htm"] = "text/htm";
typeMap["css"] = "text/css";
typeMap["gif"] = "image/gif";
typeMap["jpg"] = "image/jpeg";
typeMap["jpeg"] = "image/jpeg";
typeMap["png"] = "image/png";
typeMap["pdf"] = "application/pdf";
typeMap["ps"] = "application/postsript";
std::string strPath = m_strWebRootPath;
if (strPath.find_last_of("/") != strPath.size())
{
strPath += "/";
}
strPath = strPath + strUrl;
int fd = -1;
struct stat st;
if (stat(strPath.c_str(), &st) < 0)
{
std::string errMsg = "404:" + strPath;
NFCHttpNet::SendMsg(req, errMsg.c_str());
}
if (S_ISDIR(st.st_mode))
{
strPath += "/index.html";
}
if (stat(strPath.c_str(), &st) < 0)
{
std::string errMsg = "404:" + strPath;
NFCHttpNet::SendMsg(req, errMsg.c_str());
}
#if NF_PLATFORM == NF_PLATFORM_WIN
if ((fd = open(strPath.c_str(), O_RDONLY | O_BINARY)) < 0) {
#else
if ((fd = open(strPath.c_str(), O_RDONLY)) < 0) {
#endif
NFCHttpNet::SendMsg(req, "error");
return;
}
if (fstat(fd, &st) < 0) {
NFCHttpNet::SendMsg(req, "error");
return;
}
const char* last_period = strrchr(strPath.c_str(), '.');
std::string strType = last_period + 1;
if (typeMap.find(strType) == typeMap.end())
{
strType = "application/misc";
}
else
{
strType = typeMap[strType];
}
NFCHttpNet::SendFile(req, fd, st, strType);
}
|
xinst/NoahGameFrame
|
NFServer/NFMasterNet_HttpServerPlugin/NFCMasterNet_HttpJsonModule.cpp
|
C++
|
apache-2.0
| 4,028
|
class Solution:
def maxProfit(self, prices, fee):
dp = [[-prices[0]], [0]]
for i in range(1, len(prices)):
dp[0].append(max(dp[0][i-1], dp[1][i-1]-prices[i]))
dp[1].append(max(dp[0][i-1]+prices[i]-fee, dp[1][i-1]))
return dp[1][-1]
print(Solution().maxProfit([1, 3, 2, 8, 4, 9], 2))
|
zuun77/givemegoogletshirts
|
leetcode/python/714_best-time-to-buy-and-sell-stock-with-transaction-fee.py
|
Python
|
apache-2.0
| 335
|
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use \yii\redactor\widgets\Redactor;
$this->title = 'Добавление записи';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-signup">
<?php if (Yii::$app->user->can('createPost')){ ?>
<h1><?= Html::encode($this->title) ?></h1>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['options' => ['class' => 'addContent']]); ?>
<?= $form->field($model, 'name')->label('Название') ?>
<?= $form->field($model, 'slug')->label('Путь к ссылке') ?>
<?= $form->field($model, 'text_short')->textarea()->label('Анонс')
->widget(Redactor::className())?>
<?= $form->field($model, 'text_bb')->textarea()->label('Текст новости')
->widget(Redactor::className()) ?>
<?= $form->field($model, 'status')->checkbox()->label('Опубликовать сразу') ?>
<h2>Категория</h2>
<?php
foreach($categories as $cat) {
print $cat->name;
} ?>
<div class="form-group">
<?= Html::submitButton('Добавить', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); }?>
</div>
</div>
</div>
|
askeroff/blogyii2
|
backend/views/content/add.php
|
PHP
|
apache-2.0
| 1,488
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.