text:
// 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.

// Private header, not to be exported

#pragma once

#include <utility>

#include "arrow/array.h"
#include "arrow/extension_type.h"
#include "arrow/scalar.h"
#include "arrow/status.h"
#include "arrow/type.h"
#include "arrow/util/bit_block_counter.h"
#include "arrow/util/bit_util.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/functional.h"
#include "arrow/util/string_view.h"

namespace arrow {

#define ARROW_GENERATE_FOR_ALL_INTEGER_TYPES(ACTION) \
  ACTION(Int8);                                      \
  ACTION(UInt8);                                     \
  ACTION(Int16);                                     \
  ACTION(UInt16);                                    \
  ACTION(Int32);                                     \
  ACTION(UInt32);                                    \
  ACTION(Int64);                                     \
  ACTION(UInt64)

#define ARROW_GENERATE_FOR_ALL_NUMERIC_TYPES(ACTION) \
  ARROW_GENERATE_FOR_ALL_INTEGER_TYPES(ACTION);      \
  ACTION(HalfFloat);                                 \
  ACTION(Float);                                     \
  ACTION(Double)

#define ARROW_GENERATE_FOR_ALL_TYPES(ACTION)    \
  ACTION(Null);                                 \
  ACTION(Boolean);                              \
  ARROW_GENERATE_FOR_ALL_NUMERIC_TYPES(ACTION); \
  ACTION(String);                               \
  ACTION(Binary);                               \
  ACTION(LargeString);                          \
  ACTION(LargeBinary);                          \
  ACTION(FixedSizeBinary);                      \
  ACTION(Duration);                             \
  ACTION(Date32);                               \
  ACTION(Date64);                               \
  ACTION(Timestamp);                            \
  ACTION(Time32);                               \
  ACTION(Time64);                               \
  ACTION(MonthInterval);                        \
  ACTION(DayTimeInterval);                      \
  ACTION(Decimal128);                           \
  ACTION(Decimal256);                           \
  ACTION(List);                                 \
  ACTION(LargeList);                            \
  ACTION(Map);                                  \
  ACTION(FixedSizeList);                        \
  ACTION(Struct);                               \
  ACTION(SparseUnion);                          \
  ACTION(DenseUnion);                           \
  ACTION(Dictionary);                           \
  ACTION(Extension)

#define TYPE_VISIT_INLINE(TYPE_CLASS) \
  case TYPE_CLASS##Type::type_id:     \
    return visitor->Visit(internal::checked_cast<const TYPE_CLASS##Type&>(type));

template <typename VISITOR>
inline Status VisitTypeInline(const DataType& type, VISITOR* visitor) {
  switch (type.id()) {
    ARROW_GENERATE_FOR_ALL_TYPES(TYPE_VISIT_INLINE);
    default:
      break;
  }
  return Status::NotImplemented("Type not implemented");
}

#undef TYPE_VISIT_INLINE

#define TYPE_ID_VISIT_INLINE(TYPE_CLASS)            \
  case TYPE_CLASS##Type::type_id: {                 \
    const TYPE_CLASS##Type* concrete_ptr = nullptr; \
    return visitor->Visit(concrete_ptr);            \
  }

// Calls `visitor` with a nullptr of the corresponding concrete type class
template <typename VISITOR>
inline Status VisitTypeIdInline(Type::type id, VISITOR* visitor) {
  switch (id) {
    ARROW_GENERATE_FOR_ALL_TYPES(TYPE_ID_VISIT_INLINE);
    default:
      break;
  }
  return Status::NotImplemented("Type not implemented");
}

#undef TYPE_ID_VISIT_INLINE

#define ARRAY_VISIT_INLINE(TYPE_CLASS)                                                   \
  case TYPE_CLASS##Type::type_id:                                                        \
    return visitor->Visit(                                                               \
        internal::checked_cast<const typename TypeTraits<TYPE_CLASS##Type>::ArrayType&>( \
            array));

template <typename VISITOR>
inline Status VisitArrayInline(const Array& array, VISITOR* visitor) {
  switch (array.type_id()) {
    ARROW_GENERATE_FOR_ALL_TYPES(ARRAY_VISIT_INLINE);
    default:
      break;
  }
  return Status::NotImplemented("Type not implemented");
}

namespace internal {

template <typename T, typename Enable = void>
struct ArrayDataInlineVisitor {};

// Numeric and primitive C-compatible types
template <typename T>
struct ArrayDataInlineVisitor<T, enable_if_has_c_type<T>> {
  using c_type = typename T::c_type;

  template <typename ValidFunc, typename NullFunc>
  static Status VisitStatus(const ArrayData& arr, ValidFunc&& valid_func,
                            NullFunc&& null_func) {
    const c_type* data = arr.GetValues<c_type>(1);
    auto visit_valid = [&](int64_t i) { return valid_func(data[i]); };
    return VisitBitBlocks(arr.buffers[0], arr.offset, arr.length, std::move(visit_valid),
                          std::forward<NullFunc>(null_func));
  }

  template <typename ValidFunc, typename NullFunc>
  static void VisitVoid(const ArrayData& arr, ValidFunc&& valid_func,
                        NullFunc&& null_func) {
    using c_type = typename T::c_type;
    const c_type* data = arr.GetValues<c_type>(1);
    auto visit_valid = [&](int64_t i) { valid_func(data[i]); };
    VisitBitBlocksVoid(arr.buffers[0], arr.offset, arr.length, std::move(visit_valid),
                       std::forward<NullFunc>(null_func));
  }
};

// Boolean
template <>
struct ArrayDataInlineVisitor<BooleanType> {
  using c_type = bool;

  template <typename ValidFunc, typename NullFunc>
  static Status VisitStatus(const ArrayData& arr, ValidFunc&& valid_func,
                            NullFunc&& null_func) {
    int64_t offset = arr.offset;
    const uint8_t* data = arr.buffers[1]->data();
    return VisitBitBlocks(
        arr.buffers[0], offset, arr.length,
        [&](int64_t i) { return valid_func(BitUtil::GetBit(data, offset + i)); },
        std::forward<NullFunc>(null_func));
  }

  template <typename ValidFunc, typename NullFunc>
  static void VisitVoid(const ArrayData& arr, ValidFunc&& valid_func,
                        NullFunc&& null_func) {
    int64_t offset = arr.offset;
    const uint8_t* data = arr.buffers[1]->data();
    VisitBitBlocksVoid(
        arr.buffers[0], offset, arr.length,
        [&](int64_t i) { valid_func(BitUtil::GetBit(data, offset + i)); },
        std::forward<NullFunc>(null_func));
  }
};

// Binary, String...
template <typename T>
struct ArrayDataInlineVisitor<T, enable_if_base_binary<T>> {
  using c_type = util::string_view;

  template <typename ValidFunc, typename NullFunc>
  static Status VisitStatus(const ArrayData& arr, ValidFunc&& valid_func,
                            NullFunc&& null_func) {
    using offset_type = typename T::offset_type;
    constexpr char empty_value = 0;

    if (arr.length == 0) {
      return Status::OK();
    }
    const offset_type* offsets = arr.GetValues<offset_type>(1);
    const char* data;
    if (!arr.buffers[2]) {
      data = &empty_value;
    } else {
      // Do not apply the array offset to the values array; the value_offsets
      // index the non-sliced values array.
      data = arr.GetValues<char>(2, /*absolute_offset=*/0);
    }
    offset_type cur_offset = *offsets++;
    return VisitBitBlocks(
        arr.buffers[0], arr.offset, arr.length,
        [&](int64_t i) {
          ARROW_UNUSED(i);
          auto value = util::string_view(data + cur_offset, *offsets - cur_offset);
          cur_offset = *offsets++;
          return valid_func(value);
        },
        [&]() {
          cur_offset = *offsets++;
          return null_func();
        });
  }

  template <typename ValidFunc, typename NullFunc>
  static void VisitVoid(const ArrayData& arr, ValidFunc&& valid_func,
                        NullFunc&& null_func) {
    using offset_type = typename T::offset_type;
    constexpr uint8_t empty_value = 0;

    if (arr.length == 0) {
      return;
    }
    const offset_type* offsets = arr.GetValues<offset_type>(1);
    const uint8_t* data;
    if (!arr.buffers[2]) {
      data = &empty_value;
    } else {
      // Do not apply the array offset to the values array; the value_offsets
      // index the non-sliced values array.
      data = arr.GetValues<uint8_t>(2, /*absolute_offset=*/0);
    }

    VisitBitBlocksVoid(
        arr.buffers[0], arr.offset, arr.length,
        [&](int64_t i) {
          auto value = util::string_view(reinterpret_cast<const char*>(data + offsets[i]),
                                         offsets[i + 1] - offsets[i]);
          valid_func(value);
        },
        std::forward<NullFunc>(null_func));
  }
};

// FixedSizeBinary, Decimal128
template <typename T>
struct ArrayDataInlineVisitor<T, enable_if_fixed_size_binary<T>> {
  using c_type = util::string_view;

  template <typename ValidFunc, typename NullFunc>
  static Status VisitStatus(const ArrayData& arr, ValidFunc&& valid_func,
                            NullFunc&& null_func) {
    const auto& fw_type = internal::checked_cast<const FixedSizeBinaryType&>(*arr.type);

    const int32_t byte_width = fw_type.byte_width();
    const char* data = arr.GetValues<char>(1,
                                           /*absolute_offset=*/arr.offset * byte_width);

    return VisitBitBlocks(
        arr.buffers[0], arr.offset, arr.length,
        [&](int64_t i) {
          auto value = util::string_view(data, byte_width);
          data += byte_width;
          return valid_func(value);
        },
        [&]() {
          data += byte_width;
          return null_func();
        });
  }

  template <typename ValidFunc, typename NullFunc>
  static void VisitVoid(const ArrayData& arr, ValidFunc&& valid_func,
                        NullFunc&& null_func) {
    const auto& fw_type = internal::checked_cast<const FixedSizeBinaryType&>(*arr.type);

    const int32_t byte_width = fw_type.byte_width();
    const char* data = arr.GetValues<char>(1,
                                           /*absolute_offset=*/arr.offset * byte_width);

    VisitBitBlocksVoid(
        arr.buffers[0], arr.offset, arr.length,
        [&](int64_t i) {
          valid_func(util::string_view(data, byte_width));
          data += byte_width;
        },
        [&]() {
          data += byte_width;
          null_func();
        });
  }
};

}  // namespace internal

// Visit an array's data values, in order, without overhead.
//
// The given `ValidFunc` should be a callable with either of these signatures:
// - void(scalar_type)
// - Status(scalar_type)
//
// The `NullFunc` should have the same return type as `ValidFunc`.
//
// ... where `scalar_type` depends on the array data type:
// - the type's `c_type`, if any
// - for boolean arrays, a `bool`
// - for binary, string and fixed-size binary arrays, a `util::string_view`

template <typename T, typename ValidFunc, typename NullFunc>
typename internal::call_traits::enable_if_return<ValidFunc, Status>::type
VisitArrayDataInline(const ArrayData& arr, ValidFunc&& valid_func, NullFunc&& null_func) {
  return internal::ArrayDataInlineVisitor<T>::VisitStatus(
      arr, std::forward<ValidFunc>(valid_func), std::forward<NullFunc>(null_func));
}

template <typename T, typename ValidFunc, typename NullFunc>
typename internal::call_traits::enable_if_return<ValidFunc, void>::type
VisitArrayDataInline(const ArrayData& arr, ValidFunc&& valid_func, NullFunc&& null_func) {
  return internal::ArrayDataInlineVisitor<T>::VisitVoid(
      arr, std::forward<ValidFunc>(valid_func), std::forward<NullFunc>(null_func));
}

// Visit an array's data values, in order, without overhead.
//
// The Visit method's `visitor` argument should be an object with two public methods:
// - Status VisitNull()
// - Status VisitValue(<scalar>)
//
// The scalar value's type depends on the array data type:
// - the type's `c_type`, if any
// - for boolean arrays, a `bool`
// - for binary, string and fixed-size binary arrays, a `util::string_view`

template <typename T>
struct ArrayDataVisitor {
  using InlineVisitorType = internal::ArrayDataInlineVisitor<T>;
  using c_type = typename InlineVisitorType::c_type;

  template <typename Visitor>
  static Status Visit(const ArrayData& arr, Visitor* visitor) {
    return InlineVisitorType::VisitStatus(
        arr, [visitor](c_type v) { return visitor->VisitValue(v); },
        [visitor]() { return visitor->VisitNull(); });
  }
};

#define SCALAR_VISIT_INLINE(TYPE_CLASS) \
  case TYPE_CLASS##Type::type_id:       \
    return visitor->Visit(internal::checked_cast<const TYPE_CLASS##Scalar&>(scalar));

template <typename VISITOR>
inline Status VisitScalarInline(const Scalar& scalar, VISITOR* visitor) {
  switch (scalar.type->id()) {
    ARROW_GENERATE_FOR_ALL_TYPES(SCALAR_VISIT_INLINE);
    default:
      break;
  }
  return Status::NotImplemented("Scalar visitor for type not implemented ",
                                scalar.type->ToString());
}

#undef TYPE_VISIT_INLINE

// Visit a null bitmap, in order, without overhead.
//
// The given `ValidFunc` should be a callable with either of these signatures:
// - void()
// - Status()
//
// The `NullFunc` should have the same return type as `ValidFunc`.

template <typename ValidFunc, typename NullFunc>
typename internal::call_traits::enable_if_return<ValidFunc, Status>::type
VisitNullBitmapInline(const uint8_t* valid_bits, int64_t valid_bits_offset,
                      int64_t num_values, int64_t null_count, ValidFunc&& valid_func,
                      NullFunc&& null_func) {
  ARROW_UNUSED(null_count);
  internal::OptionalBitBlockCounter bit_counter(valid_bits, valid_bits_offset,
                                                num_values);
  int64_t position = 0;
  int64_t offset_position = valid_bits_offset;
  while (position < num_values) {
    internal::BitBlockCount block = bit_counter.NextBlock();
    if (block.AllSet()) {
      for (int64_t i = 0; i < block.length; ++i) {
        ARROW_RETURN_NOT_OK(valid_func());
      }
    } else if (block.NoneSet()) {
      for (int64_t i = 0; i < block.length; ++i) {
        ARROW_RETURN_NOT_OK(null_func());
      }
    } else {
      for (int64_t i = 0; i < block.length; ++i) {
        ARROW_RETURN_NOT_OK(BitUtil::GetBit(valid_bits, offset_position + i)
                                ? valid_func()
                                : null_func());
      }
    }
    position += block.length;
    offset_position += block.length;
  }
  return Status::OK();
}

template <typename ValidFunc, typename NullFunc>
typename internal::call_traits::enable_if_return<ValidFunc, void>::type
VisitNullBitmapInline(const uint8_t* valid_bits, int64_t valid_bits_offset,
                      int64_t num_values, int64_t null_count, ValidFunc&& valid_func,
                      NullFunc&& null_func) {
  ARROW_UNUSED(null_count);
  internal::OptionalBitBlockCounter bit_counter(valid_bits, valid_bits_offset,
                                                num_values);
  int64_t position = 0;
  int64_t offset_position = valid_bits_offset;
  while (position < num_values) {
    internal::BitBlockCount block = bit_counter.NextBlock();
    if (block.AllSet()) {
      for (int64_t i = 0; i < block.length; ++i) {
        valid_func();
      }
    } else if (block.NoneSet()) {
      for (int64_t i = 0; i < block.length; ++i) {
        null_func();
      }
    } else {
      for (int64_t i = 0; i < block.length; ++i) {
        BitUtil::GetBit(valid_bits, offset_position + i) ? valid_func() : null_func();
      }
    }
    position += block.length;
    offset_position += block.length;
  }
}

}  // namespace arrow


text:
package pod

import (
	"fmt"
	"net"
	"net/http"
	"net/url"
	"strings"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/validation"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/fields"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/registry/generic"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util/fielderrors"
)

// podStrategy implements behavior for Pods
// TODO: move to a pod specific package.
type podStrategy struct {
	runtime.ObjectTyper
	api.NameGenerator
}

// Strategy is the default logic that applies when creating and updating Pod
// objects via the REST API.
// TODO: Create other strategies for updating status, bindings, etc
var Strategy = podStrategy{api.Scheme, api.SimpleNameGenerator}

// NamespaceScoped is true for pods.
func (podStrategy) NamespaceScoped() bool {
	return true
}

// ResetBeforeCreate clears fields that are not allowed to be set by end users on creation.
func (podStrategy) ResetBeforeCreate(obj runtime.Object) {
	pod := obj.(*api.Pod)
	pod.Status = api.PodStatus{
		Host:  pod.Spec.Host,
		Phase: api.PodPending,
	}
}

// Validate validates a new pod.
func (podStrategy) Validate(obj runtime.Object) fielderrors.ValidationErrorList {
	pod := obj.(*api.Pod)
	return validation.ValidatePod(pod)
}

// AllowCreateOnUpdate is false for pods.
func (podStrategy) AllowCreateOnUpdate() bool {
	return false
}

// ValidateUpdate is the default update validation for an end user.
func (podStrategy) ValidateUpdate(obj, old runtime.Object) fielderrors.ValidationErrorList {
	return validation.ValidatePodUpdate(obj.(*api.Pod), old.(*api.Pod))
}

// CheckGracefulDelete allows a pod to be gracefully deleted.
func (podStrategy) CheckGracefulDelete(obj runtime.Object, options *api.DeleteOptions) bool {
	return false
}

type podStatusStrategy struct {
	podStrategy
}

var StatusStrategy = podStatusStrategy{Strategy}

func (podStatusStrategy) ValidateUpdate(obj, old runtime.Object) fielderrors.ValidationErrorList {
	// TODO: merge valid fields after update
	return validation.ValidatePodStatusUpdate(obj.(*api.Pod), old.(*api.Pod))
}

// MatchPod returns a generic matcher for a given label and field selector.
func MatchPod(label labels.Selector, field fields.Selector) generic.Matcher {
	return generic.MatcherFunc(func(obj runtime.Object) (bool, error) {
		podObj, ok := obj.(*api.Pod)
		if !ok {
			return false, fmt.Errorf("not a pod")
		}
		fields := PodToSelectableFields(podObj)
		return label.Matches(labels.Set(podObj.Labels)) && field.Matches(fields), nil
	})
}

// PodToSelectableFields returns a label set that represents the object
// TODO: fields are not labels, and the validation rules for them do not apply.
func PodToSelectableFields(pod *api.Pod) labels.Set {
	return labels.Set{
		"name":         pod.Name,
		"spec.host":    pod.Spec.Host,
		"status.phase": string(pod.Status.Phase),
	}
}

// ResourceGetter is an interface for retrieving resources by ResourceLocation.
type ResourceGetter interface {
	Get(api.Context, string) (runtime.Object, error)
}

// ResourceLocation returns a URL to which one can send traffic for the specified pod.
func ResourceLocation(getter ResourceGetter, ctx api.Context, id string) (*url.URL, http.RoundTripper, error) {
	// Allow ID as "podname" or "podname:port".  If port is not specified,
	// try to use the first defined port on the pod.
	parts := strings.Split(id, ":")
	if len(parts) > 2 {
		return nil, nil, errors.NewBadRequest(fmt.Sprintf("invalid pod request %q", id))
	}
	name := parts[0]
	port := ""
	if len(parts) == 2 {
		// TODO: if port is not a number but a "(container)/(portname)", do a name lookup.
		port = parts[1]
	}

	obj, err := getter.Get(ctx, name)
	if err != nil {
		return nil, nil, err
	}
	pod := obj.(*api.Pod)
	if pod == nil {
		return nil, nil, nil
	}

	// Try to figure out a port.
	if port == "" {
		for i := range pod.Spec.Containers {
			if len(pod.Spec.Containers[i].Ports) > 0 {
				port = fmt.Sprintf("%d", pod.Spec.Containers[i].Ports[0].ContainerPort)
				break
			}
		}
	}

	// We leave off the scheme ('http://') because we have no idea what sort of server
	// is listening at this endpoint.
	loc := &url.URL{}
	if port == "" {
		loc.Host = pod.Status.PodIP
	} else {
		loc.Host = net.JoinHostPort(pod.Status.PodIP, port)
	}
	return loc, nil, nil
}

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
package cn.com.warlock.mybatis.codegen;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

public class MyBatisGeneratorTool {
    public static void main(String[] args) {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        String genCfg = "/generatorConfig.xml"; //src的一级目录下
        File configFile = new File(MyBatisGeneratorTool.class.getResource(genCfg).getFile());
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = null;
        try {
            config = cp.parseConfiguration(configFile);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XMLParserException e) {
            e.printStackTrace();
        }
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = null;
        try {
            myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        } catch (InvalidConfigurationException e) {
            e.printStackTrace();
        }
        try {
            myBatisGenerator.generate(null);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


text:
'use strict';
module.exports = function calculateStatus(counts) {
	if (!counts) {
		return 'skipped';
	}
	if (counts.error) {
		return 'error';
	} else if (counts.failure) {
		return 'failure';
	} else if (counts.success) {
		return 'success';
	}
	return 'skipped';
};


text:
package kivik

import (
	"context"
	"errors"
	"io"
	"net/http"

	"github.com/go-kivik/kivik/v3/driver"
)

// BulkResults is an iterator over the results of a BulkDocs query.
type BulkResults struct {
	*iter
	bulki driver.BulkResults
}

// Next returns the next BulkResult from the feed. If an error occurs, it will
// be returned and the feed closed. io.EOF will be returned when there are no
// more results.
func (r *BulkResults) Next() bool {
	return r.iter.Next()
}

// Err returns the error, if any, that was encountered during iteration. Err
// may be called after an explicit or implicit Close.
func (r *BulkResults) Err() error {
	return r.iter.Err()
}

// Close closes the feed. Any unread updates will still be accessible via
// Next().
func (r *BulkResults) Close() error {
	return r.iter.Close()
}

type bulkIterator struct{ driver.BulkResults }

var _ iterator = &bulkIterator{}

func (r *bulkIterator) Next(i interface{}) error {
	return r.BulkResults.Next(i.(*driver.BulkResult))
}

func newBulkResults(ctx context.Context, bulki driver.BulkResults) *BulkResults {
	return &BulkResults{
		iter:  newIterator(ctx, &bulkIterator{bulki}, &driver.BulkResult{}),
		bulki: bulki,
	}
}

// ID returns the document ID name for the current result.
func (r *BulkResults) ID() string {
	runlock, err := r.rlock()
	if err != nil {
		return ""
	}
	defer runlock()
	return r.curVal.(*driver.BulkResult).ID
}

// Rev returns the revision of the current curResult.
func (r *BulkResults) Rev() string {
	runlock, err := r.rlock()
	if err != nil {
		return ""
	}
	defer runlock()
	return r.curVal.(*driver.BulkResult).Rev
}

// UpdateErr returns the error associated with the current result, or nil
// if none. Do not confuse this with Err, which returns an error for the
// iterator itself.
func (r *BulkResults) UpdateErr() error {
	runlock, err := r.rlock()
	if err != nil {
		return nil
	}
	defer runlock()
	return r.curVal.(*driver.BulkResult).Error
}

// BulkDocs allows you to create and update multiple documents at the same time
// within a single request. This function returns an iterator over the results
// of the bulk operation.
// See http://docs.couchdb.org/en/2.0.0/api/database/bulk-api.html#db-bulk-docs
//
// As with Put, each individual document may be a JSON-marshable object, or a
// raw JSON string in a []byte, json.RawMessage, or io.Reader.
func (db *DB) BulkDocs(ctx context.Context, docs []interface{}, options ...Options) (*BulkResults, error) {
	docsi, err := docsInterfaceSlice(docs)
	if err != nil {
		return nil, err
	}
	if len(docsi) == 0 {
		return nil, &Error{HTTPStatus: http.StatusBadRequest, Err: errors.New("kivik: no documents provided")}
	}
	opts := mergeOptions(options...)
	if bulkDocer, ok := db.driverDB.(driver.BulkDocer); ok {
		bulki, err := bulkDocer.BulkDocs(ctx, docsi, opts)
		if err != nil {
			return nil, err
		}
		return newBulkResults(ctx, bulki), nil
	}
	var results []driver.BulkResult
	for _, doc := range docsi {
		var err error
		var id, rev string
		if docID, ok := extractDocID(doc); ok {
			id = docID
			rev, err = db.Put(ctx, id, doc, opts)
		} else {
			id, rev, err = db.CreateDoc(ctx, doc, opts)
		}
		results = append(results, driver.BulkResult{
			ID:    id,
			Rev:   rev,
			Error: err,
		})
	}
	return newBulkResults(ctx, &emulatedBulkResults{results}), nil
}

type emulatedBulkResults struct {
	results []driver.BulkResult
}

var _ driver.BulkResults = &emulatedBulkResults{}

func (r *emulatedBulkResults) Close() error {
	r.results = nil
	return nil
}

func (r *emulatedBulkResults) Next(res *driver.BulkResult) error {
	if len(r.results) == 0 {
		return io.EOF
	}
	*res = r.results[0]
	r.results = r.results[1:]
	return nil
}

func docsInterfaceSlice(docsi []interface{}) ([]interface{}, error) {
	for i, doc := range docsi {
		x, err := normalizeFromJSON(doc)
		if err != nil {
			return nil, &Error{HTTPStatus: http.StatusBadRequest, Err: err}
		}
		docsi[i] = x
	}
	return docsi, nil
}


text:
package com.dangdang.ddframe.job.lite.console.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.io.File;

/**
 * 用户目录工具类.
 *
 * @author zhangliang
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class HomeFolderUtils {

    private static final String USER_HOME = System.getProperty("user.home");

    private static final String FILE_SEPARATOR = System.getProperty("file.separator");

    private static final String CONSOLE_ROOT_FOLDER = ".elastic-job-console";

    /**
     * 获取用户目录文件.
     *
     * @param fileName 文件名
     * @return 用户目录所在的文件名
     */
    public static String getFilePathInHomeFolder(final String fileName) {
        return String.format("%s%s", getHomeFolder(), fileName);
    }

    /**
     * 创建用户目录.
     */
    public static void createHomeFolderIfNotExisted() {
        File file = new File(getHomeFolder());
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    private static String getHomeFolder() {
        return String.format("%s%s%s%s", USER_HOME, FILE_SEPARATOR, CONSOLE_ROOT_FOLDER, FILE_SEPARATOR);
    }
}


text:
//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
var __reflect = (this && this.__reflect) || function (p, c, t) {
    p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t;
};
var __extends = this && this.__extends || function __extends(t, e) {
 function r() {
 this.constructor = t;
}
for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]);
r.prototype = e.prototype, t.prototype = new r();
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [0, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var Main = (function (_super) {
    __extends(Main, _super);
    function Main() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Main.prototype.createChildren = function () {
        _super.prototype.createChildren.call(this);
        egret.lifecycle.addLifecycleListener(function (context) {
            // custom lifecycle plugin
        });
        egret.lifecycle.onPause = function () {
            egret.ticker.pause();
        };
        egret.lifecycle.onResume = function () {
            egret.ticker.resume();
        };
        //inject the custom material parser
        //注入自定义的素材解析器
        var assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());
        this.runGame().catch(function (e) {
            console.log(e);
        });
    };
    Main.prototype.runGame = function () {
        return __awaiter(this, void 0, void 0, function () {
            var result, userInfo;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.loadResource()];
                    case 1:
                        _a.sent();
                        this.createGameScene();
                        return [4 /*yield*/, RES.getResAsync("description_json")];
                    case 2:
                        result = _a.sent();
                        return [4 /*yield*/, platform.login()];
                    case 3:
                        _a.sent();
                        return [4 /*yield*/, platform.getUserInfo()];
                    case 4:
                        userInfo = _a.sent();
                        console.log(userInfo);
                        return [2 /*return*/];
                }
            });
        });
    };
    Main.prototype.loadResource = function () {
        return __awaiter(this, void 0, void 0, function () {
            var loadingView, e_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 4, , 5]);
                        loadingView = new LoadingUI();
                        this.stage.addChild(loadingView);
                        return [4 /*yield*/, RES.loadConfig("resource/default.res.json", "resource/")];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this.loadTheme()];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, RES.loadGroup("preload", 0, loadingView)];
                    case 3:
                        _a.sent();
                        this.stage.removeChild(loadingView);
                        return [3 /*break*/, 5];
                    case 4:
                        e_1 = _a.sent();
                        console.error(e_1);
                        return [3 /*break*/, 5];
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    Main.prototype.loadTheme = function () {
        var _this = this;
        return new Promise(function (resolve, reject) {
            // load skin theme configuration file, you can manually modify the file. And replace the default skin.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            var theme = new eui.Theme("resource/default.thm.json", _this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, function () {
                resolve();
            }, _this);
        });
    };
    /**
     * 创建场景界面
     * Create scene interface
     */
    Main.prototype.createGameScene = function () {
        var sky = this.createBitmapByName("bg_jpg");
        this.addChild(sky);
        var stageW = this.stage.stageWidth;
        var stageH = this.stage.stageHeight;
        sky.width = stageW;
        sky.height = stageH;
        var topMask = new egret.Shape();
        topMask.graphics.beginFill(0x000000, 0.5);
        topMask.graphics.drawRect(0, 0, stageW, 172);
        topMask.graphics.endFill();
        topMask.y = 33;
        this.addChild(topMask);
        var icon = this.createBitmapByName("egret_icon_png");
        this.addChild(icon);
        icon.x = 26;
        icon.y = 33;
        var line = new egret.Shape();
        line.graphics.lineStyle(2, 0xffffff);
        line.graphics.moveTo(0, 0);
        line.graphics.lineTo(0, 117);
        line.graphics.endFill();
        line.x = 172;
        line.y = 61;
        this.addChild(line);
        var colorLabel = new egret.TextField();
        colorLabel.textColor = 0xffffff;
        colorLabel.width = stageW - 172;
        colorLabel.textAlign = "center";
        colorLabel.text = "Hello Egret";
        colorLabel.size = 24;
        colorLabel.x = 172;
        colorLabel.y = 80;
        this.addChild(colorLabel);
        var textfield = new egret.TextField();
        this.addChild(textfield);
        textfield.alpha = 0;
        textfield.width = stageW - 172;
        textfield.textAlign = egret.HorizontalAlign.CENTER;
        textfield.size = 24;
        textfield.textColor = 0xffffff;
        textfield.x = 172;
        textfield.y = 135;
        this.textfield = textfield;
        var button = new eui.Button();
        button.label = "发送数据";
        button.horizontalCenter = 0;
        button.verticalCenter = 0;
        this.addChild(button);
        button.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onButtonClick, this);
    };
    /**
     * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
     * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
     */
    Main.prototype.createBitmapByName = function (name) {
        var result = new egret.Bitmap();
        var texture = RES.getRes(name);
        result.texture = texture;
        return result;
    };
    /**
     * 点击按钮
     * Click the button//  request.send('http://httpbin.org/post','{"name":"egret"}'); //
     */
    Main.prototype.onButtonClick = function (e) {
        var request = new HttpRequest();
        request.addEventListener(HttpRequestEvent.ON_DATA, this.onData, this);
        request.addEventListener(HttpRequestEvent.ON_ERROR, this.onError, this);
        request.send('http://127.0.0.1/phptool/api.php', { "name": "egret", "pwd": 123456 });
    };
    Main.prototype.onData = function (event) {
        console.log(event.data);
        var result = JSON.parse(event.data);
        if (result['code'] == 1) {
            alert(result.msg);
        }
    };
    Main.prototype.onError = function (event) {
        console.log('Error');
    };
    return Main;
}(eui.UILayer));
__reflect(Main.prototype, "Main");
//# sourceMappingURL=Main.js.map


text:
package com.rasterfoundry.backsplash

import java.net.URLDecoder
import java.nio.charset.StandardCharsets

import geotrellis.raster._
import geotrellis.raster.io.geotiff._
import geotrellis.spark.SpatialKey
import geotrellis.spark.tiling._
import geotrellis.proj4._
import geotrellis.vector.{Extent, Point}
import geotrellis.contrib.vlm._
import geotrellis.contrib.vlm.gdal.GDALRasterSource
import geotrellis.contrib.vlm.geotiff._
import com.typesafe.scalalogging.LazyLogging

package object export extends LazyLogging {

  private val tileSize = ExportConfig.Export.tileSize

  def getTileXY(lat: Double,
                lng: Double,
                zoom: Int,
                displayProjection: CRS = WebMercator): (Int, Int) = {
    val p = Point(lng, lat).reproject(LatLng, displayProjection)

    val webMercator = ZoomedLayoutScheme(WebMercator, 256)
    val cellSize = webMercator.levelForZoom(zoom).layout.cellSize

    val SpatialKey(x, y) = FloatingLayoutScheme(tileSize)
      .levelFor(WebMercator.worldExtent, cellSize)
      .layout
      .mapTransform(p)
    (x, y)
  }

  def exportSegmentLayout(extent: Extent, zoom: Int): GeoTiffSegmentLayout = {
    val (minTileCol, minTileRow) =
      getTileXY(extent.ymin, extent.xmax, zoom)
    val (maxTileCol, maxTileRow) =
      getTileXY(extent.ymax, extent.xmin, zoom)

    logger.info(s"Minimum Tile: ${maxTileCol}, ${maxTileRow}")
    logger.info(s"Maximum Tile: ${minTileCol}, ${minTileRow}")

    val tileCols = minTileCol - maxTileCol + 1
    val tileRows = minTileRow - maxTileRow + 1
    logger.info(s"Columns: ${tileCols}, Rows: ${tileRows}")
    val tileLayout =
      TileLayout(tileCols, tileRows, tileSize, tileSize)
    GeoTiffSegmentLayout(
      tileCols * tileSize,
      tileRows * tileSize,
      tileLayout,
      Tiled(tileSize, tileSize),
      PixelInterleave
    )
  }

  def getRasterSource(uri: String): RasterSource = {
    val enableGDAL = ExportConfig.RasterSource.enableGDAL
    if (enableGDAL) {
      GDALRasterSource(
        URLDecoder.decode(uri, StandardCharsets.UTF_8.toString()))
    } else {
      new GeoTiffRasterSource(uri)
    }

  }
}


text:
/* A Recorder can record a datasource for a given time with a specified granularity */

var timeUtils = require('./util/TimeUtils');

function Recorder(duration, granularity) {
  if (!(this instanceof Recorder))
    return new Recorder(duration, granularity);

  this._duration    = duration;
  this._granularity = granularity;
}

/** Record the given datasource to a given target. **/
Recorder.prototype.record = function(datahandler, writer) {
  var current    = timeUtils.getTimeMillis(),
      targetTime = current + this._duration,
      loopTime   = current;

  // Open the writer
  writer.outputOpen({
    start:       current,
    duration:    this._duration,
    granularity: this._granularity,
  });

  // Set all required timeouts at once.
  while(loopTime < targetTime) {
    this._newSnapshotTimeout(datahandler, writer, loopTime);
    loopTime += this._granularity;
  }

  // Close the writer
  setTimeout(function() { writer.outputClose(); }, loopTime - timeUtils.getTimeMillis());
};

Recorder.prototype._newSnapshotTimeout = function(datasource, writer, loopTime){
  var self = this;
  setTimeout(function() { self._snapshot(datasource, writer, loopTime); }, loopTime - timeUtils.getTimeMillis());
};

Recorder.prototype._snapshot = function(datasource, writer, time) {
  datasource.fetch(function(data) {
    data && writer.outputWrite(data, time);
    if(!data) console.log("Error fetching data at " + time);
  });
};

module.exports = Recorder;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC  "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      <meta name="keywords" content="W3C SVG 1.1 2nd Edition Test Suite"/>
      <meta name="description" content="W3C SVG 1.1 2nd Edition Object Test Suite"/>
      <title>
	<d:testDescription href='http://www.w3.org/TR/SVG11/fonts.html#SVGFontsOverview' xmlns='http://www.w3.org/1999/xhtml'>

        This test demonstrates CSS font matching based on the
        font-style attribute.

        The first line of text tests selecting an italic font.

        The second line tests that order of font definition
        does not effect correct matching.

        The third line tests selecting an italic and an oblique font.
        Italic can match against oblique or italic, but all other values must match exactly.
        The letter 'a' will be an UA-dependent default font-family,
        it should be oblique, possiblely a transformation of a
        normal font.

    </d:testDescription>
      </title>

            SVG Image - The test

            PNG Image - The reference

            <object id="test" data="http://t/core/standards/SVG/Testsuites/W3C-1_1F2/harness/htmlObjectMini/modified/svg/test/fonts-desc-04-t.svg" width="480" height="360" type="image/svg+xml"> </object>

			    Test Description

				<d:testDescription href='http://www.w3.org/TR/SVG11/fonts.html#SVGFontsOverview' xmlns='http://www.w3.org/1999/xhtml'>

        This test demonstrates CSS font matching based on the
        font-style attribute.

        The first line of text tests selecting an italic font.

        The second line tests that order of font definition
        does not effect correct matching.

        The third line tests selecting an italic and an oblique font.
        Italic can match against oblique or italic, but all other values must match exactly.
        The letter 'a' will be an UA-dependent default font-family,
        it should be oblique, possiblely a transformation of a
        normal font.

    </d:testDescription>

			      Operator Script

<d:operatorScript xmlns='http://www.w3.org/1999/xhtml'>

        Run the test. No interaction required.

    </d:operatorScript>

			    Pass Criteria

			<d:passCriteria xmlns='http://www.w3.org/1999/xhtml'>

        The first line of text should produce a square followed
        by a triangle.

        The second line should produce a square followed
        by a triangle.

        The third line should produce in first place
        either a triangle, a diamond, or a letter 'a' in some fallback font.
        (All are correct,and depend on which font is chosen for fallback).
        This is followed by two diamonds.

    </d:passCriteria>


text:
<!doctype html>

    <meta charset="utf-8">
    <title>Washing Post Demo</title>
    <link rel="canonical" href="https://www.washingtonpost.com/news/monkey-cage/wp/2016/01/27/how-do-you-measure-corruption-transparency-international-does-its-best-and-thats-useful/">

    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,minimal-ui">

Article sample for demo purposes only. Courtesy of Washington Post.

            <amp-img src="https://img.washingtonpost.com/pb/resources/img/thewashingtonpost-white-2x.png" width="180" height="27" />

      <%^fcf%>

        This is an AMP Paywall demo. To run this demo:

Go to
              AMP CDN Experiments and switch on AMP Dev Channel .

For testing First-Click-Free go
              here.

      <%/fcf%>
      <%#fcf%>

        This is a test page for First-Click-Free. All links opened from this page will be treated as a First-Click-Free referral (the limit is 3).

      <%/fcf%>

Monkey Cage

Here's this year's (flawed) Corruption Perception Index. Those flaws are useful.

By Dan Hough

January 27, 2016 at 11:00 AM

Early Lead

Troy Aikman believes the Cowboys will sign either Johnny Manziel or RGIII

By Cindy Boren

January 27, 2016 at 3:11 PM

Colleges

No. 11 Virginia shocks Wake Forest at the buzzer, 72-71

By Ava Wallace

January 27, 2016 at 3:17 AM

Business

Investors await Federal Reserve signal on interest rates

By Ylan Q. Mui

January 27, 2016 at 5:51 PM

Health & Science

Why the United States is so vulnerable to the alarming spread of Zika virus

By Lena H. Sun, Brady Dennis

January 27, 2016 at 5:03 PM

Acts of Faith

Republicans prefer a religious candidate. But they're willing to give Donald Trump a pass.

By Michelle Boorstein, Sarah Pulliam Bailey

January 27, 2016 at 3:00 PM

The Switch

Sales of iPhones grow at slowest pace since the smartphone was introduced

By Hayley Tsukayama

January 26, 2016 at 9:48 PM

The Switch

Twitter needs to grow to thrive. And that may not be so easy.

By Hayley Tsukayama

January 26, 2016 at 5:59 PM

The Switch

How scared is Hollywood of Netflix and Amazon?

By Drew Harwell

January 26, 2016 at 11:57 PM

Get There

Obama's new plan would help small business workers save for retirement

By Jonnelle Marte

January 26, 2016 at 5:56 PM

Help and Contact Us

Terms of Service

Privacy Policy

Print Products Terms of Sale

Digital Products Terms of Sale

Submissions and Discussion Policy

RSS Terms of Service

Ad Choices

© 1996-2015 The Washington Post

Article sample for demo purposes only. Courtesy of Washington Post.

    <amp-pixel src="https://ssl.google-analytics.com/collect?v=1&tid=UA-50597120-4&t=pageview&cid=RANDOM&dt=TITLE&dl=CANONICAL_URL&z=RANDOM"></amp-pixel>
    <amp-pixel src="//sb.scorecardresearch.com/b?c1=2&c2=3005617&rn=RANDOM&c8=TITLE&c7=CANONICAL_URL&c9=DOCUMENT_REFERRER&cs_c7amp=AMPDOC_URL"></amp-pixel>
    <amp-analytics>

    </amp-analytics>


text:
package com.openadadapter.adapters.aerserv;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;

import com.aerserv.sdk.AerServBanner;
import com.aerserv.sdk.AerServConfig;
import com.aerserv.sdk.AerServEvent;
import com.aerserv.sdk.AerServEventListener;
import com.aerserv.sdk.AerServVirtualCurrency;
import com.inmobi.monetization.IMBanner;
import com.openadadapter.BannerAdapter;
import com.openadadapter.OpenAdAdapter;
import com.openadadapter.Util;

public class AerservBannerAdapter implements BannerAdapter {

	private OpenAdAdapter oad;
	private String banner320;
	private String banner728;
	private String name;
	private boolean top;
	boolean hasAd;
	boolean shown, failed, clicked;
	AerServConfig config;
	private AerServEventListener listener = new AerServEventListener() {

		@Override
		public void onAerServEvent(final AerServEvent event,
				final List<Object> args) {
			String msg = null;
			switch (event) {
			case AD_LOADED:
				msg = "AerServ Banner Ad Loaded";
				// Toast.makeText(selfContext, msg, Toast.LENGTH_SHORT).show();
				Log.d("OAD", msg);
				hasAd = true;

				float pixels = banner.getHeight();
//				float pixels = Util.convertDpToPixel(points, oad.getActivity());
				float points = Util.convertPixelsToDp(pixels, oad.getActivity());

				if(!top){
					points = -points;
					pixels = -pixels;
				}
				oad.reportBannerHeightInPoints(points);
				oad.reportBannerHeightInPixels(pixels);

				break;
			case AD_COMPLETED:
				msg = "AerServ Banner Ad Completed ";
				// Toast.makeText(selfContext, msg, Toast.LENGTH_SHORT).show();
				Log.d("OAD", msg);
				break;
			case AD_IMPRESSION:
				msg = "AerServ Banner Ad Impression";
				// Toast.makeText(selfContext, msg, Toast.LENGTH_SHORT).show();
				Log.d("OAD", msg);
				shown = true;
				break;
			case AD_CLICKED:
				msg = "AerServ Banner Ad Clicked";
				// Toast.makeText(selfContext, msg, Toast.LENGTH_SHORT).show();
				Log.d("OAD", msg);
				clicked = true;
				break;
			case AD_DISMISSED:
				msg = "AerServ Banner Ad Dismissed";
				// Toast.makeText(selfContext, msg, Toast.LENGTH_SHORT).show();
				Log.d("OAD", msg);
				break;
			case AD_FAILED:
				msg = "AerServ Banner Ad Failed with message: "
						+ args.get(0).toString();
				// Toast.makeText(selfContext, msg, Toast.LENGTH_SHORT).show();
				Log.d("OAD", msg);
				failed = true;
				break;
			case VIDEO_START:
				msg = "AerServ Banner Video Started";
				// Toast.makeText(selfContext, msg, Toast.LENGTH_SHORT).show();
				Log.d("OAD", msg);
				break;
			case PRELOAD_READY:
				msg = "AerServ Banner Preload ready";
				// Toast.makeText(selfContext, msg, Toast.LENGTH_SHORT).show();
				Log.d("OAD", msg);
				break;
			case VC_READY:
				AerServVirtualCurrency vcObject = (AerServVirtualCurrency) args
						.get(0);
				msg = "AerServ Banner Virtual Currency PLC has loaded: "
						+ vcObject.getName() + ", "
						+ vcObject.getAmount().toString();
				// Toast.makeText(selfContext, msg, Toast.LENGTH_SHORT).show();
				Log.d("OAD", msg);
				break;
			case VC_REWARDED:
				AerServVirtualCurrency vcObject2 = (AerServVirtualCurrency) args
						.get(0);
				msg = "AerServ Banner Virtual Currency PLC has rewarded: "
						+ vcObject2.getName() + ", "
						+ vcObject2.getAmount().toString();
				// Toast.makeText(selfContext, msg, Toast.LENGTH_SHORT).show();
				Log.d("OAD", msg);
				break;
			}

		}
	};
	private AerServBanner banner;
	private LayoutParams lparams;

	@Override
	public void init(OpenAdAdapter oad, JSONObject o1) {
		this.oad = oad;
		if (o1 != null) {
			banner320 = o1.optString("banner320");
			banner728 = o1.optString("banner728");
			name = o1.optString("name");
		}
	}

	@Override
	public void writeToJSONObject(JSONObject o1) {
		if (o1 == null)
			return;
		try {
			o1.put("name", name);
			o1.put("banner320", banner320);
			o1.put("banner728", banner728);
		} catch (JSONException e) {
		}
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public void showInTop(String tag) {
		top = true;
		show();
	}

	@Override
	public void showInBottom(String tag) {
		top = false;
		show();

	}

	private void show() {
		// List keywords = "";
		config = new AerServConfig(oad.getActivity(), getBannerId())
		// .setKeywords(keywords)
				.setEventListener(listener);
		if (banner == null) {
			banner = new AerServBanner(oad.getActivity());

			lparams = new FrameLayout.LayoutParams(
					FrameLayout.LayoutParams.MATCH_PARENT,
					FrameLayout.LayoutParams.WRAP_CONTENT);

			if (top) {
				lparams.gravity = Gravity.TOP;
			} else {
				lparams.gravity = Gravity.BOTTOM;
			}
			clicked = false;
			shown = false;
			failed = false;
			banner.configure(config).show();

			banner.setLayoutParams(lparams);

			oad.getActivity().addContentView(banner, lparams);

		}
	}

	private String getBannerId() {
		String[] banners = new String[] { banner320, banner728 };
		int i = getOptimalBannerSize();
		return banners[i];
	}

	private int getOptimalBannerSize() {

		Display display = ((WindowManager) oad.getActivity().getSystemService(
				Context.WINDOW_SERVICE)).getDefaultDisplay();
		DisplayMetrics displayMetrics = new DisplayMetrics();
		display.getMetrics(displayMetrics);
		double density = displayMetrics.density;
		double width = displayMetrics.widthPixels;
		double height = displayMetrics.heightPixels;
		int[][] maparray = { { 1, 728, 90 }, { 0, 320, 50 } };
		for (int i = 0; i < maparray.length; i++) {
			if (maparray[i][1] * density <= width
					&& maparray[i][2] * density <= height) {
				return maparray[i][0];
			}
		}
		return 0;
	}

	@Override
	public void hide() {

		if (banner != null) {

			Log.i("OAD", "aerserv hide 2");

			ViewGroup vg = (ViewGroup) banner.getParent();
			if (vg != null) {
				vg.removeView(banner);
			}

//			banner.destroy();
			banner = null;
		}

	}

	@Override
	public boolean isAvailable() {
		return false;
	}

	@Override
	public boolean isShown() {
		return shown;
	}

	@Override
	public boolean isFailed() {
		return failed;
	}

}


text:
package com.suscipio_solutions.consecro_mud.Items.Basic;
import com.suscipio_solutions.consecro_mud.Items.interfaces.RawMaterial;
import com.suscipio_solutions.consecro_mud.core.interfaces.Rideable;

public class Bed extends GenRideable
{
	@Override public String ID(){	return "Bed";}

	public Bed()
	{
		super();

		readableText = "";

		setName("a bed");
		basePhyStats.setWeight(150);
		setDisplayText("a bed is here.");
		setDescription("Looks like a nice comfortable bed");
		baseGoldValue=5;
		basePhyStats().setLevel(1);
		setMaterial(RawMaterial.RESOURCE_COTTON);
		setRideBasis(Rideable.RIDEABLE_SLEEP);
		setRiderCapacity(2);
		recoverPhyStats();
	}

}


text:
import unittest
from unittest.mock import patch

import requests_mock

from frontstage import app
from tests.integration.mocked_services import (
    encoded_jwt_token,
    respondent_party,
    survey,
    survey_list_todo,
    url_banner_api,
)

class TestSurveyList(unittest.TestCase):
    def setUp(self):
        self.app = app.test_client()
        self.app.set_cookie("localhost", "authorization", "session_key")
        self.headers = {
            "Authorization": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoicmluZ3JhbUBub3d3aGVyZS5jb20iLCJ1c2Vy"
            "X3Njb3BlcyI6WyJjaS5yZWFkIiwiY2kud3JpdGUiXX0.se0BJtNksVtk14aqjp7SvnXzRbEKoqXb8Q5U9VVdy54"
            # NOQA
        }
        self.patcher = patch("redis.StrictRedis.get", return_value=encoded_jwt_token)
        self.contact_details_form = {"option": "contact_details"}
        self.patcher.start()

    def tearDown(self):
        self.patcher.stop()

    @requests_mock.mock()
    @patch("frontstage.controllers.party_controller.get_respondent_party_by_id")
    def test_account(self, mock_request, get_respondent_party_by_id):
        mock_request.get(url_banner_api, status_code=404)
        get_respondent_party_by_id.return_value = respondent_party
        with app.app_context():
            response = self.app.get("/my-account")

            self.assertEqual(response.status_code, 200)
            self.assertTrue("example@example.com".encode() in response.data)
            self.assertTrue("0987654321".encode() in response.data)

    @requests_mock.mock()
    @patch("frontstage.controllers.party_controller.get_respondent_party_by_id")
    def test_account_options(self, mock_request, get_respondent_party_by_id):
        mock_request.get(url_banner_api, status_code=404)
        get_respondent_party_by_id.return_value = respondent_party
        with app.app_context():
            response = self.app.get("/my-account")

            self.assertEqual(response.status_code, 200)
            self.assertTrue("example@example.com".encode() in response.data)
            self.assertIn("Help with your account".encode(), response.data)

    @requests_mock.mock()
    @patch("frontstage.controllers.party_controller.get_respondent_party_by_id")
    def test_account_options_not_selection(self, mock_request, get_respondent_party_by_id):
        mock_request.get(url_banner_api, status_code=404)
        get_respondent_party_by_id.return_value = respondent_party
        response = self.app.post("/my-account", data={"option": None}, follow_redirects=True)
        self.assertIn("You need to choose an option".encode(), response.data)

    @requests_mock.mock()
    @patch("frontstage.controllers.party_controller.get_respondent_party_by_id")
    def test_account_options_selection(self, mock_request, get_respondent_party_by_id):
        mock_request.get(url_banner_api, status_code=404)
        get_respondent_party_by_id.return_value = respondent_party
        response = self.app.post("/my-account", data=self.contact_details_form, follow_redirects=True)
        self.assertEqual(response.status_code, 200)
        self.assertIn("Phone number".encode(), response.data)

    @requests_mock.mock()
    @patch("frontstage.controllers.party_controller.get_respondent_party_by_id")
    def test_account_contact_details_error(self, mock_request, get_respondent_party_by_id):
        mock_request.get(url_banner_api, status_code=404)
        get_respondent_party_by_id.return_value = respondent_party
        response = self.app.post("/my-account/change-account-details", data={"first_name": ""}, follow_redirects=True)

        self.assertIn("There are 4 errors on this page".encode(), response.data)
        self.assertIn("Problem with the first name".encode(), response.data)
        self.assertIn("Problem with the phone number".encode(), response.data)
        self.assertIn("Problem with the email address".encode(), response.data)

    @requests_mock.mock()
    @patch("frontstage.controllers.party_controller.get_respondent_party_by_id")
    @patch("frontstage.controllers.party_controller.update_account")
    @patch("frontstage.controllers.party_controller.get_survey_list_details_for_party")
    def test_account_contact_details_success(
        self, mock_request, get_survey_list, update_account, get_respondent_party_by_id
    ):
        mock_request.get(url_banner_api, status_code=404)
        get_respondent_party_by_id.return_value = respondent_party
        get_survey_list.return_value = survey_list_todo
        response = self.app.post(
            "/my-account/change-account-details",
            data={
                "first_name": "new first name",
                "last_name": "new last name",
                "phone_number": "8882257773",
                "email_address": "example@example.com",
            },
            follow_redirects=True,
        )
        self.assertIn("updated your first name, last name and telephone number".encode(), response.data)

    @requests_mock.mock()
    @patch("frontstage.controllers.party_controller.get_respondent_party_by_id")
    @patch("frontstage.controllers.party_controller.update_account")
    @patch("frontstage.controllers.party_controller.get_survey_list_details_for_party")
    def test_account_change_account_email_address(
        self, mock_request, get_survey_list, update_account, get_respondent_party_by_id
    ):
        mock_request.get(url_banner_api, status_code=404)
        get_respondent_party_by_id.return_value = respondent_party
        get_survey_list.return_value = survey_list_todo
        response = self.app.post(
            "/my-account/change-account-details",
            data={
                "first_name": "test account",
                "last_name": "test_account",
                "phone_number": "07772257773",
                "email_address": "exampleone@example.com",
            },
            follow_redirects=True,
        )
        self.assertIn("updated your first name, last name and telephone number".encode(), response.data)
        self.assertIn("Change email address".encode(), response.data)
        self.assertIn("You will need to authorise a change of email address.".encode(), response.data)
        self.assertIn("We will send a verification email to".encode(), response.data)
        self.assertIn("exampleone@example.com".encode(), response.data)

    @requests_mock.mock()
    @patch("frontstage.controllers.party_controller.get_respondent_party_by_id")
    @patch("frontstage.controllers.party_controller.update_account")
    @patch("frontstage.controllers.party_controller.get_survey_list_details_for_party")
    def test_account_change_account_email_address_almost_done(
        self, mock_request, get_survey_list, update_account, get_respondent_party_by_id
    ):
        mock_request.get(url_banner_api, status_code=404)
        get_respondent_party_by_id.return_value = respondent_party
        get_survey_list.return_value = survey_list_todo
        response = self.app.post(
            "/my-account/change-account-email-address",
            data={"email_address": "exampleone@example.com"},
            follow_redirects=True,
        )
        self.assertIn("Almost done".encode(), response.data)
        self.assertIn("We have sent a verification email to your new email address.".encode(), response.data)
        self.assertIn("Follow the link in the email to verify the change.".encode(), response.data)
        self.assertIn("Email not arrived? It may be in your junk folder.".encode(), response.data)
        self.assertIn("If it does not arrive within 15 minutes, please".encode(), response.data)

    @requests_mock.mock()
    @patch("frontstage.controllers.party_controller.get_respondent_party_by_id")
    def test_account_options_selection_change_password(self, mock_request, get_respondent_party_by_id):
        mock_request.get(url_banner_api, status_code=404)
        get_respondent_party_by_id.return_value = respondent_party
        response = self.app.post("/my-account", data={"option": "change_password"}, follow_redirects=True)
        self.assertEqual(response.status_code, 200)
        self.assertTrue("Change your password".encode() in response.data)
        self.assertTrue("Enter your current password".encode() in response.data)
        self.assertTrue("Your password must have:".encode() in response.data)
        self.assertTrue("at least 12 characters".encode() in response.data)
        self.assertTrue("at least 1 uppercase letter".encode() in response.data)
        self.assertTrue("at least 1 symbol (eg: ?!£%)".encode() in response.data)
        self.assertTrue("at least 1 number".encode() in response.data)
        self.assertTrue("New Password".encode() in response.data)
        self.assertTrue("Re-type your new password".encode() in response.data)

    @requests_mock.mock()
    @patch("frontstage.controllers.party_controller.get_respondent_party_by_id")
    def test_share_survey_options_selection(self, mock_request, get_respondent_party_by_id):
        mock_request.get(url_banner_api, status_code=404)
        get_respondent_party_by_id.return_value = respondent_party
        response = self.app.post("/my-account", data={"option": "share_surveys"}, follow_redirects=True)
        self.assertEqual(response.status_code, 200)
        self.assertTrue("Share access to your surveys".encode() in response.data)
        self.assertTrue("What will happen".encode() in response.data)
        self.assertTrue("Select which surveys you want to share.".encode() in response.data)
        self.assertTrue(
            "Enter the email address of the person who will be responding to these surveys.".encode() in response.data
        )
        self.assertTrue("We will email them the instructions to access the surveys.".encode() in response.data)
        self.assertTrue(
            "Once we confirm their access, they will be able to respond to surveys on your behalf and "
            "share access with colleagues.".encode() in response.data
        )
        self.assertTrue("Continue".encode() in response.data)
        self.assertTrue("Cancel".encode() in response.data)

    @requests_mock.mock()
    @patch("frontstage.controllers.party_controller.get_respondent_party_by_id")
    def test_transfer_survey_options_selection(self, mock_request, get_respondent_party_by_id):
        mock_request.get(url_banner_api, status_code=404)
        get_respondent_party_by_id.return_value = respondent_party
        response = self.app.post("/my-account", data={"option": "transfer_surveys"}, follow_redirects=True)
        self.assertEqual(response.status_code, 200)
        self.assertTrue("Transfer your surveys".encode() in response.data)
        self.assertTrue("What will happen".encode() in response.data)
        self.assertTrue("Select which surveys you want to transfer.".encode() in response.data)
        self.assertTrue(
            "Enter the email address of the person who will be responding to these surveys.".encode() in response.data
        )
        self.assertTrue("We will email them the instructions to access the surveys.".encode() in response.data)
        self.assertTrue(
            "Once we confirm their access, they will be able to respond to the surveys and share access "
            "with their colleagues.".encode() in response.data
        )
        self.assertTrue("Continue".encode() in response.data)
        self.assertTrue("Cancel".encode() in response.data)

    @requests_mock.mock()
    @patch("frontstage.controllers.party_controller.get_respondent_party_by_id")
    def test_something_else_options_selection(self, mock_request, get_respondent_party_by_id):
        mock_request.get(url_banner_api, status_code=404)
        get_respondent_party_by_id.return_value = respondent_party
        response = self.app.post("/my-account", data={"option": "something_else"}, follow_redirects=True)
        self.assertEqual(response.status_code, 200)
        self.assertTrue("Send a message".encode() in response.data)
        self.assertTrue(
            "Send us a message with a description of your issue and we will get back to you.".encode() in response.data
        )
        self.assertTrue("My account".encode() in response.data)
        self.assertTrue("Send".encode() in response.data)
        self.assertTrue("Cancel".encode() in response.data)

    @requests_mock.mock()
    @patch("frontstage.controllers.party_controller.get_respondent_party_by_id")
    @patch("frontstage.controllers.party_controller.get_survey_list_details_for_party")
    @patch("frontstage.controllers.conversation_controller.send_message")
    @patch("frontstage.controllers.survey_controller.get_survey_by_short_name")
    def test_create_message_post_success(
        self, mock_request, get_survey, send_message, get_survey_list, get_respondent_party_by_id
    ):
        mock_request.get(url_banner_api, status_code=404)
        get_survey.return_value = survey
        get_survey_list.return_value = survey_list_todo
        get_respondent_party_by_id.return_value = respondent_party
        form = {"body": "something-else"}
        response = self.app.post("/my-account/something-else", data=form, follow_redirects=True)

        self.assertEqual(response.status_code, 200)
        self.assertIn("Message sent.".encode(), response.data)


text:
import KLineRender from "./KLineRender.js"
import BaseChart from "./BaseChart.js"
import KEntity from "./KEntity.js"
import KLineDrawing from "./KLineDrawing.js"
import datas from "./klinedata.js"
import timedatas from "./timedata.js"
import IndexRender from "./IndexRender.js"
import VOLDrawing from "./VOLDrawing.js"
import AvgDrawing from "./AvgDrawing.js"
import TimeRender from "./TimeRender.js"
import TimeEntity from "./TimeEntity.js"
import TimeDrawing from "./TimeDrawing.js"
import TimeIndexRender from "./TimeIndexRender.js"
import CrossDrawing from "./CrossDrawing.js"

let chart = new BaseChart("#canvas");
chart.resizeCanvas();

let render = new KLineRender("kl")
    // render.margin = [10, 10, 20, 20]
render.viewport = { right: 1, bottom: 200 }
render.padding = [0, 40, 0, 40]
    // render.option.weight = 1

new KLineDrawing(render)
new CrossDrawing(render)
new AvgDrawing(render, "c", 5, "#508ce7", 1)
new AvgDrawing(render, "c", 10, "#ec9917", 1)
new AvgDrawing(render, "c", 20, "#e339dd", 1)
new AvgDrawing(render, "c", 60, "#21a764", 1)

let list = datas.LIST
for (let entity of list) {
    render.addToEnd(new KEntity(entity.OPEN, entity.HIGH, entity.LOW, entity.CLOS, entity.VOLM))
}

let indexRender = new IndexRender("index")
indexRender.viewport = { right: 1, bottom: 80 }
indexRender.margin = [0, 20, 0, 0]
indexRender.padding = [0, 10, 0, 0]
indexRender.entitySet = render.entitySet
new VOLDrawing(indexRender)
new CrossDrawing(indexRender)
new AvgDrawing(indexRender, "v", 5, "#508ce7", 1.5)
new AvgDrawing(indexRender, "v", 10, "#ec9917", 1.5)

let timeRender = new TimeRender("time")
timeRender.viewport = { right: 1, bottom: 100 }
timeRender.margin = [0, 20, 0, 0]
timeRender.padding = [0, 20, 0, 20]
new AvgDrawing(timeRender, "n", 1, "#ec9917", 1)

let timeIndexRender = new TimeIndexRender("timeIndex")
timeIndexRender.viewport = { right: 1, bottom: 40 }
timeIndexRender.margin = [0, 0, 0, 0]
timeIndexRender.padding = [0, 10, 0, 0]
timeIndexRender.entitySet = timeRender.entitySet
new VOLDrawing(timeIndexRender, "timeline")

let times = timedatas.LIST
for (let entity of times) {
    timeRender.addToEnd(new TimeEntity(entity.MINT, entity.NOW, entity.VOLM, entity.AMNT, entity.AVG))
}

new TimeDrawing(timeRender)

chart.addRender(render)
chart.addRender(indexRender)
chart.addRender(timeRender)
chart.addRender(timeIndexRender)
chart.render()

// let index = 0
// let hander = setInterval(function() {
//     let entity = times[index++]
//     timeRender.addToEnd(new TimeEntity(entity.MINT, entity.NOW, entity.VOLM, entity.AMNT, entity.AVG))
//     if (index >= 240) {
//         clearInterval(hander)
//     }
// }, 100)


text:
package parts;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

/**
 *
 * @author czimbortibor
 */
public class MouseHandler implements MouseListener{
    @Override
    public void mouseClicked(MouseEvent event){
        if ( ((Door)event.getSource()).getSelected() ){
            ((Door)event.getSource()).setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/door_simple.png")));
            ((Door)event.getSource()).setSelected(false);
        } else{
            ((Door)event.getSource()).setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/door_selected.png")));
            ((Door)event.getSource()).setSelected(true);
        }
    }

    @Override
    public void mousePressed(MouseEvent me) {

    }

    @Override
    public void mouseReleased(MouseEvent me) {

    }

    @Override
    public void mouseEntered(MouseEvent me) {

    }

    @Override
    public void mouseExited(MouseEvent me) {

    }
}


text:
require 'rails_helper'

RSpec.describe UserFeedItem, 'associations' do
  it { is_expected.to belong_to(:user) }
  it { is_expected.to belong_to(:feed_item) }
end


text:
define([
    'agrc/modules/Formatting',

    'app/charts/Controls',
    'app/config',
    'app/_GPMixin',
    'app/_ResultsQueryMixin',

    'dijit/_TemplatedMixin',
    'dijit/_WidgetBase',
    'dijit/_WidgetsInTemplateMixin',

    'dojo/dom-class',
    'dojo/promise/all',
    'dojo/string',
    'dojo/text!app/charts/templates/ChartContainer.html',
    'dojo/topic',
    'dojo/_base/declare',
    'dojo/_base/lang',

    'bootstrap',
    'highcharts',
    'highcharts/modules/boost.src'
], function (
    formatting,

    Controls,
    config,
    _GPMixin,
    _ResultsQueryMixin,

    _TemplatedMixin,
    _WidgetBase,
    _WidgetsInTemplateMixin,

    domClass,
    all,
    dojoString,
    template,
    topic,
    declare,
    lang
) {
    return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, _ResultsQueryMixin, _GPMixin], {
        // description:
        //      Container that holds all of the chart widgets.

        templateString: template,
        baseClass: 'chart-container',
        widgetsInTemplate: true,

        // gp: Geoprocessor
        gp: null,

        // currentQuery: string
        currentQuery: null,

        // currentChartType: string
        currentChartType: null,

        // currentParam: string
        currentParam: null,

        // Properties to be sent into constructor

        postCreate: function () {
            // summary:
            //      Overrides method of same name in dijit._Widget.
            // tags:
            //      private
            console.log('app.charts.ChartContainer::postCreate', arguments);

            this.controls = new Controls({}, this.chartControlsDiv);
            this.controls.startup();
            this.own(
                this.controls,
                this.controls.on('update-chart', lang.hitch(this, 'updateChart'))
            );

            this.inherited(arguments);
        },
        updateChart: function (evt) {
            // summary:
            //      regenerates the chart with the new parameters
            // evt: Event Object
            // {
            //      param: String
            //      type: String
            // }
            console.log('app.charts.ChartContainer:updateChart', arguments);

            if (!this.checkForCurrentQuery()) {
                return;
            }

            var query = this.convertToResultsQuery(this.currentQuery) + ' AND Param = \'' + evt.param + '\'';

            if (!this.gp) {
                this.initGP(config.urls.buildChart);
            }

            var chartType;
            var logTransform = false;
            if (evt.chartType === 'histogram-log-transform') {
                chartType = 'histogram';
                logTransform = true;
            } else {
                chartType = evt.chartType;
            }

            this.submitJob({
                defQuery: query,
                chartType: chartType,
                logTransform: logTransform
            });

            this.currentChartType = chartType;
            this.currentParam = evt.param;
        },
        onJobComplete: function (result) {
            // summary:
            //      Callback for gp.submitJob
            // result: Response Object
            console.log('app.charts.ChartContainer:onJobComplete', arguments);

            var that = this;
            var getData = function (parameter) {
                return that.gp.getResultData(result.jobInfo.jobId, parameter);
            };
            all({
                data: getData('data'),
                numResults: getData('numResults'),
                numStations: getData('numStations')
            }).then(lang.hitch(this, 'onChartGPComplete'));
        },
        onChartGPComplete: function (results) {
            // summary:
            //      callback for gp task
            // results: Object
            console.log('app.charts.ChartContainer:onChartGPComplete', arguments);

            this.controls.resetSpinner();
            var data = results.data.value;
            var numResults = results.numResults.value;
            var numStations = results.numStations.value;
            this.updateMsg(numResults, numStations);

            var chartType;
            var plotOptions;
            var xAxis;
            var yAxis;
            var seriesData;
            var color;
            var header = '';
            if (this.currentChartType === 'histogram') {
                chartType = 'column';
                plotOptions = {
                    column: {
                        pointPadding: 0,
                        groupPadding: 0,
                        borderWidth: 0.5,
                        shadow: false,
                        tooltip: {
                            headerFormat: header
                        }
                    },
                    tooltip: {
                        headerFormat: header
                    }
                };
                xAxis = {
                    categories: data[1],
                    labels: {
                        formatter: function () {
                            return formatting.round(this.value, 2);
                        }
                    }
                };
                yAxis = {
                    title: false
                };
                seriesData = data[0];
                color = 'rgb(124, 181, 236)';
            } else {
                chartType = 'scatter';
                plotOptions = {
                    scatter: {
                        tooltip: {
                            headerFormat: header,
                            pointFormatter: function () {
                                return new Date(this.x).toLocaleDateString() + '<br>' + this.y + ' mg/L';
                            }
                        }
                    }
                };
                xAxis = {
                    type: 'datetime'
                };
                yAxis = {
                    title: false
                };
                seriesData = data;
                color = 'rgba(124, 181, 236, 0.5)';
            }
            new window.Highcharts.Chart({
                chart: {
                    renderTo: this.chartDiv,
                    type: chartType,
                    height: 300
                },
                credits: {
                    enabled: false
                },
                legend: {
                    enabled: false
                },
                series: [{
                    name: 'count',
                    data: seriesData,
                    color: color
                }],
                plotOptions: plotOptions,
                title: false,
                xAxis: xAxis,
                yAxis: yAxis
            });
        },
        toggle: function () {
            // summary:
            //      toggles the visibility of the dialog
            console.log('app/charts/ChartContainer:toggle', arguments);

            domClass.toggle(this.panel, 'hidden');

            this.controls.initSpinner();
        },
        updateMsg: function (num_results, num_stations) {
            // summary:
            //      Sets the chart message numbers
            // num_results: Number
            // num_stations: Number
            console.log('app/charts/ChartContainer:updateMsg', arguments);

            this.chartMsg.innerHTML = dojoString.substitute(
                config.chartMsgTxt,
                [formatting.addCommas(num_results), formatting.addCommas(num_stations)]
            );
        },
        toggleAlert: function (show) {
            // summary:
            //      toggles the visibility of the heads up alert
            // show: Boolean
            console.log('app/charts/ChartContainer:toggleAlert', arguments);

            var f = (show) ? domClass.remove : domClass.add;
            f(this.alert, 'hidden');
        },
        switchToSecure: function () {
            // summary:
            //      switches to secure chart
            console.log('app/charts/ChartContainer:switchToSecure', arguments);

            this.initGP(config.urls.secureBuildChart);
        }
    });
});


text:
[![Build Status](https://travis-ci.org/lazojs/gammabot.svg?branch=master)](https://travis-ci.org/lazojs/gammabot)

# gammabot

> It's funny but is it going to get them off their tractors?

Traces Lazo node module dependencies based on package.json meta data.

## Usage

```javascript
var gammabot = require('gammabot');

// arguments
// 1. node modules directory to be scanned
// 2. options
//    - inlcude: regex of files to include
//    - includeDir: regex to limit directories
//    - excludeDir: regex to exclude directories; default is /test/
//    - exclude: regex to exclude files
// 3. callback

gammabot('node_modules', {}, function (err, list) {
    if (err) {
        throw err;
    }

    // all lazo node modules
    console.log(list.modules);
    // module version conflicts
    console.log(list.conflicts);
});
```


text:
jQuery.fn.dragToSelect = function (conf) {
	var c = typeof(conf) == 'object' ? conf : {};

	// Config
	var config = jQuery.extend({
		className:		'pf-map-drag-to-select',
		activeClass:	'active',
		disabledClass:	'disabled',
		selectedClass:	'pf-system-selected',
        ignoredClass:   'pf-system-locked', // do not select locked systems
		scrollTH:		10,
		percentCovered:	25,
		selectables:	false,
		autoScroll:		false,
		selectOnMove:	false,
		onShow:			function () {return true;},
		onHide:			function () {return true;},
		onRefresh:		function () {return true;}
	}, c);

	var realParent	= jQuery(this);
	var parent		= realParent;

	var animationFrameId;
	var mouseIsDown = false;
	var lastMousePosition = { x: 0, y: 0 };

    // deselected items
    var deselectedItems = $();

	do {
		if (/auto|scroll|hidden/.test(parent.css('overflow'))) {
			break;
		}
		parent = parent.parent();
	} while (parent[0].parentNode);

	// Does user want to disable dragToSelect
	if (conf == 'disable') {
		parent.addClass(config.disabledClass);
		return this;
	}
	else if (conf == 'enable') {
		parent.removeClass(config.disabledClass);
		return this;
	}

	var parentOffset	= parent.offset();
	var parentDim		= {
		left:	parentOffset.left,
		top:	parentOffset.top,
		width:	parent.width(),
		height:	parent.height()
	};

	// Current origin of select box
	var selectBoxOrigin = {
		left:	0,
		top:	0
	};

	// Create select box
	var selectBox = $('<div>')
						.appendTo(parent)
						.attr('class', config.className)
						.css('position', 'absolute');

	// Shows the select box
	var showSelectBox = function (e) {
		if (parent.is('.' + config.disabledClass)) {
			return;
		}

		selectBoxOrigin.left	= e.pageX - parentDim.left + parent[0].scrollLeft - 5;
		selectBoxOrigin.top		= e.pageY - parentDim.top + parent[0].scrollTop - 5;

		var css = {
			left:		selectBoxOrigin.left + 'px',
			top:		selectBoxOrigin.top + 'px',
			width:		'1px',
			height:		'1px'
		};
		selectBox.addClass(config.activeClass).css(css);

		config.onShow();
	};

	// Refreshes the select box dimensions and possibly position
	var refreshSelectBox = function () {
		var refreshed = false;

		if (!selectBox.is('.' + config.activeClass) || parent.is('.' + config.disabledClass)) {
			return refreshed;
		}

        // get scroll position
        var leftScroll  = 0;
        var rightScroll = 0;

        if(realParent.data('scrollLeft')){
            leftScroll  = realParent.data('scrollLeft');
        }

        if(realParent.data('scrollRight')){
            rightScroll  = realParent.data('scrollRight');
        }

		var left		= lastMousePosition.x - parentDim.left + parent[0].scrollLeft;
		var top			= lastMousePosition.y - parentDim.top + parent[0].scrollTop;
		var newLeft		= left;
		var newTop		= top;
		var tempWidth	= selectBoxOrigin.left - newLeft ;
		var newHeight	= selectBoxOrigin.top - newTop;
        newLeft         = selectBoxOrigin.left - leftScroll;
        var newWidth	= left - selectBoxOrigin.left;

        if(newWidth < 0){
            newLeft = newLeft - tempWidth ;
            newWidth = newWidth * -1;
        }

		if (top > selectBoxOrigin.top) {
			newTop		= selectBoxOrigin.top;
			newHeight	= top - selectBoxOrigin.top;
		}

		// check if dimension has changed -> save performance
		var dimensionHash = [newWidth, newHeight].join('_');

		if(selectBox.data('dimension-hash') !== dimensionHash){
			selectBox.data('dimension-hash', dimensionHash);
			var css = {
				left:	newLeft + 'px',
				top:	newTop + 'px',
				width:	newWidth + 'px',
				height:	newHeight + 'px'
			};

			selectBox.css(css);
			config.onRefresh();
			refreshed = true;
		}

		return refreshed;
	};

	// Hides the select box
	var hideSelectBox = function () {
		if (!selectBox.is('.' + config.activeClass) || parent.is('.' + config.disabledClass)) {
			return;
		}
		if (config.onHide(selectBox, deselectedItems) !== false) {
			selectBox.removeClass(config.activeClass);
		}
	};

	// Scrolls parent if needed
	var scrollPerhaps = function (e) {
		if (!selectBox.is('.' + config.activeClass) || parent.is('.' + config.disabledClass)) {
			return;
		}

		// Scroll down
		if ((e.pageY + config.scrollTH) > (parentDim.top + parentDim.height)) {
			parent[0].scrollTop += config.scrollTH;
		}
		// Scroll up
		if ((e.pageY - config.scrollTH) < parentDim.top) {
			parent[0].scrollTop -= config.scrollTH;
		}
		// Scroll right
		if ((e.pageX + config.scrollTH) > (parentDim.left + parentDim.width)) {
			parent[0].scrollLeft += config.scrollTH;
		}
		// Scroll left
		if ((e.pageX - config.scrollTH) < parentDim.left) {
			parent[0].scrollLeft -= config.scrollTH;
		}
	};

	// Selects all the elements in the select box's range
	var selectElementsInRange = function () {
		if (!selectBox.is('.' + config.activeClass) || parent.is('.' + config.disabledClass)) {
			return;
		}

		var selectables		= realParent.find(config.selectables + ':not(.' + config.ignoredClass + ')');
		var selectBoxOffset	= selectBox.offset();
		var selectBoxDim	= {
			left:	selectBoxOffset.left,
			top:	selectBoxOffset.top,
			width:	selectBox.width(),
			height:	selectBox.height()
		};

		selectables.each(function (i) {
			var el			= $(this);
			var elOffset	= el.offset();
			var elDim		= {
				left:	elOffset.left,
				top:	elOffset.top,
				width:	el.width(),
				height:	el.height()
			};

			if (percentCovered(selectBoxDim, elDim) > config.percentCovered) {
				el.addClass(config.selectedClass);
				// remove element from "deselected" elements (e.g on add -> remove -> add scenario)
				deselectedItems = deselectedItems.not(el);
			}else {

                if(el.hasClass(config.selectedClass)){
                    el.removeClass(config.selectedClass);
					deselectedItems = deselectedItems.add(el);
                }
			}
		});

	};

	// Returns the amount (in %) that dim1 covers dim2
	var percentCovered = function (dim1, dim2) {
		// The whole thing is covering the whole other thing
		if (
			(dim1.left <= dim2.left) &&
			(dim1.top <= dim2.top) &&
			((dim1.left + dim1.width) >= (dim2.left + dim2.width)) &&
			((dim1.top + dim1.height) > (dim2.top + dim2.height))
		) {
			return 100;
		}
		// Only parts may be covered, calculate percentage
		else {
			dim1.right		= dim1.left + dim1.width;
			dim1.bottom		= dim1.top + dim1.height;
			dim2.right		= dim2.left + dim2.width;
			dim2.bottom		= dim2.top + dim2.height;

			var l = Math.max(dim1.left, dim2.left);
			var r = Math.min(dim1.right, dim2.right);
			var t = Math.max(dim1.top, dim2.top);
			var b = Math.min(dim1.bottom, dim2.bottom);

			if (b >= t && r >= l) {
			/*	$('<div/>').appendTo(document.body).css({
					background:	'red',
					position:	'absolute',
					left:		l + 'px',
					top:		t + 'px',
					width:		(r - l) + 'px',
					height:		(b - t) + 'px',
					zIndex:		100
				}); */

				var percent = (((r - l) * (b - t)) / (dim2.width * dim2.height)) * 100;

			//	alert(percent + '% covered')

				return percent;
			}
		}
		// Nothing covered, return 0
		return 0;
	};

	// Event functions ----------------------------------------------------------------------------
	var mousemoveCallback = function(){
		if(mouseIsDown){
			var refreshed = refreshSelectBox();

			if(refreshed && config.selectables && config.selectOnMove){
				selectElementsInRange();
			}

			// recursive re-call on next render
			animationFrameId = requestAnimationFrame(mousemoveCallback);
		}
	}

	var mouseupCallback = function(){
		if (config.selectables){
			selectElementsInRange();
		}
		hideSelectBox();

		// stop animation frame and "reset" to default
		cancelAnimationFrame(animationFrameId);
		mouseIsDown = false;
		// reset deselected item array
		deselectedItems = $();
	}

	// Do the right stuff then return this --------------------------------------------------------

	selectBox.mousemove(function(e){
		lastMousePosition.x = e.pageX;
		lastMousePosition.y = e.pageY;
		e.preventDefault();
	}).mouseup(mouseupCallback);

	parent.mousedown(function(e){
		if (
			e.which === 1 && // left mouse down
			e.target === realParent[0] // prevent while dragging a system :)
		) {

			// Make sure user isn't clicking scrollbar (or disallow clicks far to the right actually)
			if ((e.pageX + 20) > jQuery(document.body).width()) {
				return;
			}

			showSelectBox(e);
			mouseIsDown = true;
			animationFrameId = requestAnimationFrame(mousemoveCallback);
		}

		e.preventDefault();
	}).mousemove(function(e){
		lastMousePosition.x = e.pageX;
		lastMousePosition.y = e.pageY;
		e.preventDefault();
	}).mouseup(mouseupCallback);

	// Be nice
	return this;
};


text:
package com.example.android.sunshine.app;

import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataItem;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;

/**
 * Created by skipj on 27.10.2015.
 */
public class DigitalWatchFaceUtil {
    private static final String TAG = "DigitalWatchFaceUtil";

    /**
     * The {@link DataMap} key for {@link SunshineWearable} background color name.
     * The color name must be a {@link String} recognized by {@link Color#parseColor}.
     */
    public static final String KEY_BACKGROUND_COLOR = "BACKGROUND_COLOR";

    /**
     * The {@link DataMap} key for {@link SunshineWearable} hour digits color name.
     * The color name must be a {@link String} recognized by {@link Color#parseColor}.
     */
    public static final String KEY_WEATHER_ID = "key_weather_id";

    /**
     * The {@link DataMap} key for {@link SunshineWearable} minute digits color name.
     * The color name must be a {@link String} recognized by {@link Color#parseColor}.
     */
    public static final String KEY_MAX_TEMP = "key_max_temp";

    /**
     * The {@link DataMap} key for {@link SunshineWearable} second digits color name.
     * The color name must be a {@link String} recognized by {@link Color#parseColor}.
     */
    public static final String KEY_MIN_TEMP = "key_min_temp";

    /**
     * The path for the {@link DataItem} containing {@link SunshineWearable} configuration.
     */
    public static final String PATH = "/weather";

    /**
     * Name of the default interactive mode background color and the ambient mode background color.
     */
    public static final String COLOR_NAME_DEFAULT_AND_AMBIENT_BACKGROUND = "#03A9F4";
    public static final int COLOR_VALUE_DEFAULT_AND_AMBIENT_BACKGROUND =
            parseColor(COLOR_NAME_DEFAULT_AND_AMBIENT_BACKGROUND);

    /**
     * Name of the default interactive mode hour digits color and the ambient mode hour digits
     * color.
     */
    public static final String COLOR_NAME_DEFAULT_AND_AMBIENT_HOUR_DIGITS = "White";
    public static final int COLOR_VALUE_DEFAULT_AND_AMBIENT_HOUR_DIGITS =
            parseColor(COLOR_NAME_DEFAULT_AND_AMBIENT_HOUR_DIGITS);

    /**
     * Name of the default interactive mode minute digits color and the ambient mode minute digits
     * color.
     */
    public static final String COLOR_NAME_DEFAULT_AND_AMBIENT_MINUTE_DIGITS = "White";
    public static final int COLOR_VALUE_DEFAULT_AND_AMBIENT_MINUTE_DIGITS =
            parseColor(COLOR_NAME_DEFAULT_AND_AMBIENT_MINUTE_DIGITS);

    /**
     * Name of the default interactive mode second digits color and the ambient mode second digits
     * color.
     */
    public static final String COLOR_NAME_DEFAULT_AND_AMBIENT_SECOND_DIGITS = "White";
    public static final int COLOR_VALUE_DEFAULT_AND_AMBIENT_SECOND_DIGITS =
            parseColor(COLOR_NAME_DEFAULT_AND_AMBIENT_SECOND_DIGITS);

    /**
     * Callback interface to perform an action with the current config {@link DataMap} for
     * {@link SunshineWearable}.
     */
    public interface FetchConfigDataMapCallback {
        /**
         * Callback invoked with the current config {@link DataMap} for
         * {@link SunshineWearable}.
         */
        void onConfigDataMapFetched(DataMap config);
    }

    private static int parseColor(String colorName) {
        return Color.parseColor(colorName.toLowerCase());
    }

    /**
     * Asynchronously fetches the current config {@link DataMap} for {@link SunshineWearable}
     * and passes it to the given callback.
     * <p>
     * If the current config {@link DataItem} doesn't exist, it isn't created and the callback
     * receives an empty DataMap.
     */
    public static void fetchConfigDataMap(final GoogleApiClient client,
                                          final FetchConfigDataMapCallback callback) {
        Wearable.NodeApi.getLocalNode(client).setResultCallback(
                new ResultCallback<NodeApi.GetLocalNodeResult>() {
                    @Override
                    public void onResult(NodeApi.GetLocalNodeResult getLocalNodeResult) {
                        String localNode = getLocalNodeResult.getNode().getId();
                        Uri uri = new Uri.Builder()
                                .scheme("wear")
                                .path(DigitalWatchFaceUtil.PATH)
                                .authority(localNode)
                                .build();
                        Wearable.DataApi.getDataItem(client, uri)
                                .setResultCallback(new DataItemResultCallback(callback));
                    }
                }
        );
    }

    private static class DataItemResultCallback implements ResultCallback<DataApi.DataItemResult> {

        private final FetchConfigDataMapCallback mCallback;

        public DataItemResultCallback(FetchConfigDataMapCallback callback) {
            mCallback = callback;
        }

        @Override
        public void onResult(DataApi.DataItemResult dataItemResult) {
            if (dataItemResult.getStatus().isSuccess()) {
                if (dataItemResult.getDataItem() != null) {
                    DataItem configDataItem = dataItemResult.getDataItem();
                    DataMapItem dataMapItem = DataMapItem.fromDataItem(configDataItem);
                    DataMap config = dataMapItem.getDataMap();
                    mCallback.onConfigDataMapFetched(config);
                } else {
                    mCallback.onConfigDataMapFetched(new DataMap());
                }
            }
        }
    }

    public static int getIconResourceForWeatherCondition(int weatherId) {
        // Based on weather code data found at:
        // http://bugs.openweathermap.org/projects/api/wiki/Weather_Condition_Codes
        if (weatherId >= 200 && weatherId <= 232) {
            return R.drawable.ic_storm;
        } else if (weatherId >= 300 && weatherId <= 321) {
            return R.drawable.ic_light_rain;
        } else if (weatherId >= 500 && weatherId <= 504) {
            return R.drawable.ic_rain;
        } else if (weatherId == 511) {
            return R.drawable.ic_snow;
        } else if (weatherId >= 520 && weatherId <= 531) {
            return R.drawable.ic_rain;
        } else if (weatherId >= 600 && weatherId <= 622) {
            return R.drawable.ic_snow;
        } else if (weatherId >= 701 && weatherId <= 761) {
            return R.drawable.ic_fog;
        } else if (weatherId == 761 || weatherId == 781) {
            return R.drawable.ic_storm;
        } else if (weatherId == 800) {
            return R.drawable.ic_clear;
        } else if (weatherId == 801) {
            return R.drawable.ic_light_clouds;
        } else if (weatherId >= 802 && weatherId <= 804) {
            return R.drawable.ic_cloudy;
        }
        return -1;
    }

    public static String formatTemperature(Resources resources, double temperature) {
        return String.format(resources.getString(R.string.format_temperature), temperature);
    }

    private DigitalWatchFaceUtil() { }

}