text stringlengths 2 1.04M | meta dict |
|---|---|
package gossip
import (
"fmt"
"math"
"math/rand"
"sync"
"time"
"github.com/weaveworks/mesh"
"github.com/weaveworks/weave/common"
)
// Router to convey gossip from one gossiper to another, for testing
type unicastMessage struct {
sender mesh.PeerName
buf []byte
}
type broadcastMessage struct {
sender mesh.PeerName
data mesh.GossipData
}
type gossipMessage struct {
sender mesh.PeerName
data mesh.GossipData
}
type exitMessage struct {
exitChan chan struct{}
}
type flushMessage struct {
flushChan chan struct{}
}
type TestRouter struct {
sync.Mutex
gossipChans map[mesh.PeerName]chan interface{}
loss float32 // 0.0 means no loss
}
func NewTestRouter(loss float32) *TestRouter {
return &TestRouter{gossipChans: make(map[mesh.PeerName]chan interface{}, 100), loss: loss}
}
// Copy so we can access outside of a lock
func (grouter *TestRouter) copyGossipChans() map[mesh.PeerName]chan interface{} {
ret := make(map[mesh.PeerName]chan interface{})
grouter.Lock()
defer grouter.Unlock()
for p, c := range grouter.gossipChans {
ret[p] = c
}
return ret
}
func (grouter *TestRouter) Stop() {
for peer := range grouter.copyGossipChans() {
grouter.RemovePeer(peer)
}
}
func (grouter *TestRouter) gossipBroadcast(sender mesh.PeerName, update mesh.GossipData) {
for _, gossipChan := range grouter.copyGossipChans() {
select {
case gossipChan <- broadcastMessage{sender: sender, data: update}:
default: // drop the message if we cannot send it
common.Log.Errorf("Dropping message")
}
}
}
func (grouter *TestRouter) gossip(sender mesh.PeerName, update mesh.GossipData) error {
gossipChans := grouter.copyGossipChans()
count := int(math.Log2(float64(len(gossipChans))))
for dest, gossipChan := range gossipChans {
if dest == sender {
continue
}
select {
case gossipChan <- gossipMessage{sender: sender, data: update}:
default: // drop the message if we cannot send it
common.Log.Errorf("Dropping message")
}
count--
if count <= 0 {
break
}
}
return nil
}
func (grouter *TestRouter) Flush() {
for _, gossipChan := range grouter.copyGossipChans() {
flushChan := make(chan struct{})
gossipChan <- flushMessage{flushChan: flushChan}
<-flushChan
}
}
func (grouter *TestRouter) RemovePeer(peer mesh.PeerName) {
grouter.Lock()
gossipChan := grouter.gossipChans[peer]
grouter.Unlock()
resultChan := make(chan struct{})
gossipChan <- exitMessage{exitChan: resultChan}
<-resultChan
grouter.Lock()
delete(grouter.gossipChans, peer)
grouter.Unlock()
}
type TestRouterClient struct {
router *TestRouter
sender mesh.PeerName
}
func (grouter *TestRouter) run(sender mesh.PeerName, gossiper mesh.Gossiper, gossipChan chan interface{}) {
gossipTimer := time.Tick(2 * time.Second)
for {
select {
case gossip := <-gossipChan:
switch message := gossip.(type) {
case exitMessage:
close(message.exitChan)
return
case flushMessage:
close(message.flushChan)
case unicastMessage:
if rand.Float32() > (1.0 - grouter.loss) {
continue
}
if err := gossiper.OnGossipUnicast(message.sender, message.buf); err != nil {
panic(fmt.Sprintf("Error doing gossip unicast to %s: %s", message.sender, err))
}
case broadcastMessage:
if rand.Float32() > (1.0 - grouter.loss) {
continue
}
for _, msg := range message.data.Encode() {
if _, err := gossiper.OnGossipBroadcast(message.sender, msg); err != nil {
panic(fmt.Sprintf("Error doing gossip broadcast: %s", err))
}
}
case gossipMessage:
if rand.Float32() > (1.0 - grouter.loss) {
continue
}
for _, msg := range message.data.Encode() {
diff, err := gossiper.OnGossip(msg)
if err != nil {
panic(fmt.Sprintf("Error doing gossip: %s", err))
}
if diff == nil {
continue
}
// Sanity check - reconsuming the diff should yield nil
for _, diffMsg := range diff.Encode() {
if nextDiff, err := gossiper.OnGossip(diffMsg); err != nil {
panic(fmt.Sprintf("Error doing gossip: %s", err))
} else if nextDiff != nil {
panic(fmt.Sprintf("Breach of gossip interface: %v != nil", nextDiff))
}
}
grouter.gossip(message.sender, diff)
}
}
case <-gossipTimer:
grouter.gossip(sender, gossiper.Gossip())
}
}
}
func (grouter *TestRouter) Connect(sender mesh.PeerName, gossiper mesh.Gossiper) mesh.Gossip {
gossipChan := make(chan interface{}, 100)
go grouter.run(sender, gossiper, gossipChan)
grouter.Lock()
grouter.gossipChans[sender] = gossipChan
grouter.Unlock()
return TestRouterClient{grouter, sender}
}
func (client TestRouterClient) GossipUnicast(dstPeerName mesh.PeerName, buf []byte) error {
client.router.Lock()
gossipChan := client.router.gossipChans[dstPeerName]
client.router.Unlock()
select {
case gossipChan <- unicastMessage{sender: client.sender, buf: buf}:
default: // drop the message if we cannot send it
common.Log.Errorf("Dropping message")
}
return nil
}
func (client TestRouterClient) GossipBroadcast(update mesh.GossipData) {
client.router.gossipBroadcast(client.sender, update)
}
func (client TestRouterClient) GossipNeighbourSubset(update mesh.GossipData) {
client.router.gossip(client.sender, update)
}
| {
"content_hash": "b70b4239785aba1b949bee355104dc68",
"timestamp": "",
"source": "github",
"line_count": 205,
"max_line_length": 107,
"avg_line_length": 25.726829268292683,
"alnum_prop": 0.6943496397421313,
"repo_name": "weaveworks/weave",
"id": "2824e83a1d6d132f6878ed8bd6cfeb1c31d46fd0",
"size": "5274",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "testing/gossip/mocks.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "4434"
},
{
"name": "Go",
"bytes": "772745"
},
{
"name": "Makefile",
"bytes": "18761"
},
{
"name": "Python",
"bytes": "1057"
},
{
"name": "Ruby",
"bytes": "1545"
},
{
"name": "Shell",
"bytes": "219492"
}
],
"symlink_target": ""
} |
FROM balenalib/armv7hf-debian:sid-run
LABEL io.balena.device-type="colibri-imx6"
RUN apt-get update && apt-get install -y --no-install-recommends \
less \
kmod \
nano \
net-tools \
ifupdown \
iputils-ping \
i2c-tools \
usbutils \
&& rm -rf /var/lib/apt/lists/*
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Sid \nVariant: run variant \nDefault variable(s): UDEV=off \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"content_hash": "18e20bb7d2dac2f108b92deca1fdc0c9",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 608,
"avg_line_length": 54.25,
"alnum_prop": 0.7004608294930875,
"repo_name": "nghiant2710/base-images",
"id": "cbf6346fbec9f4762a1e27c63bd71fb5bcde8819",
"size": "1085",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "balena-base-images/device-base/colibri-imx6/debian/sid/run/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
@implementation NSDateFormatter (YCYMake)
+(NSDateFormatter *)ycy_dateFormatterWithFormat:(NSString *)format {
return [self ycy_dateFormatterWithFormat:format timeZone:nil];
}
+(NSDateFormatter *)ycy_dateFormatterWithFormat:(NSString *)format timeZone:(NSTimeZone *)timeZone {
return [self ycy_dateFormatterWithFormat:format timeZone:timeZone locale:nil];
}
+(NSDateFormatter *)ycy_dateFormatterWithFormat:(NSString *)format timeZone:(NSTimeZone *)timeZone locale:(NSLocale *)locale {
if (format == nil || [format isEqualToString:@""]) return nil;
NSString *key = [NSString stringWithFormat:@"NSDateFormatter-tz-%@-fmt-%@-loc-%@", [timeZone abbreviation], format, [locale localeIdentifier]];
NSMutableDictionary* dictionary = [[NSThread currentThread] threadDictionary];
NSDateFormatter* dateFormatter = [dictionary objectForKey:key];
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:format];
[dictionary setObject:dateFormatter forKey:key];
#if !__has_feature(objc_arc)
[dateFormatter autorelease];
#endif
}
if (locale != nil) [dateFormatter setLocale:locale]; // this may change so don't cache
if (timeZone != nil) [dateFormatter setTimeZone:timeZone]; // this may change
return dateFormatter;
}
+(NSDateFormatter *)ycy_dateFormatterWithDateStyle:(NSDateFormatterStyle)style {
return [self ycy_dateFormatterWithDateStyle:style timeZone:nil];
}
+(NSDateFormatter *)ycy_dateFormatterWithDateStyle:(NSDateFormatterStyle)style timeZone:(NSTimeZone *)timeZone {
NSString *key = [NSString stringWithFormat:@"NSDateFormatter-%@-dateStyle-%d", [timeZone abbreviation], (int)style];
NSMutableDictionary* dictionary = [[NSThread currentThread] threadDictionary];
NSDateFormatter* dateFormatter = [dictionary objectForKey:key];
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:style];
[dictionary setObject:dateFormatter forKey:key];
#if !__has_feature(objc_arc)
[dateFormatter autorelease];
#endif
}
if (timeZone != nil) [dateFormatter setTimeZone:timeZone]; // this may change so don't cache
return dateFormatter;
}
+(NSDateFormatter *)ycy_dateFormatterWithTimeStyle:(NSDateFormatterStyle)style {
return [self ycy_dateFormatterWithTimeStyle:style timeZone:nil];
}
+(NSDateFormatter *)ycy_dateFormatterWithTimeStyle:(NSDateFormatterStyle)style timeZone:(NSTimeZone *)timeZone {
NSString *key = [NSString stringWithFormat:@"NSDateFormatter-%@-timeStyle-%d", [timeZone abbreviation], (int)style];
NSMutableDictionary* dictionary = [[NSThread currentThread] threadDictionary];
NSDateFormatter* dateFormatter = [dictionary objectForKey:key];
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:style];
[dictionary setObject:dateFormatter forKey:key];
#if !__has_feature(objc_arc)
[dateFormatter autorelease];
#endif
}
if (timeZone != nil) [dateFormatter setTimeZone:timeZone]; // this may change so don't cache
return dateFormatter;
}
@end
| {
"content_hash": "f530c224323a5cc17035e75f4bc9caf6",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 147,
"avg_line_length": 47.776119402985074,
"alnum_prop": 0.7353951890034365,
"repo_name": "CattleToCoaxStudio/YCYToolKit",
"id": "478da49d240f85065867aeea096ab265bca58b49",
"size": "3385",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "YCYToolKit/YCYCategories/Foundation/NSDateFormatter/NSDateFormatter+YCYMake.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "1072600"
},
{
"name": "Ruby",
"bytes": "8129"
}
],
"symlink_target": ""
} |
#include "extractor/guidance/turn_instruction.hpp"
#include "engine/plugins/plugin_base.hpp"
#include "engine/plugins/tile.hpp"
#include "util/coordinate_calculation.hpp"
#include "util/string_view.hpp"
#include "util/vector_tile.hpp"
#include "util/web_mercator.hpp"
#include "engine/api/json_factory.hpp"
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/multi/geometries/multi_linestring.hpp>
#include <protozero/pbf_writer.hpp>
#include <protozero/varint.hpp>
#include <algorithm>
#include <numeric>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <cmath>
#include <cstdint>
namespace osrm
{
namespace engine
{
namespace plugins
{
constexpr const static int MIN_ZOOM_FOR_TURNS = 15;
namespace
{
// Creates an indexed lookup table for values - used to encoded the vector tile
// which uses a lookup table and index pointers for encoding
template <typename T> struct ValueIndexer
{
private:
std::vector<T> used_values;
std::unordered_map<T, std::size_t> value_offsets;
public:
std::size_t add(const T &value)
{
const auto found = value_offsets.find(value);
std::size_t offset;
if (found == value_offsets.end())
{
used_values.push_back(value);
offset = used_values.size() - 1;
value_offsets[value] = offset;
}
else
{
offset = found->second;
}
return offset;
}
std::size_t indexOf(const T &value) { return value_offsets[value]; }
const std::vector<T> &values() { return used_values; }
std::size_t size() const { return used_values.size(); }
};
using RTreeLeaf = datafacade::BaseDataFacade::RTreeLeaf;
// TODO: Port all this encoding logic to https://github.com/mapbox/vector-tile, which wasn't
// available when this code was originally written.
// Simple container class for WGS84 coordinates
template <typename T> struct Point final
{
Point(T _x, T _y) : x(_x), y(_y) {}
const T x;
const T y;
};
// Simple container to hold a bounding box
struct BBox final
{
BBox(const double _minx, const double _miny, const double _maxx, const double _maxy)
: minx(_minx), miny(_miny), maxx(_maxx), maxy(_maxy)
{
}
double width() const { return maxx - minx; }
double height() const { return maxy - miny; }
const double minx;
const double miny;
const double maxx;
const double maxy;
};
// Simple container for integer coordinates (i.e. pixel coords)
struct point_type_i final
{
point_type_i(std::int64_t _x, std::int64_t _y) : x(_x), y(_y) {}
const std::int64_t x;
const std::int64_t y;
};
using FixedPoint = Point<std::int32_t>;
using FloatPoint = Point<double>;
using FixedLine = std::vector<FixedPoint>;
using FloatLine = std::vector<FloatPoint>;
// We use boost::geometry to clip lines/points that are outside or cross the boundary
// of the tile we're rendering. We need these types defined to use boosts clipping
// logic
typedef boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian> point_t;
typedef boost::geometry::model::linestring<point_t> linestring_t;
typedef boost::geometry::model::box<point_t> box_t;
typedef boost::geometry::model::multi_linestring<linestring_t> multi_linestring_t;
const static box_t clip_box(point_t(-util::vector_tile::BUFFER, -util::vector_tile::BUFFER),
point_t(util::vector_tile::EXTENT + util::vector_tile::BUFFER,
util::vector_tile::EXTENT + util::vector_tile::BUFFER));
// from mapnik-vector-tile
// Encodes a linestring using protobuf zigzag encoding
inline bool encodeLinestring(const FixedLine &line,
protozero::packed_field_uint32 &geometry,
std::int32_t &start_x,
std::int32_t &start_y)
{
const std::size_t line_size = line.size();
if (line_size < 2)
{
return false;
}
const unsigned lineto_count = static_cast<const unsigned>(line_size) - 1;
auto pt = line.begin();
const constexpr int MOVETO_COMMAND = 9;
geometry.add_element(MOVETO_COMMAND); // move_to | (1 << 3)
geometry.add_element(protozero::encode_zigzag32(pt->x - start_x));
geometry.add_element(protozero::encode_zigzag32(pt->y - start_y));
start_x = pt->x;
start_y = pt->y;
// This means LINETO repeated N times
// See: https://github.com/mapbox/vector-tile-spec/tree/master/2.1#example-command-integers
geometry.add_element((lineto_count << 3u) | 2u);
// Now that we've issued the LINETO REPEAT N command, we append
// N coordinate pairs immediately after the command.
for (++pt; pt != line.end(); ++pt)
{
const std::int32_t dx = pt->x - start_x;
const std::int32_t dy = pt->y - start_y;
geometry.add_element(protozero::encode_zigzag32(dx));
geometry.add_element(protozero::encode_zigzag32(dy));
start_x = pt->x;
start_y = pt->y;
}
return true;
}
// from mapnik-vctor-tile
// Encodes a point
inline void encodePoint(const FixedPoint &pt, protozero::packed_field_uint32 &geometry)
{
const constexpr int MOVETO_COMMAND = 9;
geometry.add_element(MOVETO_COMMAND);
const std::int32_t dx = pt.x;
const std::int32_t dy = pt.y;
// Manual zigzag encoding.
geometry.add_element(protozero::encode_zigzag32(dx));
geometry.add_element(protozero::encode_zigzag32(dy));
}
linestring_t floatLineToTileLine(const FloatLine &geo_line, const BBox &tile_bbox)
{
linestring_t unclipped_line;
for (auto const &pt : geo_line)
{
double px_merc = pt.x * util::web_mercator::DEGREE_TO_PX;
double py_merc = util::web_mercator::latToY(util::FloatLatitude{pt.y}) *
util::web_mercator::DEGREE_TO_PX;
// convert lon/lat to tile coordinates
const auto px = std::round(
((px_merc - tile_bbox.minx) * util::web_mercator::TILE_SIZE / tile_bbox.width()) *
util::vector_tile::EXTENT / util::web_mercator::TILE_SIZE);
const auto py = std::round(
((tile_bbox.maxy - py_merc) * util::web_mercator::TILE_SIZE / tile_bbox.height()) *
util::vector_tile::EXTENT / util::web_mercator::TILE_SIZE);
boost::geometry::append(unclipped_line, point_t(px, py));
}
return unclipped_line;
}
std::vector<FixedLine> coordinatesToTileLine(const std::vector<util::Coordinate> &points,
const BBox &tile_bbox)
{
FloatLine geo_line;
for (auto const &c : points)
{
geo_line.emplace_back(static_cast<double>(util::toFloating(c.lon)),
static_cast<double>(util::toFloating(c.lat)));
}
linestring_t unclipped_line = floatLineToTileLine(geo_line, tile_bbox);
multi_linestring_t clipped_line;
boost::geometry::intersection(clip_box, unclipped_line, clipped_line);
std::vector<FixedLine> result;
// b::g::intersection might return a line with one point if the
// original line was very short and coords were dupes
for (auto const &cl : clipped_line)
{
if (cl.size() < 2)
continue;
FixedLine tile_line;
for (const auto &p : cl)
tile_line.emplace_back(p.get<0>(), p.get<1>());
result.emplace_back(std::move(tile_line));
}
return result;
}
/**
* Return the x1,y1,x2,y2 pixel coordinates of a line in a given
* tile.
*
* @param start the first coordinate of the line
* @param target the last coordinate of the line
* @param tile_bbox the boundaries of the tile, in mercator coordinates
* @return a FixedLine with coordinates relative to the tile_bbox.
*/
FixedLine coordinatesToTileLine(const util::Coordinate start,
const util::Coordinate target,
const BBox &tile_bbox)
{
FloatLine geo_line;
geo_line.emplace_back(static_cast<double>(util::toFloating(start.lon)),
static_cast<double>(util::toFloating(start.lat)));
geo_line.emplace_back(static_cast<double>(util::toFloating(target.lon)),
static_cast<double>(util::toFloating(target.lat)));
linestring_t unclipped_line = floatLineToTileLine(geo_line, tile_bbox);
multi_linestring_t clipped_line;
boost::geometry::intersection(clip_box, unclipped_line, clipped_line);
FixedLine tile_line;
// b::g::intersection might return a line with one point if the
// original line was very short and coords were dupes
if (!clipped_line.empty() && clipped_line[0].size() == 2)
{
for (const auto &p : clipped_line[0])
{
tile_line.emplace_back(p.get<0>(), p.get<1>());
}
}
return tile_line;
}
/**
* Converts lon/lat into coordinates inside a Mercator projection tile (x/y pixel values)
*
* @param point the lon/lat you want the tile coords for
* @param tile_bbox the mercator boundaries of the tile
* @return a point (x,y) on the tile defined by tile_bbox
*/
FixedPoint coordinatesToTilePoint(const util::Coordinate point, const BBox &tile_bbox)
{
const FloatPoint geo_point{static_cast<double>(util::toFloating(point.lon)),
static_cast<double>(util::toFloating(point.lat))};
const double px_merc = geo_point.x * util::web_mercator::DEGREE_TO_PX;
const double py_merc = util::web_mercator::latToY(util::FloatLatitude{geo_point.y}) *
util::web_mercator::DEGREE_TO_PX;
const auto px = static_cast<std::int32_t>(std::round(
((px_merc - tile_bbox.minx) * util::web_mercator::TILE_SIZE / tile_bbox.width()) *
util::vector_tile::EXTENT / util::web_mercator::TILE_SIZE));
const auto py = static_cast<std::int32_t>(std::round(
((tile_bbox.maxy - py_merc) * util::web_mercator::TILE_SIZE / tile_bbox.height()) *
util::vector_tile::EXTENT / util::web_mercator::TILE_SIZE));
return FixedPoint{px, py};
}
std::vector<RTreeLeaf> getEdges(const DataFacadeBase &facade, unsigned x, unsigned y, unsigned z)
{
double min_lon, min_lat, max_lon, max_lat;
// Convert the z,x,y mercator tile coordinates into WGS84 lon/lat values
//
util::web_mercator::xyzToWGS84(
x, y, z, min_lon, min_lat, max_lon, max_lat, util::web_mercator::TILE_SIZE * 0.10);
util::Coordinate southwest{util::FloatLongitude{min_lon}, util::FloatLatitude{min_lat}};
util::Coordinate northeast{util::FloatLongitude{max_lon}, util::FloatLatitude{max_lat}};
// Fetch all the segments that are in our bounding box.
// This hits the OSRM StaticRTree
return facade.GetEdgesInBox(southwest, northeast);
}
std::vector<std::size_t> getEdgeIndex(const std::vector<RTreeLeaf> &edges)
{
// In order to ensure consistent tile encoding, we need to process
// all edges in the same order. Differences in OSX/Linux/Windows
// sorting methods mean that GetEdgesInBox doesn't return the same
// ordered array on all platforms.
// GetEdgesInBox is marked `const`, so we can't sort the array itself,
// instead we create an array of indexes and sort that instead.
std::vector<std::size_t> sorted_edge_indexes(edges.size(), 0);
std::iota(
sorted_edge_indexes.begin(), sorted_edge_indexes.end(), 0); // fill with 0,1,2,3,...N-1
// Now, sort that array based on the edges list, using the u/v node IDs
// as the sort condition
std::sort(sorted_edge_indexes.begin(),
sorted_edge_indexes.end(),
[&edges](const std::size_t &left, const std::size_t &right) -> bool {
return (edges[left].u != edges[right].u) ? edges[left].u < edges[right].u
: edges[left].v < edges[right].v;
});
return sorted_edge_indexes;
}
std::vector<NodeID> getSegregatedNodes(const DataFacadeBase &facade,
const std::vector<RTreeLeaf> &edges)
{
std::vector<NodeID> result;
for (RTreeLeaf const &e : edges)
{
if (e.forward_segment_id.enabled && facade.IsSegregated(e.forward_segment_id.id))
result.push_back(e.forward_segment_id.id);
}
return result;
}
void encodeVectorTile(const DataFacadeBase &facade,
unsigned x,
unsigned y,
unsigned z,
const std::vector<RTreeLeaf> &edges,
const std::vector<std::size_t> &sorted_edge_indexes,
const std::vector<routing_algorithms::TurnData> &all_turn_data,
const std::vector<NodeID> &segregated_nodes,
std::string &pbf_buffer)
{
std::uint8_t max_datasource_id = 0;
// Vector tiles encode properties on features as indexes into a layer-specific
// lookup table. These ValueIndexer's act as memoizers for values as we discover
// them during edge explioration, and are then used to generate the lookup
// tables for each tile layer.
ValueIndexer<int> line_int_index;
ValueIndexer<util::StringView> line_string_index;
ValueIndexer<int> point_int_index;
ValueIndexer<float> point_float_index;
ValueIndexer<std::string> point_string_index;
const auto get_geometry_id = [&facade](auto edge) {
return facade.GetGeometryIndex(edge.forward_segment_id.id).id;
};
// Vector tiles encode feature properties as indexes into a lookup table. So, we need
// to "pre-loop" over all the edges to create the lookup tables. Once we have those, we
// can then encode the features, and we'll know the indexes that feature properties
// need to refer to.
for (const auto &edge_index : sorted_edge_indexes)
{
const auto &edge = edges[edge_index];
const auto geometry_id = get_geometry_id(edge);
const auto forward_datasource_vector =
facade.GetUncompressedForwardDatasources(geometry_id);
const auto reverse_datasource_vector =
facade.GetUncompressedReverseDatasources(geometry_id);
BOOST_ASSERT(edge.fwd_segment_position < forward_datasource_vector.size());
const auto forward_datasource = forward_datasource_vector[edge.fwd_segment_position];
BOOST_ASSERT(edge.fwd_segment_position < reverse_datasource_vector.size());
const auto reverse_datasource = reverse_datasource_vector[reverse_datasource_vector.size() -
edge.fwd_segment_position - 1];
// Keep track of the highest datasource seen so that we don't write unnecessary
// data to the layer attribute values
max_datasource_id = std::max(max_datasource_id, forward_datasource);
max_datasource_id = std::max(max_datasource_id, reverse_datasource);
}
// Convert tile coordinates into mercator coordinates
double min_mercator_lon, min_mercator_lat, max_mercator_lon, max_mercator_lat;
util::web_mercator::xyzToMercator(
x, y, z, min_mercator_lon, min_mercator_lat, max_mercator_lon, max_mercator_lat);
const BBox tile_bbox{min_mercator_lon, min_mercator_lat, max_mercator_lon, max_mercator_lat};
// Protobuf serializes blocks when objects go out of scope, hence
// the extra scoping below.
protozero::pbf_writer tile_writer{pbf_buffer};
{
{
// Add a layer object to the PBF stream. 3=='layer' from the vector tile spec
// (2.1)
protozero::pbf_writer line_layer_writer(tile_writer, util::vector_tile::LAYER_TAG);
// TODO: don't write a layer if there are no features
line_layer_writer.add_uint32(util::vector_tile::VERSION_TAG, 2); // version
// Field 1 is the "layer name" field, it's a string
line_layer_writer.add_string(util::vector_tile::NAME_TAG, "speeds"); // name
// Field 5 is the tile extent. It's a uint32 and should be set to 4096
// for normal vector tiles.
line_layer_writer.add_uint32(util::vector_tile::EXTENT_TAG,
util::vector_tile::EXTENT); // extent
// Because we need to know the indexes into the vector tile lookup table,
// we need to do an initial pass over the data and create the complete
// index of used values.
for (const auto &edge_index : sorted_edge_indexes)
{
const auto &edge = edges[edge_index];
const auto geometry_id = get_geometry_id(edge);
// Get coordinates for start/end nodes of segment (NodeIDs u and v)
const auto a = facade.GetCoordinateOfNode(edge.u);
const auto b = facade.GetCoordinateOfNode(edge.v);
// Calculate the length in meters
const double length = osrm::util::coordinate_calculation::haversineDistance(a, b);
// Weight values
const auto forward_weight_vector =
facade.GetUncompressedForwardWeights(geometry_id);
const auto reverse_weight_vector =
facade.GetUncompressedReverseWeights(geometry_id);
const auto forward_weight = forward_weight_vector[edge.fwd_segment_position];
const auto reverse_weight = reverse_weight_vector[reverse_weight_vector.size() -
edge.fwd_segment_position - 1];
line_int_index.add(forward_weight);
line_int_index.add(reverse_weight);
std::uint32_t forward_rate =
static_cast<std::uint32_t>(round(length / forward_weight * 10.));
std::uint32_t reverse_rate =
static_cast<std::uint32_t>(round(length / reverse_weight * 10.));
line_int_index.add(forward_rate);
line_int_index.add(reverse_rate);
// Duration values
const auto forward_duration_vector =
facade.GetUncompressedForwardDurations(geometry_id);
const auto reverse_duration_vector =
facade.GetUncompressedReverseDurations(geometry_id);
const auto forward_duration = forward_duration_vector[edge.fwd_segment_position];
const auto reverse_duration =
reverse_duration_vector[reverse_duration_vector.size() -
edge.fwd_segment_position - 1];
line_int_index.add(forward_duration);
line_int_index.add(reverse_duration);
}
// Begin the layer features block
{
// Each feature gets a unique id, starting at 1
unsigned id = 1;
for (const auto &edge_index : sorted_edge_indexes)
{
const auto &edge = edges[edge_index];
const auto geometry_id = get_geometry_id(edge);
// Get coordinates for start/end nodes of segment (NodeIDs u and v)
const auto a = facade.GetCoordinateOfNode(edge.u);
const auto b = facade.GetCoordinateOfNode(edge.v);
// Calculate the length in meters
const double length =
osrm::util::coordinate_calculation::haversineDistance(a, b);
const auto forward_weight_vector =
facade.GetUncompressedForwardWeights(geometry_id);
const auto reverse_weight_vector =
facade.GetUncompressedReverseWeights(geometry_id);
const auto forward_duration_vector =
facade.GetUncompressedForwardDurations(geometry_id);
const auto reverse_duration_vector =
facade.GetUncompressedReverseDurations(geometry_id);
const auto forward_datasource_vector =
facade.GetUncompressedForwardDatasources(geometry_id);
const auto reverse_datasource_vector =
facade.GetUncompressedReverseDatasources(geometry_id);
const auto forward_weight = forward_weight_vector[edge.fwd_segment_position];
const auto reverse_weight =
reverse_weight_vector[reverse_weight_vector.size() -
edge.fwd_segment_position - 1];
const auto forward_duration =
forward_duration_vector[edge.fwd_segment_position];
const auto reverse_duration =
reverse_duration_vector[reverse_duration_vector.size() -
edge.fwd_segment_position - 1];
const auto forward_datasource_idx =
forward_datasource_vector[edge.fwd_segment_position];
const auto reverse_datasource_idx =
reverse_datasource_vector[reverse_datasource_vector.size() -
edge.fwd_segment_position - 1];
const auto component_id = facade.GetComponentID(edge.forward_segment_id.id);
const auto name_id = facade.GetNameIndex(edge.forward_segment_id.id);
auto name = facade.GetNameForID(name_id);
line_string_index.add(name);
const auto encode_tile_line = [&line_layer_writer,
&edge,
&component_id,
&id,
&max_datasource_id,
&line_int_index](
const FixedLine &tile_line,
const std::uint32_t speed_kmh_idx,
const std::uint32_t rate_idx,
const std::size_t weight_idx,
const std::size_t duration_idx,
const DatasourceID datasource_idx,
const std::size_t name_idx,
std::int32_t &start_x,
std::int32_t &start_y) {
// Here, we save the two attributes for our feature: the speed and
// the is_small boolean. We only serve up speeds from 0-139, so all we
// do is save the first
protozero::pbf_writer feature_writer(line_layer_writer,
util::vector_tile::FEATURE_TAG);
// Field 3 is the "geometry type" field. Value 2 is "line"
feature_writer.add_enum(
util::vector_tile::GEOMETRY_TAG,
util::vector_tile::GEOMETRY_TYPE_LINE); // geometry type
// Field 1 for the feature is the "id" field.
feature_writer.add_uint64(util::vector_tile::ID_TAG, id++); // id
{
// When adding attributes to a feature, we have to write
// pairs of numbers. The first value is the index in the
// keys array (written later), and the second value is the
// index into the "values" array (also written later). We're
// not writing the actual speed or bool value here, we're saving
// an index into the "values" array. This means many features
// can share the same value data, leading to smaller tiles.
protozero::packed_field_uint32 field(
feature_writer, util::vector_tile::FEATURE_ATTRIBUTES_TAG);
field.add_element(0); // "speed" tag key offset
field.add_element(std::min(
speed_kmh_idx, 127u)); // save the speed value, capped at 127
field.add_element(1); // "is_small" tag key offset
field.add_element(
128 + (component_id.is_tiny ? 0 : 1)); // is_small feature offset
field.add_element(2); // "datasource" tag key offset
field.add_element(130 + datasource_idx); // datasource value offset
field.add_element(3); // "weight" tag key offset
field.add_element(130 + max_datasource_id + 1 +
weight_idx); // weight value offset
field.add_element(4); // "duration" tag key offset
field.add_element(130 + max_datasource_id + 1 +
duration_idx); // duration value offset
field.add_element(5); // "name" tag key offset
field.add_element(130 + max_datasource_id + 1 +
line_int_index.values().size() + name_idx);
field.add_element(6); // rate tag key offset
field.add_element(130 + max_datasource_id + 1 + rate_idx);
}
{
// Encode the geometry for the feature
protozero::packed_field_uint32 geometry(
feature_writer, util::vector_tile::FEATURE_GEOMETRIES_TAG);
encodeLinestring(tile_line, geometry, start_x, start_y);
}
};
// If this is a valid forward edge, go ahead and add it to the tile
if (forward_duration != 0 && edge.forward_segment_id.enabled)
{
std::int32_t start_x = 0;
std::int32_t start_y = 0;
// Calculate the speed for this line
// Speeds are looked up in a simple 1:1 table, so the speed value == lookup
// table index
std::uint32_t speed_kmh_idx =
static_cast<std::uint32_t>(round(length / forward_duration * 10 * 3.6));
// Rate values are in meters per weight-unit - and similar to speeds, we
// present 1 decimal place of precision (these values are added as
// double/10) lower down
std::uint32_t forward_rate =
static_cast<std::uint32_t>(round(length / forward_weight * 10.));
auto tile_line = coordinatesToTileLine(a, b, tile_bbox);
if (!tile_line.empty())
{
encode_tile_line(tile_line,
speed_kmh_idx,
line_int_index.indexOf(forward_rate),
line_int_index.indexOf(forward_weight),
line_int_index.indexOf(forward_duration),
forward_datasource_idx,
line_string_index.indexOf(name),
start_x,
start_y);
}
}
// Repeat the above for the coordinates reversed and using the `reverse`
// properties
if (reverse_duration != 0 && edge.reverse_segment_id.enabled)
{
std::int32_t start_x = 0;
std::int32_t start_y = 0;
// Calculate the speed for this line
// Speeds are looked up in a simple 1:1 table, so the speed value == lookup
// table index
std::uint32_t speed_kmh_idx =
static_cast<std::uint32_t>(round(length / reverse_duration * 10 * 3.6));
// Rate values are in meters per weight-unit - and similar to speeds, we
// present 1 decimal place of precision (these values are added as
// double/10) lower down
std::uint32_t reverse_rate =
static_cast<std::uint32_t>(round(length / reverse_weight * 10.));
auto tile_line = coordinatesToTileLine(b, a, tile_bbox);
if (!tile_line.empty())
{
encode_tile_line(tile_line,
speed_kmh_idx,
line_int_index.indexOf(reverse_rate),
line_int_index.indexOf(reverse_weight),
line_int_index.indexOf(reverse_duration),
reverse_datasource_idx,
line_string_index.indexOf(name),
start_x,
start_y);
}
}
}
}
// Field id 3 is the "keys" attribute
// We need two "key" fields, these are referred to with 0 and 1 (their array
// indexes) earlier
line_layer_writer.add_string(util::vector_tile::KEY_TAG, "speed");
line_layer_writer.add_string(util::vector_tile::KEY_TAG, "is_small");
line_layer_writer.add_string(util::vector_tile::KEY_TAG, "datasource");
line_layer_writer.add_string(util::vector_tile::KEY_TAG, "weight");
line_layer_writer.add_string(util::vector_tile::KEY_TAG, "duration");
line_layer_writer.add_string(util::vector_tile::KEY_TAG, "name");
line_layer_writer.add_string(util::vector_tile::KEY_TAG, "rate");
// Now, we write out the possible speed value arrays and possible is_tiny
// values. Field type 4 is the "values" field. It's a variable type field,
// so requires a two-step write (create the field, then write its value)
for (std::size_t i = 0; i < 128; i++)
{
// Writing field type 4 == variant type
protozero::pbf_writer values_writer(line_layer_writer,
util::vector_tile::VARIANT_TAG);
// Attribute value 5 == uint64 type
values_writer.add_uint64(util::vector_tile::VARIANT_TYPE_UINT64, i);
}
{
protozero::pbf_writer values_writer(line_layer_writer,
util::vector_tile::VARIANT_TAG);
// Attribute value 7 == bool type
values_writer.add_bool(util::vector_tile::VARIANT_TYPE_BOOL, true);
}
{
protozero::pbf_writer values_writer(line_layer_writer,
util::vector_tile::VARIANT_TAG);
// Attribute value 7 == bool type
values_writer.add_bool(util::vector_tile::VARIANT_TYPE_BOOL, false);
}
for (std::size_t i = 0; i <= max_datasource_id; i++)
{
// Writing field type 4 == variant type
protozero::pbf_writer values_writer(line_layer_writer,
util::vector_tile::VARIANT_TAG);
// Attribute value 1 == string type
values_writer.add_string(util::vector_tile::VARIANT_TYPE_STRING,
facade.GetDatasourceName(i).to_string());
}
for (auto value : line_int_index.values())
{
// Writing field type 4 == variant type
protozero::pbf_writer values_writer(line_layer_writer,
util::vector_tile::VARIANT_TAG);
// Attribute value 2 == float type
// Durations come out of OSRM in integer deciseconds, so we convert them
// to seconds with a simple /10 for display
values_writer.add_double(util::vector_tile::VARIANT_TYPE_DOUBLE, value / 10.);
}
for (const auto &name : line_string_index.values())
{
// Writing field type 4 == variant type
protozero::pbf_writer values_writer(line_layer_writer,
util::vector_tile::VARIANT_TAG);
// Attribute value 1 == string type
values_writer.add_string(
util::vector_tile::VARIANT_TYPE_STRING, name.data(), name.size());
}
}
// Only add the turn layer to the tile if it has some features (we sometimes won't
// for tiles of z<16, and tiles that don't show any intersections)
if (!all_turn_data.empty())
{
struct EncodedTurnData
{
util::Coordinate coordinate;
std::size_t angle_index;
std::size_t turn_index;
std::size_t duration_index;
std::size_t weight_index;
std::size_t turntype_index;
std::size_t turnmodifier_index;
};
// we need to pre-encode all values here because we need the full offsets later
// for encoding the actual features.
std::vector<EncodedTurnData> encoded_turn_data(all_turn_data.size());
std::transform(
all_turn_data.begin(),
all_turn_data.end(),
encoded_turn_data.begin(),
[&](const routing_algorithms::TurnData &t) {
auto angle_idx = point_int_index.add(t.in_angle);
auto turn_idx = point_int_index.add(t.turn_angle);
auto duration_idx =
point_float_index.add(t.duration / 10.0); // Note conversion to float here
auto weight_idx =
point_float_index.add(t.weight / 10.0); // Note conversion to float here
auto turntype_idx =
point_string_index.add(extractor::guidance::internalInstructionTypeToString(
t.turn_instruction.type));
auto turnmodifier_idx =
point_string_index.add(extractor::guidance::instructionModifierToString(
t.turn_instruction.direction_modifier));
return EncodedTurnData{t.coordinate,
angle_idx,
turn_idx,
duration_idx,
weight_idx,
turntype_idx,
turnmodifier_idx};
});
// Now write the points layer for turn penalty data:
// Add a layer object to the PBF stream. 3=='layer' from the vector tile spec
// (2.1)
protozero::pbf_writer point_layer_writer(tile_writer, util::vector_tile::LAYER_TAG);
point_layer_writer.add_uint32(util::vector_tile::VERSION_TAG, 2); // version
point_layer_writer.add_string(util::vector_tile::NAME_TAG, "turns"); // name
point_layer_writer.add_uint32(util::vector_tile::EXTENT_TAG,
util::vector_tile::EXTENT); // extent
// Begin writing the set of point features
{
// Start each features with an ID starting at 1
int id = 1;
// Helper function to encode a new point feature on a vector tile.
const auto encode_tile_point = [&](const FixedPoint &tile_point,
const auto &point_turn_data) {
protozero::pbf_writer feature_writer(point_layer_writer,
util::vector_tile::FEATURE_TAG);
// Field 3 is the "geometry type" field. Value 1 is "point"
feature_writer.add_enum(
util::vector_tile::GEOMETRY_TAG,
util::vector_tile::GEOMETRY_TYPE_POINT); // geometry type
feature_writer.add_uint64(util::vector_tile::ID_TAG, id++); // id
{
// Write out the 4 properties we want on the feature. These
// refer to indexes in the properties lookup table, which we
// add to the tile after we add all features.
protozero::packed_field_uint32 field(
feature_writer, util::vector_tile::FEATURE_ATTRIBUTES_TAG);
field.add_element(0); // "bearing_in" tag key offset
field.add_element(point_turn_data.angle_index);
field.add_element(1); // "turn_angle" tag key offset
field.add_element(point_turn_data.turn_index);
field.add_element(2); // "cost" tag key offset
field.add_element(point_int_index.size() + point_turn_data.duration_index);
field.add_element(3); // "weight" tag key offset
field.add_element(point_int_index.size() + point_turn_data.weight_index);
field.add_element(4); // "type" tag key offset
field.add_element(point_int_index.size() + point_float_index.size() +
point_turn_data.turntype_index);
field.add_element(5); // "modifier" tag key offset
field.add_element(point_int_index.size() + point_float_index.size() +
point_turn_data.turnmodifier_index);
}
{
// Add the geometry as the last field in this feature
protozero::packed_field_uint32 geometry(
feature_writer, util::vector_tile::FEATURE_GEOMETRIES_TAG);
encodePoint(tile_point, geometry);
}
};
// Loop over all the turns we found and add them as features to the layer
for (const auto &turndata : encoded_turn_data)
{
const auto tile_point = coordinatesToTilePoint(turndata.coordinate, tile_bbox);
if (!boost::geometry::within(point_t(tile_point.x, tile_point.y), clip_box))
{
continue;
}
encode_tile_point(tile_point, turndata);
}
}
// Add the names of the three attributes we added to all the turn penalty
// features previously. The indexes used there refer to these keys.
point_layer_writer.add_string(util::vector_tile::KEY_TAG, "bearing_in");
point_layer_writer.add_string(util::vector_tile::KEY_TAG, "turn_angle");
point_layer_writer.add_string(util::vector_tile::KEY_TAG, "cost");
point_layer_writer.add_string(util::vector_tile::KEY_TAG, "weight");
point_layer_writer.add_string(util::vector_tile::KEY_TAG, "type");
point_layer_writer.add_string(util::vector_tile::KEY_TAG, "modifier");
// Now, save the lists of integers and floats that our features refer to.
for (const auto &value : point_int_index.values())
{
protozero::pbf_writer values_writer(point_layer_writer,
util::vector_tile::VARIANT_TAG);
values_writer.add_sint64(util::vector_tile::VARIANT_TYPE_SINT64, value);
}
for (const auto &value : point_float_index.values())
{
protozero::pbf_writer values_writer(point_layer_writer,
util::vector_tile::VARIANT_TAG);
values_writer.add_float(util::vector_tile::VARIANT_TYPE_FLOAT, value);
}
for (const auto &value : point_string_index.values())
{
protozero::pbf_writer values_writer(point_layer_writer,
util::vector_tile::VARIANT_TAG);
values_writer.add_string(util::vector_tile::VARIANT_TYPE_STRING, value);
}
}
// OSM Node tile layer
{
protozero::pbf_writer point_layer_writer(tile_writer, util::vector_tile::LAYER_TAG);
point_layer_writer.add_uint32(util::vector_tile::VERSION_TAG, 2); // version
point_layer_writer.add_string(util::vector_tile::NAME_TAG, "osmnodes"); // name
point_layer_writer.add_uint32(util::vector_tile::EXTENT_TAG,
util::vector_tile::EXTENT); // extent
std::vector<NodeID> internal_nodes;
internal_nodes.reserve(edges.size() * 2);
for (const auto &edge : edges)
{
internal_nodes.push_back(edge.u);
internal_nodes.push_back(edge.v);
}
std::sort(internal_nodes.begin(), internal_nodes.end());
auto new_end = std::unique(internal_nodes.begin(), internal_nodes.end());
internal_nodes.resize(new_end - internal_nodes.begin());
for (const auto &internal_node : internal_nodes)
{
const auto coord = facade.GetCoordinateOfNode(internal_node);
const auto tile_point = coordinatesToTilePoint(coord, tile_bbox);
if (!boost::geometry::within(point_t(tile_point.x, tile_point.y), clip_box))
{
continue;
}
protozero::pbf_writer feature_writer(point_layer_writer,
util::vector_tile::FEATURE_TAG);
// Field 3 is the "geometry type" field. Value 1 is "point"
feature_writer.add_enum(util::vector_tile::GEOMETRY_TAG,
util::vector_tile::GEOMETRY_TYPE_POINT); // geometry type
const auto osmid =
static_cast<OSMNodeID::value_type>(facade.GetOSMNodeIDOfNode(internal_node));
feature_writer.add_uint64(util::vector_tile::ID_TAG, osmid); // id
// There are no additional properties, just the ID and the geometry
{
// Add the geometry as the last field in this feature
protozero::packed_field_uint32 geometry(
feature_writer, util::vector_tile::FEATURE_GEOMETRIES_TAG);
encodePoint(tile_point, geometry);
}
}
}
{
protozero::pbf_writer line_layer_writer(tile_writer, util::vector_tile::LAYER_TAG);
line_layer_writer.add_uint32(util::vector_tile::VERSION_TAG, 2); // version
line_layer_writer.add_string(util::vector_tile::NAME_TAG, "internal-nodes"); // name
line_layer_writer.add_uint32(util::vector_tile::EXTENT_TAG,
util::vector_tile::EXTENT); // extent
unsigned id = 0;
for (auto edgeNodeID : segregated_nodes)
{
auto const geomIndex = facade.GetGeometryIndex(edgeNodeID);
std::vector<NodeID> geometry;
if (geomIndex.forward)
geometry = facade.GetUncompressedForwardGeometry(geomIndex.id);
else
geometry = facade.GetUncompressedReverseGeometry(geomIndex.id);
std::vector<util::Coordinate> points;
for (auto const nodeID : geometry)
points.push_back(facade.GetCoordinateOfNode(nodeID));
const auto encode_tile_line = [&line_layer_writer, &id](
const FixedLine &tile_line, std::int32_t &start_x, std::int32_t &start_y) {
protozero::pbf_writer feature_writer(line_layer_writer,
util::vector_tile::FEATURE_TAG);
feature_writer.add_enum(util::vector_tile::GEOMETRY_TAG,
util::vector_tile::GEOMETRY_TYPE_LINE); // geometry type
feature_writer.add_uint64(util::vector_tile::ID_TAG, id++); // id
{
protozero::packed_field_uint32 field(
feature_writer, util::vector_tile::FEATURE_ATTRIBUTES_TAG);
}
{
// Encode the geometry for the feature
protozero::packed_field_uint32 geometry(
feature_writer, util::vector_tile::FEATURE_GEOMETRIES_TAG);
encodeLinestring(tile_line, geometry, start_x, start_y);
}
};
std::int32_t start_x = 0;
std::int32_t start_y = 0;
auto tile_lines = coordinatesToTileLine(points, tile_bbox);
if (!tile_lines.empty())
{
for (auto const &tl : tile_lines)
{
encode_tile_line(tl, start_x, start_y);
}
}
}
}
}
// protozero serializes data during object destructors, so once the scope closes,
// our result buffer will have all the tile data encoded into it.
}
}
Status TilePlugin::HandleRequest(const RoutingAlgorithmsInterface &algorithms,
const api::TileParameters ¶meters,
std::string &pbf_buffer) const
{
BOOST_ASSERT(parameters.IsValid());
const auto &facade = algorithms.GetFacade();
auto edges = getEdges(facade, parameters.x, parameters.y, parameters.z);
auto segregated_nodes = getSegregatedNodes(facade, edges);
auto edge_index = getEdgeIndex(edges);
std::vector<routing_algorithms::TurnData> turns;
// If we're zooming into 16 or higher, include turn data. Why? Because turns make the map
// really cramped, so we don't bother including the data for tiles that span a large area.
if (parameters.z >= MIN_ZOOM_FOR_TURNS && algorithms.HasGetTileTurns())
{
turns = algorithms.GetTileTurns(edges, edge_index);
}
encodeVectorTile(facade,
parameters.x,
parameters.y,
parameters.z,
edges,
edge_index,
turns,
segregated_nodes,
pbf_buffer);
return Status::Ok;
}
}
}
}
| {
"content_hash": "4f213fc2192052d19966751f956272af",
"timestamp": "",
"source": "github",
"line_count": 1023,
"max_line_length": 100,
"avg_line_length": 47.19843597262952,
"alnum_prop": 0.5366995277938862,
"repo_name": "KnockSoftware/osrm-backend",
"id": "965882c45c5aee561a6dd710c128f644c797436c",
"size": "48284",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/engine/plugins/tile.cpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "6637"
},
{
"name": "C++",
"bytes": "3385651"
},
{
"name": "CMake",
"bytes": "100275"
},
{
"name": "Gherkin",
"bytes": "1187226"
},
{
"name": "JavaScript",
"bytes": "205508"
},
{
"name": "Lua",
"bytes": "113019"
},
{
"name": "Makefile",
"bytes": "3170"
},
{
"name": "Python",
"bytes": "22224"
},
{
"name": "Shell",
"bytes": "15158"
}
],
"symlink_target": ""
} |
class SocialSearchRailsEngine::ContactsController < ApplicationController
before_action :check_key
skip_before_action :check_key, only: [:auth]
def check_key
p 'checking the key'
@token = session[:token]
if(@token.nil?)
render :json => { success: :false, message: 'You must login first. ' }.to_json
end
end
def auth
provider = params[:provider]
session[:token] = request.env["omniauth.auth"]["credentials"]["token"]
render :json => true
end
def search
search_term = params[:name]
users = Contact.search(search_term, @token)
render :json => { success: :true, payload: users }
end
def searchform
end
end | {
"content_hash": "597638ea6d584b5196b7b9e6cdbb4b0d",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 82,
"avg_line_length": 22.857142857142858,
"alnum_prop": 0.6921875,
"repo_name": "jbavari/SocialSearchRailsEngine",
"id": "4e4aa84964b02bdfa46926de2e6a2030943d5465",
"size": "640",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/social_search_rails_engine/contacts_controller.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1092"
},
{
"name": "JavaScript",
"bytes": "1198"
},
{
"name": "Ruby",
"bytes": "14760"
}
],
"symlink_target": ""
} |
/**
*/
var BOOKS = [
{
"title": "The Personal MBA",
"author": "Josh Kaufman",
"cover": "the-personal-mba-cover.jpg"
},
{
"title": "Stuff Matters",
"author": "Mark Miodownik",
"cover": "stuff-matters-cover.jpg"
},
{
"title": "A Random Walk Down Wall Street",
"author": "Burton Malkiel",
"cover": "a-random-walk-cover.jpg"
},
{
"title": "Change by Design",
"author": "Tim Brown",
"cover": "change-by-design-cover.jpg"
},
{
"title": "Adventures of an IT Leader",
"author": "Robert D. Austin, Richard L. Nolan, Shannon O'Donnell",
"cover": "adventures-of-an-it-leader-cover.jpg"
},
{
"title": "How to Win Friends and Influence People",
"author": "Dale Carnegie",
"cover": "how-to-win-friends-cover.jpg"
},
{
"title": "The Little Book of Behavioural Investing",
"author": "James Montier",
"cover": "behavioural-investing-cover.jpg"
},
{
"title": "Data Science for Business",
"author": "Foster Provost, Tom Fawcett",
"cover": "data-science-for-business-cover.jpg"
},
{
"title": "Business Adventures",
"author": "John Brooks",
"cover": "business-adventures-cover.jpg"
},
{
"title": "The Little Book of Common Sense Investing",
"author": "John Bogle",
"cover": "common-sense-investing-cover.jpg"
},
{
"title": "A Short Book About Art",
"author": "Dana Arnold",
"cover": "a-short-book-about-art-cover.jpg"
},
{
"title": "What Are You Looking At?: 150 Years of Modern Art in a Nutshell",
"author": "Will Gompertz",
"cover": "150-years-of-modern-art-cover.jpg"
},
{
"title": "Rework",
"author": "Jason Fried, David Heinemeier Hansson",
"cover": "rework-cover.jpg"
},
{
"title": "The Outsiders: Eight Unconventional CEOs and Their Radically Rational Blueprint for Success",
"author": "William N. Thorndike Jr.",
"cover": "the-outsiders-cover.jpg"
},
{
"title": "Shoe Dog",
"author": "Phil Knight",
"cover": "shoe-dog-cover.jpg"
},
{
"title": "On Writing: A Memoir of the Craft",
"author": "Stephen King",
"cover": "on-writing-cover.jpg"
},
{
"title": "Mistakes Were Made (But Not by Me): Why We Justify Foolish Beliefs, Bad Decisions, and Hurtful Acts",
"author": "Carol Tavris, Elliot Aronson",
"cover": "mistakes-were-made-cover.jpg"
},
{
"title": "The $100 Startup: Reinvent the Way You Make a Living, Do What You Love, and Create a New Future",
"author": "Chris Guillebeau ",
"cover": "100-startup-cover.jpg"
},
{
"title": "Anything You Want: 40 Lessons for a New Kind of Entrepreneur",
"author": "Derek Sivers",
"cover": "anything-you-want-cover.jpg"
},
{
"title": "Managing Humans: Biting and Humorous Tales of a Software Engineering Manager",
"author": "Michael Lopp",
"cover": "managing-humans-cover.jpg"
},
{
"title": "Ego Is the Enemy",
"author": "Ryan Holiday",
"cover": "ego-is-the-enemy-cover.jpg"
},
{
"title": "Leaders Eat Last: Why Some Teams Pull Together and Others Don't",
"author": "Simon Sinek",
"cover": "leaders-eat-last-cover.jpg"
},
{
"title": "Harder Than I Thought: Adventures of a Twenty-First Century Leader",
"author": "Robert D. Austin, Richard L. Nolan, Shannon O'Donnell",
"cover": "harder-than-i-thought-cover.jpg"
}
];
(function($){
$(function() {
function getImage(name) {
return 'images/book-covers/' + name;
}
var getBookHTML = function(title, author, image) {
var html ='<div class="col s6 m5 l3">' +
'<div class="book center-align">' +
'<img class="lazy" data-src="'+ getImage(image) + '"></img>' +
'<p class="center"><strong>' + title + '</strong><br/>'+ author + '</p>' +
'</div>' +
'</div>';
return html;
}
// load books
for (var i = 0; i < BOOKS.length; i++) {
var book = BOOKS[i];
var html = getBookHTML(book.title, book.author, book.cover);
$('#books-list').append(html);
}
// Start lazy loading - we must do this at the end
$('.lazy').lazy();
}); // end of document ready
})(jQuery); // end of jQuery name space
| {
"content_hash": "4a9af4ce01883d221dd9a7da2d2bc485",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 113,
"avg_line_length": 26.593333333333334,
"alnum_prop": 0.6264728002005515,
"repo_name": "jjestrel/jjestrel.github.io",
"id": "9bca31fc45c48cd351856fddbfee23042262afd7",
"size": "3989",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/personal.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "195672"
},
{
"name": "HTML",
"bytes": "17933"
},
{
"name": "JavaScript",
"bytes": "265082"
}
],
"symlink_target": ""
} |
layout: post
title: Android DEPPLINK及APPLink原理简析
category: Android
---
APP开发中经常会有这种需求:在浏览器或者短信中唤起APP,如果安装了就唤起,否则引导下载。对于Android而言,这里主要牵扯的技术就是deeplink,也可以简单看成scheme,Android一直是支持scheme的,但是由于Android的开源特性,不同手机厂商或者不同浏览器厂家处理的千奇百怪,有些能拉起,有些不行,本文只简单分析下link的原理,包括deeplink,也包括Android6.0之后的AppLink。**其实个人认为,AppLink可以就是deeplink,只不过它多了一种类似于验证机制,如果验证通过,就设置默认打开,如果验证不过,则退化为deeplink**,如果单从APP端来看,区别主要在Manifest文件中的android:autoVerify="true",如下,
**APPLINK只是在安装时候多了一个验证,其他跟之前deeplink一样,如果没联网,验证失败,那就跟之前的deeplink表现一样**
> deeplink配置(不限http/https)
<intent-filter>
<data android:scheme="https" android:host="test.example.com" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
(不限http/https)
<intent-filter>
<data android:scheme="example" />
<!-- 下面这几行也必须得设置 -->
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
> applink配置(只能http/https)
<intent-filter android:autoVerify="true">
<data android:scheme="https" android:host="test.example.com" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
在Android原生的APPLink实现中,需要APP跟服务端双向验证才能让APPLink生效,如果如果APPLink验证失败,APPLink会完全退化成deepLink,这也是为什么说APPLINK是一种特殊的deepLink,所以先分析下deepLink,deepLink理解了,APPLink就很容易理解。
# deepLink原理分析
deeplink的scheme相应分两种:一种是只有一个APP能相应,另一种是有多个APP可以相应,比如,如果为一个APP的Activity配置了http scheme类型的deepLink,如果通过短信或者其他方式唤起这种link的时候,一般会出现一个让用户选择的弹窗,因为一般而言,系统会带个浏览器,也相应这类scheme,比如下面的例子:
>adb shell am start -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "https://test.example.com/b/g"
<intent-filter>
<data android:scheme="https" android:host="test.example.com" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>

如果是设置了一个私用的,并且没有跟其他app重复的,那么会直接打开,比如下面的:
>adb shell am start -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "example://test.example.com/b/g"
<intent-filter>
<data android:scheme="example" />
<!-- 下面这几行也必须得设置 -->
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
当然,如果私有scheme跟其他APP的重复了,还是会唤起APP选择界面(其实是一个ResolverActivity)。下面就来看看scheme是如何匹配并拉起对应APP的。
## startActivity入口与ResolverActivity
无论APPLink跟DeepLink其实都是通过唤起一个Activity来实现界面的跳转,无论从APP外部:比如短信、浏览器,还是APP内部。通过在APP内部模拟跳转来看看具体实现,写一个H5界面,然后通过Webview加载,不过Webview不进行任何设置,这样跳转就需要系统进行解析,走deeplink这一套:
<html>
<body>
<a href="https://test.example.com/a/g">Scheme跳转</a>
</body>
</html>
点击Scheme跳转,一般会唤起如下界面,让用户选择打开方式:

如果通过adb打印log,你会发现**ActivityManagerService**会打印这样一条Log:
> 12-04 20:32:04.367 887 9064 I ActivityManager: START u0 {act=android.intent.action.VIEW dat=https://test.example.com/... cmp=android/com.android.internal.app.ResolverActivity (has extras)} from uid 10067 on display 0
其实看到的选择对话框就是ResolverActivity,不过我们先来看看到底是走到ResolverActivity的,也就是这个scheme怎么会唤起App选择界面,在短信中,或者Webview中遇到scheme,他们一般会发出相应的Intent(当然第三方APP可能会屏蔽掉,比如微信就换不起APP),其实上面的作用跟下面的代码结果一样:
val intent = Intent()
intent.setAction("android.intent.action.VIEW")
intent.setData(Uri.parse("https://test.example.com/a/g"))
intent.addCategory("android.intent.category.DEFAULT")
intent.addCategory("android.intent.category.BROWSABLE")
startActivity(intent)
那剩下的就是看startActivity,在6.0的源码中,startActivity最后会通过ActivityManagerService调用ActivityStatckSupervisor的startActivityMayWait
> ActivityStatckSUpervisor
final int startActivityMayWait(IApplicationThread caller, int callingUid, String callingPackage, Intent intent, String resolvedType, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, WaitResult outResult, Configuration config, Bundle options, boolean ignoreTargetSecurity, int userId, IActivityContainer iContainer, TaskRecord inTask) {
...
boolean componentSpecified = intent.getComponent() != null;
//创建新的Intent对象,即便intent被修改也不受影响
intent = new Intent(intent);
//收集Intent所指向的Activity信息, 当存在多个可供选择的Activity,则直接向用户弹出resolveActivity [见2.7.1]
ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags, profilerInfo, userId);
...
}
startActivityMayWait会通过**resolveActivity**先找到目标Activity,这个过程中,可能找到多个匹配的Activity,这就是ResolverActivity的入口:
ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
ProfilerInfo profilerInfo, int userId) {
// Collect information about the target of the Intent.
ActivityInfo aInfo;
try {
ResolveInfo rInfo =
AppGlobals.getPackageManager().resolveIntent(
intent, resolvedType,
PackageManager.MATCH_DEFAULT_ONLY
| ActivityManagerService.STOCK_PM_FLAGS, userId);
aInfo = rInfo != null ? rInfo.activityInfo : null;
} catch (RemoteException e) {
aInfo = null;
}
可以认为,所有的四大组件的信息都在PackageManagerService中有登记,想要找到这些类,就必须向PackagemanagerService查询,
> PackageManagerService
@Override
public ResolveInfo resolveIntent(Intent intent, String resolvedType,
int flags, int userId) {
if (!sUserManager.exists(userId)) return null;
enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
return chooseBestActivity(intent, resolvedType, flags, query, userId);
}
PackageManagerService会通过queryIntentActivities找到所有适合的Activity,再通过chooseBestActivity提供选择的权利。这里分如下三种情况:
* 仅仅找到一个,直接启动
* 找到了多个,并且设置了其中一个为默认启动,则直接启动相应Acitivity
* **找到了多个,切没有设置默认启动,则启动ResolveActivity供用户选择**
关于如何查询,匹配的这里不详述,仅仅简单看看如何唤起选择页面,或者默认打开,比较关键的就是chooseBestActivity,
private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
int flags, List<ResolveInfo> query, int userId) {
<!--查询最好的Activity-->
ResolveInfo ri = findPreferredActivity(intent, resolvedType,
flags, query, r0.priority, true, false, debug, userId);
if (ri != null) {
return ri;
}
...
}
ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
List<ResolveInfo> query, int priority, boolean always,
boolean removeMatches, boolean debug, int userId) {
if (!sUserManager.exists(userId)) return null;
// writer
synchronized (mPackages) {
if (intent.getSelector() != null) {
intent = intent.getSelector();
}
<!--如果用户已经选择过默认打开的APP,则这里返回的就是相对应APP中的Activity-->
ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
debug, userId);
if (pri != null) {
return pri;
}
<!--找Activity-->
PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
...
final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
...
}
@Override
public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
if (!sUserManager.exists(userId)) return null;
enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
synchronized (mPackages) {
...
<!--弄一个ResolveActivity的ActivityInfo-->
if (mResolveComponentName.equals(component)) {
return PackageParser.generateActivityInfo(mResolveActivity, flags,
new PackageUserState(), userId);
}
}
return null;
}
其实上述流程比较复杂,这里只是自己简单猜想下流程,找到目标Activity后,无论是真的目标Acitiviy,还是ResolveActivity,都会通过startActivityLocked继续走启动流程,这里就会看到之前打印的Log信息:
> ActivityStatckSUpervisor
final int startActivityLocked(IApplicationThread caller...{
if (err == ActivityManager.START_SUCCESS) {
Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true, true, false)
+ "} from uid " + callingUid
+ " on display " + (container == null ? (mFocusedStack == null ?
Display.DEFAULT_DISPLAY : mFocusedStack.mDisplayId) :
(container.mActivityDisplay == null ? Display.DEFAULT_DISPLAY :
container.mActivityDisplay.mDisplayId)));
}
如果是ResolveActivity还会根据用户选择的信息将一些设置持久化到本地,这样下次就可以直接启动用户的偏好App。其实以上就是deeplink的原理,说白了一句话:**scheme就是隐式启动Activity,如果能找到唯一或者设置的目标Acitivity则直接启动,如果找到多个,则提供APP选择界面。**
# AppLink原理
一般而言,每个APP都希望被自己制定的scheme唤起,这就是Applink,之前分析deeplink的时候提到了ResolveActivity这么一个选择过程,而AppLink就是自动帮用户完成这个选择过程,并且选择的scheme是最适合它的scheme(开发者的角度)。因此对于AppLink要分析的就是如何完成了这个默认选择的过程。
目前Android源码提供的是一个双向认证的方案:**在APP安装的时候,客户端根据APP配置像服务端请求,如果满足条件,scheme跟服务端配置匹配的上,就为APP设置默认启动选项**,所以这个方案很明显,在安装的时候需要联网才行,否则就是完全不会验证,那就是普通的deeplink,既然是在安装的时候去验证,那就看看PackageManagerService是如何处理这个流程的:
> PackageManagerService
private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
final int installFlags = args.installFlags;
<!--开始验证applink-->
startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
...
}
private void startIntentFilterVerifications(int userId, boolean replacing,
PackageParser.Package pkg) {
if (mIntentFilterVerifierComponent == null) {
return;
}
final int verifierUid = getPackageUid(
mIntentFilterVerifierComponent.getPackageName(),
(userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
mHandler.sendMessage(msg);
}
startIntentFilterVerifications发送一个消息开启验证,随后调用verifyIntentFiltersIfNeeded进行验证
private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
PackageParser.Package pkg) {
...
<!--检查是否有Activity设置了AppLink-->
final boolean hasDomainURLs = hasDomainURLs(pkg);
if (!hasDomainURLs) {
if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
"No domain URLs, so no need to verify any IntentFilter!");
return;
}
<!--是否autoverigy-->
boolean needToVerify = false;
for (PackageParser.Activity a : pkg.activities) {
for (ActivityIntentInfo filter : a.intents) {
<!--needsVerification是否设置autoverify -->
if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
needToVerify = true;
break;
}
}
}
<!--如果有搜集需要验证的Activity信息及scheme信息-->
if (needToVerify) {
final int verificationId = mIntentFilterVerificationToken++;
for (PackageParser.Activity a : pkg.activities) {
for (ActivityIntentInfo filter : a.intents) {
if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
"Verification needed for IntentFilter:" + filter.toString());
mIntentFilterVerifier.addOneIntentFilterVerification(
verifierUid, userId, verificationId, filter, packageName);
count++;
} } } } }
<!--开始验证-->
if (count > 0) {
mIntentFilterVerifier.startVerifications(userId);
}
}
可以看出,验证就三步:检查、搜集、验证。在检查阶段,首先看看是否有设置http/https scheme的Activity,并且是否满足设置了Intent.ACTION_DEFAULT与Intent.ACTION_VIEW,如果没有,则压根不需要验证,
* Check if one of the IntentFilter as both actions DEFAULT / VIEW and a HTTP/HTTPS data URI
*/
private static boolean hasDomainURLs(Package pkg) {
if (pkg == null || pkg.activities == null) return false;
final ArrayList<Activity> activities = pkg.activities;
final int countActivities = activities.size();
for (int n=0; n<countActivities; n++) {
Activity activity = activities.get(n);
ArrayList<ActivityIntentInfo> filters = activity.intents;
if (filters == null) continue;
final int countFilters = filters.size();
for (int m=0; m<countFilters; m++) {
ActivityIntentInfo aii = filters.get(m);
// 必须设置Intent.ACTION_VIEW 必须设置有ACTION_DEFAULT 必须要有SCHEME_HTTPS或者SCHEME_HTTP,查到一个就可以
if (!aii.hasAction(Intent.ACTION_VIEW)) continue;
if (!aii.hasAction(Intent.ACTION_DEFAULT)) continue;
if (aii.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
aii.hasDataScheme(IntentFilter.SCHEME_HTTPS)) {
return true;
}
}
}
return false;
}
检查的第二步试看看是否设置了autoverify,当然中间还有些是否设置过,用户是否选择过的操作,比较复杂,不分析,不过不影响对流程的理解:
<!--检查是否设置了autoverify,并且再次检查是否是http https类-->
public final boolean needsVerification() {
return getAutoVerify() && handlesWebUris(true);
}
public final boolean getAutoVerify() {
return ((mVerifyState & STATE_VERIFY_AUTO) == STATE_VERIFY_AUTO);
}
只要找到一个满足以上条件的Activity,就开始验证。如果想要开启applink,Manifest中配置必须像下面这样
<intent-filter android:autoVerify="true">
<data android:scheme="https" android:host="xxx.com" />
<data android:scheme="http" android:host="xxx.com" />
<!--外部intent打开,比如短信,文本编辑等-->
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
搜集其实就是搜集intentfilter信息,下面直接看验证过程,
@Override
public void startVerifications(int userId) {
...
sendVerificationRequest(userId, verificationId, ivs);
}
mCurrentIntentFilterVerifications.clear();
}
private void sendVerificationRequest(int userId, int verificationId,
IntentFilterVerificationState ivs) {
Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
verificationIntent.putExtra(
PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
verificationId);
verificationIntent.putExtra(
PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
getDefaultScheme());
verificationIntent.putExtra(
PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
ivs.getHostsString());
verificationIntent.putExtra(
PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
ivs.getPackageName());
verificationIntent.setComponent(mIntentFilterVerifierComponent);
verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
UserHandle user = new UserHandle(userId);
mContext.sendBroadcastAsUser(verificationIntent, user);
}
目前Android的实现是通过发送一个广播来进行验证的,也就是说,这是个异步的过程,验证是需要耗时的(网络请求),所以安装后,一般要等个几秒Applink才能生效,广播的接受处理者是:IntentFilterVerificationReceiver
public final class IntentFilterVerificationReceiver extends BroadcastReceiver {
private static final String TAG = IntentFilterVerificationReceiver.class.getSimpleName();
...
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION.equals(action)) {
Bundle inputExtras = intent.getExtras();
if (inputExtras != null) {
Intent serviceIntent = new Intent(context, DirectStatementService.class);
serviceIntent.setAction(DirectStatementService.CHECK_ALL_ACTION);
...
serviceIntent.putExtras(extras);
context.startService(serviceIntent);
}
IntentFilterVerificationReceiver收到验证消息后,通过start一个DirectStatementService进行验证,兜兜转转最终调用IsAssociatedCallable的verifyOneSource,
private class IsAssociatedCallable implements Callable<Void> {
...
private boolean verifyOneSource(AbstractAsset source, AbstractAssetMatcher target,
Relation relation) throws AssociationServiceException {
Result statements = mStatementRetriever.retrieveStatements(source);
for (Statement statement : statements.getStatements()) {
if (relation.matches(statement.getRelation())
&& target.matches(statement.getTarget())) {
return true;
}
}
return false;
}
IsAssociatedCallable会逐一对需要验证的intentfilter进行验证,具体是通过DirectStatementRetriever的retrieveStatements来实现:
@Override
public Result retrieveStatements(AbstractAsset source) throws AssociationServiceException {
if (source instanceof AndroidAppAsset) {
return retrieveFromAndroid((AndroidAppAsset) source);
} else if (source instanceof WebAsset) {
return retrieveFromWeb((WebAsset) source);
} else {
..
}
}
AndroidAppAsset好像是Google的另一套assetlink类的东西,好像用在APP web登陆信息共享之类的地方 ,不看,直接看retrieveFromWeb:从名字就能看出,这是获取服务端Applink的配置,获取后跟本地校验,如果通过了,那就是applink启动成功:
private Result retrieveStatementFromUrl(String urlString, int maxIncludeLevel,
AbstractAsset source)
throws AssociationServiceException {
List<Statement> statements = new ArrayList<Statement>();
if (maxIncludeLevel < 0) {
return Result.create(statements, DO_NOT_CACHE_RESULT);
}
WebContent webContent;
try {
URL url = new URL(urlString);
if (!source.followInsecureInclude()
&& !url.getProtocol().toLowerCase().equals("https")) {
return Result.create(statements, DO_NOT_CACHE_RESULT);
}
<!--通过网络请求获取配置-->
webContent = mUrlFetcher.getWebContentFromUrlWithRetry(url,
HTTP_CONTENT_SIZE_LIMIT_IN_BYTES, HTTP_CONNECTION_TIMEOUT_MILLIS,
HTTP_CONNECTION_BACKOFF_MILLIS, HTTP_CONNECTION_RETRY);
} catch (IOException | InterruptedException e) {
return Result.create(statements, DO_NOT_CACHE_RESULT);
}
try {
ParsedStatement result = StatementParser
.parseStatementList(webContent.getContent(), source);
statements.addAll(result.getStatements());
<!--如果有一对多的情况,或者说设置了“代理”,则循环获取配置-->
for (String delegate : result.getDelegates()) {
statements.addAll(
retrieveStatementFromUrl(delegate, maxIncludeLevel - 1, source)
.getStatements());
}
<!--发送结果-->
return Result.create(statements, webContent.getExpireTimeMillis());
} catch (JSONException | IOException e) {
return Result.create(statements, DO_NOT_CACHE_RESULT);
}
}
其实就是通过UrlFetcher获取服务端配置,然后发给之前的receiver进行验证:
public WebContent getWebContentFromUrl(URL url, long fileSizeLimit, int connectionTimeoutMillis)
throws AssociationServiceException, IOException {
final String scheme = url.getProtocol().toLowerCase(Locale.US);
if (!scheme.equals("http") && !scheme.equals("https")) {
throw new IllegalArgumentException("The url protocol should be on http or https.");
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(true);
connection.setConnectTimeout(connectionTimeoutMillis);
connection.setReadTimeout(connectionTimeoutMillis);
connection.setUseCaches(true);
connection.setInstanceFollowRedirects(false);
connection.addRequestProperty("Cache-Control", "max-stale=60");
...
return new WebContent(inputStreamToString(
connection.getInputStream(), connection.getContentLength(), fileSizeLimit),
expireTimeMillis);
}
看到这里的HttpURLConnection就知道为什么Applink需在安装时联网才有效,到这里其实就可以理解的差不多,后面其实就是针对配置跟App自身的配置进行校验,如果通过就设置默认启动,并持久化,验证成功的话可以通过
adb shell dumpsys package d
查看结果:
Package: com.xxx
Domains: xxxx.com
Status: always : 200000002
验证后再通过PackageManagerService持久化到设置信息,如此就完成了Applink验证流程。
# Chrome浏览器对于自定义scheme的拦截
> A little known feature in Android lets you launch apps directly from a web page via an Android Intent. One scenario is launching an app when the user lands on a page, which you can achieve by embedding an iframe in the page with a custom URI-scheme set as the src, as follows: < iframe src="paulsawesomeapp://page1"> </iframe>. This works in the Chrome for Android browser, version 18 and earlier. It also works in the Android browser, of course.
> The functionality has changed slightly in Chrome for Android, versions 25 and later. It is no longer possible to launch an Android app by setting an iframe's src attribute. For example, navigating an iframe to a URI with a custom scheme such as paulsawesomeapp:// will not work even if the user has the appropriate app installed. Instead, you should implement a user gesture to launch the app via a custom scheme, or use the “intent:” syntax described in this article.
也就是在chrome中不能通过iframe跳转自定义scheme唤起APP了,直接被block,如下图:

但是仍然可以通过window.location.href唤起:
function clickAndroid1(){
window.location.href="yaxxxuan://lab/u.xx.com";
}
或者通过<a>跳转标签唤起
<a href="yanxuan://lab/u.you.com">测试</a>
当然,如果自定义了https/http的也是可以的。总的来说Chrome除了Iframe,其他的好像都没问题。
<a href="https://xxx.com/a/g"> https 跳转</a>
# 国内乱七八糟的浏览器(观察日期2019-6-11)
* 360浏览器,可以通过iframe、<a>、<ref> 方式调用scheme,除了不支持https/http,其他都支持
* UC浏览器可以通过iframe、<a>、<ref> 方式调用scheme(即便如此,也可能被屏蔽(域名)) ,无法通过https/http/intent
* QQ浏览器可以通过iframe、<a>、<ref> 、intent 方式调用scheme,(也可能被屏蔽(域名),目前看没屏蔽) ,但是无法通过https/http
# 总结
其实关于applink有几个比较特殊的点:
* applink第一它只验证一次,在安装的时候,为什么不每次启动动检测呢?可能是为了给用户自己选怎留后门。
* applink验证的时候需要联网,不联网的方案行吗?个人理解,不联网应该也可以,只要在安装的时候,只本地验证好了,但是这样明显没有双向验证安全,因为双向验证证明了网站跟app是一对一应的,这样才能保证安全,防止第三方打包篡改。
# 参考文档
[Android M DeepLinks AppLinks 详解](http://fanhongwei.github.io/blog/2015/12/17/app-links-deep-links/)
[Verify Android App Links](https://developer.android.com/training/app-links/verify-site-associations)
| {
"content_hash": "4b8c154bf30e4eb87e5c3b23b2564063",
"timestamp": "",
"source": "github",
"line_count": 552,
"max_line_length": 470,
"avg_line_length": 44.416666666666664,
"alnum_prop": 0.6688147483481524,
"repo_name": "happylishang/happylishang.github.io",
"id": "3cee8d46c51cf5d91b22de0fb4cb58ce531ace40",
"size": "29767",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/App开发/2018-12-9-Android DEPPLINK及APPLink原理简析.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "117618"
},
{
"name": "CSS",
"bytes": "23261"
},
{
"name": "HTML",
"bytes": "25671"
},
{
"name": "Java",
"bytes": "4611"
},
{
"name": "JavaScript",
"bytes": "17182"
}
],
"symlink_target": ""
} |
// a hash table buffer that can expand, and can support as many deletions as
// additions, list-based, with elements of list held in array (for destruction
// management), multiplicative hashing (like ets). No synchronization built-in.
//
#ifndef __TBB__flow_graph_hash_buffer_impl_H
#define __TBB__flow_graph_hash_buffer_impl_H
#ifndef __TBB_flow_graph_H
#error Do not #include this internal file directly; use public TBB headers instead.
#endif
// included in namespace tbb::flow::interfaceX::internal
// elements in the table are a simple list; we need pointer to next element to
// traverse the chain
template<typename ValueType>
struct buffer_element_type {
// the second parameter below is void * because we can't forward-declare the type
// itself, so we just reinterpret_cast below.
typedef typename aligned_pair<ValueType, void *>::type type;
};
template
<
typename Key, // type of key within ValueType
typename ValueType,
typename ValueToKey, // abstract method that returns "const Key" or "const Key&" given ValueType
typename HashCompare, // has hash and equal
typename Allocator=tbb::cache_aligned_allocator< typename aligned_pair<ValueType, void *>::type >
>
class hash_buffer : public HashCompare {
public:
static const size_t INITIAL_SIZE = 8; // initial size of the hash pointer table
typedef ValueType value_type;
typedef typename buffer_element_type< value_type >::type element_type;
typedef value_type *pointer_type;
typedef element_type *list_array_type; // array we manage manually
typedef list_array_type *pointer_array_type;
typedef typename Allocator::template rebind<list_array_type>::other pointer_array_allocator_type;
typedef typename Allocator::template rebind<element_type>::other elements_array_allocator;
typedef typename tbb::internal::strip<Key>::type Knoref;
private:
ValueToKey *my_key;
size_t my_size;
size_t nelements;
pointer_array_type pointer_array; // pointer_array[my_size]
list_array_type elements_array; // elements_array[my_size / 2]
element_type* free_list;
size_t mask() { return my_size - 1; }
void set_up_free_list( element_type **p_free_list, list_array_type la, size_t sz) {
for(size_t i=0; i < sz - 1; ++i ) { // construct free list
la[i].second = &(la[i+1]);
}
la[sz-1].second = NULL;
*p_free_list = (element_type *)&(la[0]);
}
// cleanup for exceptions
struct DoCleanup {
pointer_array_type *my_pa;
list_array_type *my_elements;
size_t my_size;
DoCleanup(pointer_array_type &pa, list_array_type &my_els, size_t sz) :
my_pa(&pa), my_elements(&my_els), my_size(sz) { }
~DoCleanup() {
if(my_pa) {
size_t dont_care = 0;
internal_free_buffer(*my_pa, *my_elements, my_size, dont_care);
}
}
};
// exception-safety requires we do all the potentially-throwing operations first
void grow_array() {
size_t new_size = my_size*2;
size_t new_nelements = nelements; // internal_free_buffer zeroes this
list_array_type new_elements_array = NULL;
pointer_array_type new_pointer_array = NULL;
list_array_type new_free_list = NULL;
{
DoCleanup my_cleanup(new_pointer_array, new_elements_array, new_size);
new_elements_array = elements_array_allocator().allocate(my_size);
new_pointer_array = pointer_array_allocator_type().allocate(new_size);
for(size_t i=0; i < new_size; ++i) new_pointer_array[i] = NULL;
set_up_free_list(&new_free_list, new_elements_array, my_size );
for(size_t i=0; i < my_size; ++i) {
for( element_type* op = pointer_array[i]; op; op = (element_type *)(op->second)) {
value_type *ov = reinterpret_cast<value_type *>(&(op->first));
// could have std::move semantics
internal_insert_with_key(new_pointer_array, new_size, new_free_list, *ov);
}
}
my_cleanup.my_pa = NULL;
my_cleanup.my_elements = NULL;
}
internal_free_buffer(pointer_array, elements_array, my_size, nelements);
free_list = new_free_list;
pointer_array = new_pointer_array;
elements_array = new_elements_array;
my_size = new_size;
nelements = new_nelements;
}
// v should have perfect forwarding if std::move implemented.
// we use this method to move elements in grow_array, so can't use class fields
void internal_insert_with_key( element_type **p_pointer_array, size_t p_sz, list_array_type &p_free_list,
const value_type &v) {
size_t l_mask = p_sz-1;
__TBB_ASSERT(my_key, "Error: value-to-key functor not provided");
size_t h = this->hash((*my_key)(v)) & l_mask;
__TBB_ASSERT(p_free_list, "Error: free list not set up.");
element_type* my_elem = p_free_list; p_free_list = (element_type *)(p_free_list->second);
(void) new(&(my_elem->first)) value_type(v);
my_elem->second = p_pointer_array[h];
p_pointer_array[h] = my_elem;
}
void internal_initialize_buffer() {
pointer_array = pointer_array_allocator_type().allocate(my_size);
for(size_t i = 0; i < my_size; ++i) pointer_array[i] = NULL;
elements_array = elements_array_allocator().allocate(my_size / 2);
set_up_free_list(&free_list, elements_array, my_size / 2);
}
// made static so an enclosed class can use to properly dispose of the internals
static void internal_free_buffer( pointer_array_type &pa, list_array_type &el, size_t &sz, size_t &ne ) {
if(pa) {
for(size_t i = 0; i < sz; ++i ) {
element_type *p_next;
for( element_type *p = pa[i]; p; p = p_next) {
p_next = (element_type *)p->second;
internal::punned_cast<value_type *>(&(p->first))->~value_type();
}
}
pointer_array_allocator_type().deallocate(pa, sz);
pa = NULL;
}
// Separate test (if allocation of pa throws, el may be allocated.
// but no elements will be constructed.)
if(el) {
elements_array_allocator().deallocate(el, sz / 2);
el = NULL;
}
sz = INITIAL_SIZE;
ne = 0;
}
public:
hash_buffer() : my_key(NULL), my_size(INITIAL_SIZE), nelements(0) {
internal_initialize_buffer();
}
~hash_buffer() {
internal_free_buffer(pointer_array, elements_array, my_size, nelements);
if(my_key) delete my_key;
}
void reset() {
internal_free_buffer(pointer_array, elements_array, my_size, nelements);
internal_initialize_buffer();
}
// Take ownership of func object allocated with new.
// This method is only used internally, so can't be misused by user.
void set_key_func(ValueToKey *vtk) { my_key = vtk; }
// pointer is used to clone()
ValueToKey* get_key_func() { return my_key; }
bool insert_with_key(const value_type &v) {
pointer_type p = NULL;
__TBB_ASSERT(my_key, "Error: value-to-key functor not provided");
if(find_ref_with_key((*my_key)(v), p)) {
p->~value_type();
(void) new(p) value_type(v); // copy-construct into the space
return false;
}
++nelements;
if(nelements*2 > my_size) grow_array();
internal_insert_with_key(pointer_array, my_size, free_list, v);
return true;
}
// returns true and sets v to array element if found, else returns false.
bool find_ref_with_key(const Knoref& k, pointer_type &v) {
size_t i = this->hash(k) & mask();
for(element_type* p = pointer_array[i]; p; p = (element_type *)(p->second)) {
pointer_type pv = reinterpret_cast<pointer_type>(&(p->first));
__TBB_ASSERT(my_key, "Error: value-to-key functor not provided");
if(this->equal((*my_key)(*pv), k)) {
v = pv;
return true;
}
}
return false;
}
bool find_with_key( const Knoref& k, value_type &v) {
value_type *p;
if(find_ref_with_key(k, p)) {
v = *p;
return true;
}
else
return false;
}
void delete_with_key(const Knoref& k) {
size_t h = this->hash(k) & mask();
element_type* prev = NULL;
for(element_type* p = pointer_array[h]; p; prev = p, p = (element_type *)(p->second)) {
value_type *vp = reinterpret_cast<value_type *>(&(p->first));
__TBB_ASSERT(my_key, "Error: value-to-key functor not provided");
if(this->equal((*my_key)(*vp), k)) {
vp->~value_type();
if(prev) prev->second = p->second;
else pointer_array[h] = (element_type *)(p->second);
p->second = free_list;
free_list = p;
--nelements;
return;
}
}
__TBB_ASSERT(false, "key not found for delete");
}
};
#endif // __TBB__flow_graph_hash_buffer_impl_H
| {
"content_hash": "a9cc5714d07127a91932417a6a03aec5",
"timestamp": "",
"source": "github",
"line_count": 235,
"max_line_length": 109,
"avg_line_length": 39.85531914893617,
"alnum_prop": 0.5844544095665172,
"repo_name": "Teaonly/easyLearning.js",
"id": "46755fe07078525fe64ea399248579ae794c383c",
"size": "9982",
"binary": false,
"copies": "26",
"ref": "refs/heads/master",
"path": "TensorExpress/aten/src/ATen/cpu/tbb/tbb_remote/include/tbb/internal/_flow_graph_tagged_buffer_impl.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1"
},
{
"name": "C++",
"bytes": "11485"
},
{
"name": "JavaScript",
"bytes": "100936"
},
{
"name": "Jupyter Notebook",
"bytes": "213476"
},
{
"name": "Lua",
"bytes": "17603"
},
{
"name": "Python",
"bytes": "320"
},
{
"name": "Shell",
"bytes": "375"
}
],
"symlink_target": ""
} |
package com.insightfullogic.honest_profiler.core.parser;
import org.slf4j.Logger;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import static com.insightfullogic.honest_profiler.core.parser.LogParser.AmountRead.*;
public class LogParser
{
private static final int NOT_WRITTEN = 0;
private static final int TRACE_START = 1;
private static final int STACK_FRAME_BCI_ONLY = 2;
private static final int STACK_FRAME_FULL = 21;
private static final int NEW_METHOD = 3;
private final LogEventListener listener;
private final Logger logger;
public static enum AmountRead
{
COMPLETE_RECORD, PARTIAL_RECORD, NOTHING
}
public LogParser(final Logger logger, final LogEventListener listener)
{
this.listener = listener;
this.logger = logger;
}
public AmountRead readRecord(ByteBuffer input)
{
int initialPosition = input.position();
if (!input.hasRemaining())
{
return NOTHING;
}
byte type = input.get();
try
{
switch (type)
{
case NOT_WRITTEN:
// go back one byte since we've just read a 0
input.position(input.position() - 1);
return NOTHING;
case TRACE_START:
readTraceStart(input);
return COMPLETE_RECORD;
case STACK_FRAME_BCI_ONLY:
readStackFrameBciOnly(input);
return COMPLETE_RECORD;
case STACK_FRAME_FULL:
readStackFrameFull(input);
return COMPLETE_RECORD;
case NEW_METHOD:
readNewMethod(input);
return COMPLETE_RECORD;
}
}
catch (BufferUnderflowException e)
{
// If you've underflowed the buffer,
// then you need to wait for more data to be written.
input.position(initialPosition);
return PARTIAL_RECORD;
}
// Should never get here
return NOTHING;
}
public void endOfLog()
{
listener.endOfLog();
}
private void readNewMethod(ByteBuffer input)
{
Method newMethod = new Method(input.getLong(), readString(input), readString(input), readString(input));
newMethod.accept(listener);
}
private String readString(ByteBuffer input)
{
int size = input.getInt();
char[] buffer = new char[size];
// conversion from c style characters to Java.
for (int i = 0; i < size; i++)
{
buffer[i] = (char) input.get();
}
return new String(buffer);
}
private void readStackFrameBciOnly(ByteBuffer input)
{
int bci = input.getInt();
long methodId = input.getLong();
StackFrame stackFrame = new StackFrame(bci, methodId);
stackFrame.accept(listener);
}
private void readStackFrameFull(ByteBuffer input)
{
int bci = input.getInt();
int lineNumber = input.getInt();
long methodId = input.getLong();
StackFrame stackFrame = new StackFrame(bci, lineNumber, methodId);
stackFrame.accept(listener);
}
private void readTraceStart(ByteBuffer input)
{
int numberOfFrames = input.getInt();
long threadId = input.getLong();
TraceStart traceStart = new TraceStart(numberOfFrames, threadId);
traceStart.accept(listener);
}
}
| {
"content_hash": "4f114be8746cbd427ee6dd9ac956162f",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 112,
"avg_line_length": 28.452380952380953,
"alnum_prop": 0.5838214783821478,
"repo_name": "ofdrm/honest-profiler",
"id": "5dbce0c9ffdc4e82041e2b2288ff9ef989da3215",
"size": "4753",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/com/insightfullogic/honest_profiler/core/parser/LogParser.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "50309"
},
{
"name": "CMake",
"bytes": "4082"
},
{
"name": "CSS",
"bytes": "85"
},
{
"name": "HTML",
"bytes": "3892"
},
{
"name": "Java",
"bytes": "310242"
},
{
"name": "JavaScript",
"bytes": "8988"
},
{
"name": "Protocol Buffer",
"bytes": "519"
},
{
"name": "Shell",
"bytes": "521"
}
],
"symlink_target": ""
} |
layout: default
---
<div class="home">
<p class="intro">I'm a front-end web developer with a focus on modern
JavaScript workflows and tooling, and a yen for functional programming.</p>
<h1 class="section-heading">Skillset</h1>
{% for skill in site.skills %}
<p class="skill" data-powertip="{{ skill.content | escape }}">
<strong>{{ skill.title }}:</strong>
<em>{{ skill.proficiency }}</em>
</p>
{% endfor %}
<h1 class="section-heading">Open Source</h1>
{% for contrib in site.contribs %}
<div class="contribution">
<h2 class="contribution-heading">
{{ contrib.title }}
<a class="contrib-reference" href="{{ contrib.reference_url }}">
view on GitHub
</a>
</h2>
{{ contrib.content }}
</div>
{% endfor %}
<h1 class="section-heading">Projects</h1>
{% for proj in site.projects %}
<div class="project">
{% if proj.images | length %}
<div class="project-images">
{% for image in proj.images %}
<div class="project-image">
<img src="{{ image | prepend: site.baseurl }}">
</div>
{% endfor %}
</div>
{% endif %}
<ul class="relatedlinks">
<li>
<a href="{{ proj.github_repo_name | prepend: '/' | prepend: site.baseurl }}">
Demo
</a>
</li>
<li>
<a href="https://github.com/{{ site.github_username }}/{{ proj.github_repo_name }}">
Code
</a>
</li>
</ul>
<div class="project-description">
<h2 class="project-heading">{{ proj.title }}</h2>
<ul class="techstack">
{% for tech in proj.tech %}
<li>{{ tech }}</li>
{% endfor %}
</ul>
{{ proj.content }}
</div>
</div>
{% endfor %}
<script src="scripts/main.js"></script>
</div>
| {
"content_hash": "fe76c6ef8ec236a8037f6bf02add9f55",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 94,
"avg_line_length": 26.746478873239436,
"alnum_prop": 0.5118483412322274,
"repo_name": "b-paul/b-paul.github.io",
"id": "9f4197b254f785543c54920e752ba9db0c9eb9a9",
"size": "1903",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4985"
},
{
"name": "HTML",
"bytes": "17862"
}
],
"symlink_target": ""
} |
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django import forms
class SearchFrom(forms.Form):
search_widget = forms.TextInput(attrs={'placeholder': 'Event name, location, description...'})
q = forms.CharField(required=False, label='Search', widget=search_widget)
def __init__(self, *args, **kwargs):
super(SearchFrom, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_class = 'searchForms'
self.helper.form_method = 'GET'
self.helper.form_action = 'search'
self.helper.label_class = 'hidden'
self.helper.field_class = 'col-lg-6 col-md-10'
self.helper.add_input(Submit('submit', 'Search'))
def clean_q(self):
try:
q = self.cleaned_data.get("q")
except:
return None
return q
| {
"content_hash": "02fb264a3ba473fa14f8a3dac5d6fefc",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 98,
"avg_line_length": 31.321428571428573,
"alnum_prop": 0.6259977194982896,
"repo_name": "MihaZelnik/Meeple",
"id": "2ec23d3c6b167ffbeeb6a5915b71b397fef4b003",
"size": "877",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/meeple/apps/events/forms.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "622349"
},
{
"name": "JavaScript",
"bytes": "10426"
},
{
"name": "Python",
"bytes": "53986"
},
{
"name": "Shell",
"bytes": "3028"
}
],
"symlink_target": ""
} |
import logging
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from horizon.utils import memoized
from ironic_discoverd import client as discoverd_client
from ironicclient import client as ironic_client
from openstack_dashboard.api import base
from openstack_dashboard.api import glance
from openstack_dashboard.api import nova
import requests
from tuskar_ui.cached_property import cached_property # noqa
from tuskar_ui.handle_errors import handle_errors # noqa
from tuskar_ui.utils import utils
# power states
ERROR_STATES = set(['deploy failed', 'error'])
POWER_ON_STATES = set(['on', 'power on'])
# provision_states of ironic aggregated to reasonable groups
PROVISION_STATE_FREE = ['available', 'deleted', None]
PROVISION_STATE_PROVISIONED = ['active']
PROVISION_STATE_PROVISIONING = [
'deploying', 'wait call-back', 'rebuild', 'deploy complete']
PROVISION_STATE_DELETING = ['deleting']
PROVISION_STATE_ERROR = ['error', 'deploy failed']
# names for states of ironic used in UI,
# provison_states + discovery states
DISCOVERING_STATE = 'discovering'
DISCOVERED_STATE = 'discovered'
DISCOVERY_FAILED_STATE = 'discovery failed'
MAINTENANCE_STATE = 'manageable'
PROVISIONED_STATE = 'provisioned'
PROVISIONING_FAILED_STATE = 'provisioning failed'
PROVISIONING_STATE = 'provisioning'
DELETING_STATE = 'deleting'
FREE_STATE = 'free'
IRONIC_DISCOVERD_URL = getattr(settings, 'IRONIC_DISCOVERD_URL', None)
LOG = logging.getLogger(__name__)
def ironicclient(request):
api_version = 1
kwargs = {'os_auth_token': request.user.token.id,
'ironic_url': base.url_for(request, 'baremetal')}
return ironic_client.get_client(api_version, **kwargs)
# FIXME(lsmola) This should be done in Horizon, they don't have caching
@memoized.memoized
@handle_errors(_("Unable to retrieve image."))
def image_get(request, image_id):
"""Returns an Image object with metadata
Returns an Image object populated with metadata for image
with supplied identifier.
:param image_id: list of objects to be put into a dict
:type image_id: list
:return: object
:rtype: glanceclient.v1.images.Image
"""
image = glance.image_get(request, image_id)
return image
class Node(base.APIResourceWrapper):
_attrs = ('id', 'uuid', 'instance_uuid', 'driver', 'driver_info',
'properties', 'power_state', 'target_power_state',
'provision_state', 'maintenance', 'extra')
def __init__(self, apiresource, request=None, instance=None):
"""Initialize a Node
:param apiresource: apiresource we want to wrap
:type apiresource: IronicNode
:param request: request
:type request: django.core.handlers.wsgi.WSGIRequest
:param instance: instance relation we want to cache
:type instance: openstack_dashboard.api.nova.Server
:return: Node object
:rtype: tusar_ui.api.node.Node
"""
super(Node, self).__init__(apiresource)
self._request = request
self._instance = instance
@classmethod
def create(cls, request, ipmi_address=None, cpu_arch=None, cpus=None,
memory_mb=None, local_gb=None, mac_addresses=[],
ipmi_username=None, ipmi_password=None, ssh_address=None,
ssh_username=None, ssh_key_contents=None,
deployment_kernel=None, deployment_ramdisk=None,
driver=None):
"""Create a Node in Ironic."""
if driver == 'pxe_ssh':
driver_info = {
'ssh_address': ssh_address,
'ssh_username': ssh_username,
'ssh_key_contents': ssh_key_contents,
'ssh_virt_type': 'virsh',
}
else:
driver_info = {
'ipmi_address': ipmi_address,
'ipmi_username': ipmi_username,
'ipmi_password': ipmi_password
}
driver_info.update(
deploy_kernel=deployment_kernel,
deploy_ramdisk=deployment_ramdisk
)
properties = {'capabilities': 'boot_option:local', }
if cpus:
properties.update(cpus=cpus)
if memory_mb:
properties.update(memory_mb=memory_mb)
if local_gb:
properties.update(local_gb=local_gb)
if cpu_arch:
properties.update(cpu_arch=cpu_arch)
node = ironicclient(request).node.create(
driver=driver,
driver_info=driver_info,
properties=properties,
)
for mac_address in mac_addresses:
ironicclient(request).port.create(
node_uuid=node.uuid,
address=mac_address
)
return cls(node, request)
@classmethod
@handle_errors(_("Unable to retrieve node"))
def get(cls, request, uuid):
"""Return the Node that matches the ID
:param request: request object
:type request: django.http.HttpRequest
:param uuid: ID of Node to be retrieved
:type uuid: str
:return: matching Node, or None if no IronicNode matches the ID
:rtype: tuskar_ui.api.node.Node
"""
node = ironicclient(request).node.get(uuid)
if node.instance_uuid is not None:
server = nova.server_get(request, node.instance_uuid)
else:
server = None
return cls(node, request, server)
@classmethod
@handle_errors(_("Unable to retrieve node"))
def get_by_instance_uuid(cls, request, instance_uuid):
"""Return the Node associated with the instance ID
:param request: request object
:type request: django.http.HttpRequest
:param instance_uuid: ID of Instance that is deployed on the Node
to be retrieved
:type instance_uuid: str
:return: matching Node
:rtype: tuskar_ui.api.node.Node
:raises: ironicclient.exc.HTTPNotFound if there is no Node with
the matching instance UUID
"""
node = ironicclient(request).node.get_by_instance_uuid(instance_uuid)
server = nova.server_get(request, instance_uuid)
return cls(node, request, server)
@classmethod
@handle_errors(_("Unable to retrieve nodes"), [])
def list(cls, request, associated=None, maintenance=None):
"""Return a list of Nodes
:param request: request object
:type request: django.http.HttpRequest
:param associated: should we also retrieve all Nodes, only those
associated with an Instance, or only those not
associated with an Instance?
:type associated: bool
:param maintenance: should we also retrieve all Nodes, only those
in maintenance mode, or those which are not in
maintenance mode?
:type maintenance: bool
:return: list of Nodes, or an empty list if there are none
:rtype: list of tuskar_ui.api.node.Node
"""
nodes = ironicclient(request).node.list(associated=associated,
maintenance=maintenance)
if associated is None or associated:
servers = nova.server_list(request)[0]
servers_dict = utils.list_to_dict(servers)
nodes_with_instance = []
for n in nodes:
server = servers_dict.get(n.instance_uuid, None)
nodes_with_instance.append(cls(n, instance=server,
request=request))
return [cls.get(request, node.uuid)
for node in nodes_with_instance]
return [cls.get(request, node.uuid) for node in nodes]
@classmethod
def delete(cls, request, uuid):
"""Delete an Node
Remove the IronicNode matching the ID if it
exists; otherwise, does nothing.
:param request: request object
:type request: django.http.HttpRequest
:param uuid: ID of IronicNode to be removed
:type uuid: str
"""
return ironicclient(request).node.delete(uuid)
@classmethod
def discover(cls, request, uuids):
"""Set the maintenance status of node
:param request: request object
:type request: django.http.HttpRequest
:param uuids: IDs of IronicNodes
:type uuids: list of str
"""
if not IRONIC_DISCOVERD_URL:
return
for uuid in uuids:
discoverd_client.introspect(uuid, IRONIC_DISCOVERD_URL,
request.user.token.id)
@classmethod
def set_maintenance(cls, request, uuid, maintenance):
"""Set the maintenance status of node
:param request: request object
:type request: django.http.HttpRequest
:param uuid: ID of Node to be removed
:type uuid: str
:param maintenance: desired maintenance state
:type maintenance: bool
"""
patch = {
'op': 'replace',
'value': 'True' if maintenance else 'False',
'path': '/maintenance'
}
node = ironicclient(request).node.update(uuid, [patch])
return cls(node, request)
@classmethod
def set_power_state(cls, request, uuid, power_state):
"""Set the power_state of node
:param request: request object
:type request: django.http.HttpRequest
:param uuid: ID of Node
:type uuid: str
:param power_state: desired power_state
:type power_state: str
"""
node = ironicclient(request).node.set_power_state(uuid, power_state)
return cls(node, request)
@classmethod
def list_ports(cls, request, uuid):
"""Return a list of ports associated with this Node
:param request: request object
:type request: django.http.HttpRequest
:param uuid: ID of IronicNode
:type uuid: str
"""
return ironicclient(request).node.list_ports(uuid)
@cached_property
def addresses(self):
"""Return a list of port addresses associated with this IronicNode
:return: list of port addresses associated with this IronicNode, or
an empty list if no addresses are associated with
this IronicNode
:rtype: list of str
"""
ports = self.list_ports(self._request, self.uuid)
return [port.address for port in ports]
@cached_property
def cpus(self):
return self.properties.get('cpus', None)
@cached_property
def memory_mb(self):
return self.properties.get('memory_mb', None)
@cached_property
def local_gb(self):
return self.properties.get('local_gb', None)
@cached_property
def cpu_arch(self):
return self.properties.get('cpu_arch', None)
@cached_property
def state(self):
if self.maintenance:
if not IRONIC_DISCOVERD_URL:
return MAINTENANCE_STATE
try:
status = discoverd_client.get_status(
uuid=self.uuid,
base_url=IRONIC_DISCOVERD_URL,
auth_token=self._request.user.token.id,
)
except requests.HTTPError as e:
if getattr(e.response, 'status_code', None) == 404:
return MAINTENANCE_STATE
raise
if status['error']:
return DISCOVERY_FAILED_STATE
elif status['finished']:
return DISCOVERED_STATE
else:
return DISCOVERING_STATE
else:
if self.provision_state in PROVISION_STATE_FREE:
return FREE_STATE
if self.provision_state in PROVISION_STATE_PROVISIONING:
return PROVISIONING_STATE
if self.provision_state in PROVISION_STATE_PROVISIONED:
return PROVISIONED_STATE
if self.provision_state in PROVISION_STATE_DELETING:
return DELETING_STATE
if self.provision_state in PROVISION_STATE_ERROR:
return PROVISIONING_FAILED_STATE
# Unknown state
return None
@cached_property
def instance(self):
"""Return the Nova Instance associated with this Node
:return: Nova Instance associated with this Node; or
None if there is no Instance associated with this
Node, or no matching Instance is found
:rtype: Instance
"""
if self._instance is not None:
return self._instance
if self.instance_uuid:
servers, _has_more_data = nova.server_list(self._request)
for server in servers:
if server.id == self.instance_uuid:
return server
@cached_property
def ip_address(self):
try:
apiresource = self.instace._apiresource
except AttributeError:
LOG.error("Couldn't obtain IP address")
return None
return apiresource.addresses['ctlplane'][0]['addr']
@cached_property
def image_name(self):
"""Return image name of associated instance
Returns image name of instance associated with node
:return: Image name of instance
:rtype: string
"""
if self.instance is None:
return
image = image_get(self._request, self.instance.image['id'])
return image.name
@cached_property
def instance_status(self):
return getattr(getattr(self, 'instance', None), 'status', None)
@cached_property
def provisioning_status(self):
if self.instance_uuid:
return _("Provisioned")
return _("Free")
@classmethod
def get_all_mac_addresses(cls, request):
macs = [node.addresses for node in cls.list(request)]
return set([mac.upper() for sublist in macs for mac in sublist])
| {
"content_hash": "8714203910368b58ca35c0b6349d2370",
"timestamp": "",
"source": "github",
"line_count": 420,
"max_line_length": 77,
"avg_line_length": 33.7,
"alnum_prop": 0.6035749611417267,
"repo_name": "rdo-management/tuskar-ui",
"id": "12b037b44a46c4f7bf9fac07d5208acb603e8a16",
"size": "14727",
"binary": false,
"copies": "1",
"ref": "refs/heads/mgt-master",
"path": "tuskar_ui/api/node.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10852"
},
{
"name": "HTML",
"bytes": "78854"
},
{
"name": "JavaScript",
"bytes": "47323"
},
{
"name": "Makefile",
"bytes": "588"
},
{
"name": "Python",
"bytes": "395453"
},
{
"name": "Shell",
"bytes": "16701"
}
],
"symlink_target": ""
} |
namespace Umbraco.Cms.Tests.Common.Builders.Interfaces;
public interface IAccountBuilder : IWithLoginBuilder,
IWithEmailBuilder,
IWithFailedPasswordAttemptsBuilder,
IWithIsApprovedBuilder,
IWithIsLockedOutBuilder,
IWithLastLoginDateBuilder,
IWithLastPasswordChangeDateBuilder
{
}
| {
"content_hash": "b41c7b999c572a6135f95f7957850b2d",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 55,
"avg_line_length": 27.727272727272727,
"alnum_prop": 0.819672131147541,
"repo_name": "umbraco/Umbraco-CMS",
"id": "e6ac2438b84c172440e760ef04cc082ced2af6e8",
"size": "365",
"binary": false,
"copies": "5",
"ref": "refs/heads/v11/contrib",
"path": "tests/Umbraco.Tests.Common/Builders/Interfaces/IAccountBuilder.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "15983652"
},
{
"name": "CSS",
"bytes": "20625"
},
{
"name": "Dockerfile",
"bytes": "1204"
},
{
"name": "HTML",
"bytes": "1384255"
},
{
"name": "JavaScript",
"bytes": "4766393"
},
{
"name": "Less",
"bytes": "734364"
},
{
"name": "Smalltalk",
"bytes": "1"
},
{
"name": "TypeScript",
"bytes": "241078"
}
],
"symlink_target": ""
} |
package com.googlecode.aluminumproject.libraries.io.actions;
import com.googlecode.aluminumproject.AluminumException;
import com.googlecode.aluminumproject.annotations.Required;
import com.googlecode.aluminumproject.context.Context;
import com.googlecode.aluminumproject.libraries.actions.AbstractAction;
import com.googlecode.aluminumproject.writers.Writer;
import java.io.File;
@SuppressWarnings("javadoc")
public class RenameFile extends AbstractAction {
private @Required File source;
private @Required String targetName;
public void execute(Context context, Writer writer) throws AluminumException {
File target = new File(source.getParentFile(), targetName);
if (!source.getParentFile().equals(target.getParentFile())) {
throw new AluminumException("the rename file action does not support moving files");
} else if (target.exists()) {
throw new AluminumException("can't rename '", source.getName(), "' to '", targetName, "': ",
"a file with that name already exists");
} else if (!source.renameTo(target)) {
throw new AluminumException("can't rename '", source.getName(), "' to '", targetName, "'");
}
}
} | {
"content_hash": "bad699a161e635a5dae4d0b75db9eb74",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 95,
"avg_line_length": 39.48275862068966,
"alnum_prop": 0.7633187772925765,
"repo_name": "levi-h/aluminumproject",
"id": "33599550e422a88afc355f253c661f313ef509f8",
"size": "1745",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "libraries/general/io/src/main/java/com/googlecode/aluminumproject/libraries/io/actions/RenameFile.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2162"
},
{
"name": "Java",
"bytes": "1686923"
},
{
"name": "Shell",
"bytes": "2204"
}
],
"symlink_target": ""
} |
from setuptools import setup, find_packages
version = '1.3'
setup(
name='i2a',
version=version,
description='i2a creates ASCII art from images right on your terminal.',
long_description=open('README.rst').read(),
author='Sid Verma',
author_email='sid@sidverma.net',
license='MIT',
keywords=['image','jpg','ascii','art'],
url='http://github.com/mavidser/i2a',
packages=['i2a'],
install_requires=[
'docopt>=0.6.2',
'Pillow>=2.5.0'
],
entry_points={
'console_scripts': [
'i2a=i2a.i2a:main'
],
}
)
| {
"content_hash": "c39418d0f47218d12b4fa6af4251f424",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 76,
"avg_line_length": 23.84,
"alnum_prop": 0.5771812080536913,
"repo_name": "mavidser/i2a",
"id": "857805f918381d44d264c4e2dbe5cf2088c5af65",
"size": "619",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "7264"
}
],
"symlink_target": ""
} |
<?php
namespace Sonata\CacheAltBundle\Adapter;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Process\Process;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Sonata\CacheAltBundle\Cache\CacheInterface;
use Sonata\CacheAltBundle\Cache\CacheElement;
use Symfony\Component\HttpFoundation\Request;
/**
* http://www.varnish-cache.org/docs/2.1/reference/varnishadm.html
* echo vcl.use foo | varnishadm -T localhost:999 -S /var/db/secret
* echo vcl.use foo | ssh vhost varnishadm -T localhost:999 -S /var/db/secret
*
* in the config.yml file :
* echo %s "%s" | varnishadm -T localhost:999 -S /var/db/secret
* echo %s "%s" | ssh vhost varnishadm -T localhost:999 -S /var/db/secret
*/
class EsiCache implements CacheInterface
{
protected $router;
protected $servers;
protected $resolver;
protected $token;
/**
* @param $token
* @param array $servers
* @param \Symfony\Component\Routing\RouterInterface $router
* @param null|\Symfony\Component\HttpKernel\Controller\ControllerResolverInterface $resolver
*/
public function __construct($token, array $servers = array(), RouterInterface $router, ControllerResolverInterface $resolver = null)
{
$this->token = $token;
$this->servers = $servers;
$this->router = $router;
$this->resolver = $resolver;
}
/**
* {@inheritdoc}
*/
public function flushAll()
{
return $this->runCommand('purge', 'req.url ~ .*');
}
/**
* @param string $command
* @param string $expression
* @return bool
*/
private function runCommand($command, $expression)
{
$return = true;
foreach ($this->servers as $server) {
$command = str_replace(array('{{ COMMAND }}', '{{ EXPRESSION }}'), array($command, $expression), $server);
$process = new Process($command);
if ($process->run() == 0) {
continue;
}
$return = false;
}
return $return;
}
/**
* {@inheritdoc}
*/
public function flush(array $keys = array())
{
$parameters = array();
foreach ($keys as $key => $value) {
$parameters[] = sprintf('obj.http.%s ~ %s', $this->normalize($key), $value);
}
$purge = implode(" && ", $parameters);
return $this->runCommand('purge', $purge);
}
/**
* {@inheritdoc}
*/
public function has(array $keys)
{
return true;
}
/**
* {@inheritdoc}
*/
public function get(array $keys)
{
if (!isset($keys['controller'])) {
throw new \RuntimeException('Please define a controller key');
}
if (!isset($keys['parameters'])) {
throw new \RuntimeException('Please define a parameters key');
}
$content = sprintf('<esi:include src="%s"/>', $this->getUrl($keys));
return new CacheElement($keys, new Response($content));
}
/**
* {@inheritdoc}
*/
public function set(array $keys, $data, $ttl = 84600, array $contextualKeys = array())
{
return new CacheElement($keys, $data, $ttl, $contextualKeys);
}
/**
* @param array $keys
* @return string
*/
protected function getUrl(array $keys)
{
$parameters = array(
'token' => $this->computeHash($keys),
'parameters' => $keys
);
return $this->router->generate('sonata_cache_esi', $parameters, true);
}
/**
* @param array $keys
* @return string
*/
protected function computeHash(array $keys)
{
return hash('sha256', $this->token.serialize($keys));
}
/**
* @param $key
* @return string
*/
protected function normalize($key)
{
return sprintf('x-sonata-cache-%s', str_replace(array('_', '\\'), '-', strtolower($key)));
}
/**
* @param \Symfony\Component\HttpFoundation\Request $request
* @return mixed
*/
public function cacheAction(Request $request)
{
$parameters = $request->get('parameters', array());
if ($request->get('token') != $this->computeHash($parameters)) {
throw new AccessDeniedHttpException('Invalid token');
}
$subRequest = Request::create('', 'get', $parameters, $request->cookies->all(), array(), $request->server->all());
$controller = $this->resolver->getController($subRequest);
$arguments = $this->resolver->getArguments($request, $controller);
// call controller
return call_user_func_array($controller, $arguments);
}
/**
* {@inheritdoc}
*/
public function isContextual()
{
return true;
}
} | {
"content_hash": "5e7763e7f5ef0ba2117d1b5972052b6b",
"timestamp": "",
"source": "github",
"line_count": 188,
"max_line_length": 136,
"avg_line_length": 26.382978723404257,
"alnum_prop": 0.5816532258064516,
"repo_name": "petitp/SonataCacheBundleAlt",
"id": "42e405b4b747e243ad893e2bdac4f0df1d3c3095",
"size": "5199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Adapter/EsiCache.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "97199"
}
],
"symlink_target": ""
} |
'use strict';
var fs = require('fs')
, logEvents = require('../../lib/log-events')
, Images = require('../../').Images
, Containers = require('../../').Containers
, createDocker = require('../../').createDocker
, dockerhost = process.env.DOCKER_HOST
, testUnoTar = __dirname + '/../fixtures/test-uno.tar'
, testDosTar = __dirname + '/../fixtures/test-dos.tar'
, toastUnoTar = __dirname + '/../fixtures/toast-uno.tar'
var docker = createDocker(dockerhost);
var images = new Images(docker);
logEvents(images, 'silly');
var containers = new Containers(docker);
logEvents(containers, 'silly');
function wipeGroup(group, cb) {
containers
.stopRemoveGroup(group, function (err, res) {
if (err) return cb(err);
images.removeGroup(group, cb);
});
}
function build(img, tar, cb) {
images.build(fs.createReadStream(tar), img, function (err) {
if (err) return cb(err);
cb();
})
}
function setup(cb) {
wipeGroup('test', function (err) {
if (err) return cb(err);
wipeGroup('toast', cb);
});
}
exports.findImage = function findImage(img, name) {
for (var i = 0; i < img.length; i++) {
if (img[i].RepoTags[0] === name) return img[i];
}
}
exports.findContainer = function (cont, imageName) {
for (var i = 0; i < cont.length; i++) {
if (cont[i].Image === imageName) return cont[i];
}
}
exports.testToastImages = function setupTestToast(t) {
setup(function (err) {
if (err) { t.fail(err); return t.end(); }
build('test:uno', testUnoTar, function () {
// prevent timeout by talking to tap a bit
t.pass('built test:uno')
build('test:dos', testDosTar, function () {
// prevent timeout by talking to tap a bit more
t.pass('built test:dos')
build('toast:uno', toastUnoTar, t.end.bind(t))
})
})
})
}
exports.images = images;
exports.containers = containers;
| {
"content_hash": "28cecf674bed5ac6df3a49b701911e6c",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 62,
"avg_line_length": 26.65277777777778,
"alnum_prop": 0.607608129233976,
"repo_name": "thlorenz/dockops",
"id": "f4b1a5f37430e8389f5a1980091d2a3a894e36a0",
"size": "1919",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/utils/setup.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "39989"
},
{
"name": "Shell",
"bytes": "389"
}
],
"symlink_target": ""
} |
package com.planet_ink.coffee_mud.Common;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.exceptions.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import org.mozilla.javascript.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@SuppressWarnings("unchecked")
public class DefaultScriptingEngine implements ScriptingEngine
{
public String ID(){return "DefaultScriptingEngine";}
public String name(){return "Default Scripting Engine";}
protected static final Hashtable funcH=new Hashtable();
protected static final Hashtable methH=new Hashtable();
protected static final Hashtable progH=new Hashtable();
protected static final Hashtable connH=new Hashtable();
protected static final Hashtable gstatH=new Hashtable();
protected static final Hashtable signH=new Hashtable();
protected static Hashtable patterns=new Hashtable();
protected boolean noDelay=CMSecurity.isDisabled("SCRIPTABLEDELAY");
protected String scope="";
protected long tickStatus=Tickable.STATUS_NOT;
protected boolean isSavable=true;
protected MOB lastToHurtMe=null;
protected Room lastKnownLocation=null;
protected Tickable altStatusTickable=null;
protected Vector que=new Vector();
protected Vector oncesDone=new Vector();
protected Hashtable delayTargetTimes=new Hashtable();
protected Hashtable delayProgCounters=new Hashtable();
protected Hashtable lastTimeProgsDone=new Hashtable();
protected Hashtable lastDayProgsDone=new Hashtable();
protected HashSet registeredSpecialEvents=new HashSet();
protected Hashtable noTrigger=new Hashtable();
protected MOB backupMOB=null;
protected CMMsg lastMsg=null;
protected Resources resources=Resources.instance();
protected Environmental lastLoaded=null;
protected String myScript="";
protected String defaultQuestName="";
public DefaultScriptingEngine()
{
super();
CMClass.bumpCounter(this,CMClass.OBJECT_COMMON);
}
public boolean isSavable(){ return isSavable;}
public void setSavable(boolean truefalse){isSavable=truefalse;}
public String defaultQuestName(){ return defaultQuestName;}
protected Quest defaultQuest() {
if(defaultQuestName.length()==0)
return null;
return CMLib.quests().fetchQuest(defaultQuestName);
}
public void setVarScope(String newScope){
if((newScope==null)||(newScope.trim().length()==0))
{
scope="";
resources=Resources.instance();
}
else
scope=newScope.toUpperCase().trim();
if(scope.equalsIgnoreCase("*"))
resources = Resources.newResources();
else
{
resources=(Resources)Resources.getResource("VARSCOPE-"+scope);
if(resources==null)
{
resources = Resources.newResources();
Resources.submitResource("VARSCOPE-"+scope,resources);
}
}
}
public String getVarScope() { return scope;}
protected Object[] newObjs() { return new Object[ScriptingEngine.SPECIAL_NUM_OBJECTS];}
public String getLocalVarXML()
{
if((scope==null)||(scope.length()==0)) return "";
StringBuffer str=new StringBuffer("");
Vector V=resources._findResourceKeys("SCRIPTVAR-");
for(int v=0;v<V.size();v++)
{
String key=(String)V.elementAt(v);
if(key.startsWith("SCRIPTVAR-"))
{
str.append("<"+key.substring(10)+">");
Hashtable H=(Hashtable)resources._getResource(key);
for(Enumeration e=H.keys();e.hasMoreElements();)
{
String vn=(String)e.nextElement();
String val=(String)H.get(vn);
str.append("<"+vn+">"+CMLib.xml().parseOutAngleBrackets(val)+"</"+vn+">");
}
str.append("</"+key.substring(10)+">");
}
}
return str.toString();
}
public void setLocalVarXML(String xml)
{
Vector V=resources._findResourceKeys("SCRIPTVAR-");
for(int v=0;v<V.size();v++)
{
String key=(String)V.elementAt(v);
if(key.startsWith("SCRIPTVAR-"))
resources._removeResource(key);
}
V=CMLib.xml().parseAllXML(xml);
for(int v=0;v<V.size();v++)
{
XMLLibrary.XMLpiece piece=(XMLLibrary.XMLpiece)V.elementAt(v);
if((piece.contents!=null)&&(piece.contents.size()>0))
{
String kkey="SCRIPTVAR-"+piece.tag;
Hashtable H=new Hashtable();
for(int c=0;c<piece.contents.size();c++)
{
XMLLibrary.XMLpiece piece2=(XMLLibrary.XMLpiece)piece.contents.elementAt(c);
H.put(piece2.tag,piece2.value);
}
resources._submitResource(kkey,H);
}
}
}
private Quest getQuest(String named)
{
if((defaultQuestName.length()>0)&&(named.equals("*")||named.equalsIgnoreCase(defaultQuestName)))
return defaultQuest();
Quest Q=null;
for(int i=0;i<CMLib.quests().numQuests();i++)
{
try{Q=CMLib.quests().fetchQuest(i);}catch(Exception e){}
if(Q!=null)
{
if(Q.name().equalsIgnoreCase(named))
if(Q.running()) return Q;
}
}
return CMLib.quests().fetchQuest(named);
}
public long getTickStatus()
{
Tickable T=altStatusTickable;
if(T!=null) return T.getTickStatus();
return tickStatus;
}
public void registerDefaultQuest(String qName){
if((qName==null)||(qName.trim().length()==0))
defaultQuestName="";
else
defaultQuestName=qName.trim();
}
public CMObject newInstance()
{
try
{
return (ScriptingEngine)this.getClass().newInstance();
}
catch(Exception e)
{
Log.errOut(ID(),e);
}
return new DefaultScriptingEngine();
}
public CMObject copyOf()
{
try
{
ScriptingEngine S=(ScriptingEngine)this.clone();
CMClass.bumpCounter(S,CMClass.OBJECT_COMMON);
S.setScript(getScript());
return S;
}
catch(CloneNotSupportedException e)
{
return new DefaultScriptingEngine();
}
}
protected void finalize(){CMClass.unbumpCounter(this,CMClass.OBJECT_COMMON);}
/**
* c=clean bit, r=pastbitclean, p=pastbit, s=remaining clean bits, t=trigger
*/
protected String[] parseBits(DVector script, int row, String instructions)
{
String line=(String)script.elementAt(row,1);
String[] newLine=parseBits(line,instructions);
script.setElementAt(row,2,newLine);
return newLine;
}
protected String[] parseSpecial3PartEval(String[][] eval, int t)
{
String[] tt=eval[0];
String funcParms=tt[t];
String[] tryTT=parseBits(funcParms,"ccr");
if(signH.containsKey(tryTT[1]))
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
else
{
String[] parsed=null;
if(CMParms.cleanBit(funcParms).equals(funcParms))
parsed=parseBits("'"+funcParms+"' . .","cr");
else
parsed=parseBits(funcParms+" . .","cr");
tt=insertStringArray(tt,parsed,t);
eval[0]=tt;
}
return tt;
}
/**
* c=clean bit, r=pastbitclean, p=pastbit, s=remaining clean bits, t=trigger
*/
protected String[] parseBits(String line, String instructions)
{
String[] newLine=new String[instructions.length()];
for(int i=0;i<instructions.length();i++)
switch(instructions.charAt(i))
{
case 'c': newLine[i]=CMParms.getCleanBit(line,i); break;
case 'C': newLine[i]=CMParms.getCleanBit(line,i).toUpperCase().trim(); break;
case 'r': newLine[i]=CMParms.getPastBitClean(line,i-1); break;
case 'R': newLine[i]=CMParms.getPastBitClean(line,i-1).toUpperCase().trim(); break;
case 'p': newLine[i]=CMParms.getPastBit(line,i-1); break;
case 'P': newLine[i]=CMParms.getPastBit(line,i-1).toUpperCase().trim(); break;
case 'S': line=line.toUpperCase();
case 's':
{
String s=CMParms.getPastBit(line,i-1);
int numBits=CMParms.numBits(s);
String[] newNewLine=new String[newLine.length-1+numBits];
for(int x=0;x<i;x++)
newNewLine[x]=newLine[x];
for(int x=0;x<numBits;x++)
newNewLine[i+x]=CMParms.getCleanBit(s,i-1);
newLine=newNewLine;
i=instructions.length();
break;
}
case 'T': line=line.toUpperCase();
case 't':
{
String s=CMParms.getPastBit(line,i-1);
String[] newNewLine=null;
if(CMParms.getCleanBit(s,0).equalsIgnoreCase("P"))
{
newNewLine=new String[newLine.length+1];
for(int x=0;x<i;x++)
newNewLine[x]=newLine[x];
newNewLine[i]="P";
newNewLine[i+1]=CMParms.getPastBitClean(s,0);
}
else
{
int numNewBits=(s.trim().length()==0)?1:CMParms.numBits(s);
newNewLine=new String[newLine.length-1+numNewBits];
for(int x=0;x<i;x++)
newNewLine[x]=newLine[x];
for(int x=0;x<numNewBits;x++)
newNewLine[i+x]=CMParms.getCleanBit(s,x);
}
newLine=newNewLine;
i=instructions.length();
break;
}
}
return newLine;
}
protected String[] insertStringArray(String[] oldS, String[] inS, int where)
{
String[] newLine=new String[oldS.length+inS.length-1];
for(int i=0;i<where;i++)
newLine[i]=oldS[i];
for(int i=0;i<inS.length;i++)
newLine[where+i]=inS[i];
for(int i=where+1;i<oldS.length;i++)
newLine[inS.length+i-1]=oldS[i];
return newLine;
}
/**
* c=clean bit, r=pastbitclean, p=pastbit, s=remaining clean bits, t=trigger
*/
protected String[] parseBits(String[][] oldBits, int start, String instructions)
{
String[] tt=(String[])oldBits[0];
String parseMe=tt[start];
String[] parsed=parseBits(parseMe,instructions);
if(parsed.length==1)
{
tt[start]=parsed[0];
return tt;
}
String[] newLine=insertStringArray(tt,parsed,start);
oldBits[0]=newLine;
return newLine;
}
public boolean endQuest(Environmental hostObj, MOB mob, String quest)
{
if(mob!=null)
{
Vector scripts=getScripts();
if(!mob.amDead()) lastKnownLocation=mob.location();
String trigger="";
String[] tt=null;
for(int v=0;v<scripts.size();v++)
{
DVector script=(DVector)scripts.elementAt(v);
if(script.size()>0)
{
trigger=((String)script.elementAt(0,1)).toUpperCase().trim();
tt=(String[])script.elementAt(0,2);
if((getTriggerCode(trigger,tt)==13) //questtimeprog
&&(!oncesDone.contains(script)))
{
if(tt==null) tt=parseBits(script,0,"CCC");
if((tt[1].equals(quest)||(tt[1].equals("*")))
&&(CMath.s_int(tt[2])<0))
{
oncesDone.addElement(script);
execute(hostObj,mob,mob,mob,null,null,script,null,newObjs());
return true;
}
}
}
}
}
return false;
}
public Vector externalFiles()
{
Vector xmlfiles=new Vector();
parseLoads(getScript(), 0, xmlfiles, null);
return xmlfiles;
}
protected String getVarHost(Environmental E,
String rawHost,
MOB source,
Environmental target,
Environmental scripted,
MOB monster,
Item primaryItem,
Item secondaryItem,
String msg,
Object[] tmp)
{
if(!rawHost.equals("*"))
{
if(E==null)
rawHost=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,rawHost);
else
if(E instanceof Room)
rawHost=CMLib.map().getExtendedRoomID((Room)E);
else
rawHost=E.Name();
}
return rawHost;
}
public boolean isVar(String host, String var) {
if(host.equalsIgnoreCase("*"))
{
Vector V=resources._findResourceKeys("SCRIPTVAR-");
String val=null;
Hashtable H=null;
String key=null;
var=var.toUpperCase();
for(int v=0;v<V.size();v++)
{
key=(String)V.elementAt(v);
if(key.startsWith("SCRIPTVAR-"))
{
H=(Hashtable)resources._getResource(key);
val=(String)H.get(var);
if(val!=null) return true;
}
}
return false;
}
Hashtable H=(Hashtable)resources._getResource("SCRIPTVAR-"+host);
String val=null;
if(H!=null)
val=(String)H.get(var.toUpperCase());
return (val!=null);
}
public String getVar(Environmental E, String rawHost, String var, MOB source, Environmental target,
Environmental scripted, MOB monster, Item primaryItem, Item secondaryItem, String msg,
Object[] tmp)
{ return getVar(getVarHost(E,rawHost,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp),var); }
public String getVar(String host, String var)
{
if(host.equalsIgnoreCase("*"))
{
if(var.equals("COFFEEMUD_SYSTEM_INTERNAL_NONFILENAME_SCRIPT"))
{
StringBuffer str=new StringBuffer("");
parseLoads(getScript(),0,null,str);
return str.toString();
}
Vector V=resources._findResourceKeys("SCRIPTVAR-");
String val=null;
Hashtable H=null;
String key=null;
var=var.toUpperCase();
for(int v=0;v<V.size();v++)
{
key=(String)V.elementAt(v);
if(key.startsWith("SCRIPTVAR-"))
{
H=(Hashtable)resources._getResource(key);
val=(String)H.get(var);
if(val!=null) return val;
}
}
return "";
}
Hashtable H=(Hashtable)resources._getResource("SCRIPTVAR-"+host);
String val=null;
if(H!=null)
val=(String)H.get(var.toUpperCase());
else
if((defaultQuestName!=null)&&(defaultQuestName.length()>0))
{
MOB M=CMLib.players().getPlayer(host);
if(M!=null)
for(int s=0;s<M.numScripts();s++)
{
ScriptingEngine E=M.fetchScript(s);
if((E!=null)
&&(E!=this)
&&(defaultQuestName.equalsIgnoreCase(E.defaultQuestName()))
&&(E.isVar(host,var)))
return E.getVar(host,var);
}
}
if(val==null) return "";
return val;
}
private StringBuffer getResourceFileData(String named)
{
if(getQuest("*")!=null) return getQuest("*").getResourceFileData(named);
return new CMFile(Resources.makeFileResourceName(named),null,true).text();
}
public String getScript(){ return myScript;}
public void setScript(String newParms)
{
newParms=CMStrings.replaceAll(newParms,"'","`");
if(newParms.startsWith("+"))
{
String superParms=getScript();
if(superParms.length()>100)
Resources.removeResource("PARSEDPRG: "+superParms.substring(0,100)+superParms.length()+superParms.hashCode());
else
Resources.removeResource("PARSEDPRG: "+superParms);
newParms=superParms+";"+newParms.substring(1);
}
que=new Vector();
oncesDone=new Vector();
delayTargetTimes=new Hashtable();
delayProgCounters=new Hashtable();
lastTimeProgsDone=new Hashtable();
lastDayProgsDone=new Hashtable();
registeredSpecialEvents=new HashSet();
noTrigger=new Hashtable();
myScript=newParms;
if(oncesDone.size()>0)
oncesDone.clear();
}
public boolean canActAtAll(Tickable affecting)
{ return CMLib.flags().canActAtAll(affecting);}
public boolean canFreelyBehaveNormal(Tickable affecting)
{ return CMLib.flags().canFreelyBehaveNormal(affecting);}
protected String parseLoads(String text, int depth, Vector filenames, StringBuffer nonFilenameScript)
{
StringBuffer results=new StringBuffer("");
String parse=text;
if(depth>10) return ""; // no including off to infinity
String p=null;
while(parse.length()>0)
{
int y=parse.toUpperCase().indexOf("LOAD=");
if(y>=0)
{
p=parse.substring(0,y).trim();
if((!p.endsWith(";"))
&&(!p.endsWith("\n"))
&&(!p.endsWith("~"))
&&(!p.endsWith("\r"))
&&(p.length()>0))
{
if(nonFilenameScript!=null)
nonFilenameScript.append(parse.substring(0,y+1));
results.append(parse.substring(0,y+1));
parse=parse.substring(y+1);
continue;
}
results.append(p+"\n");
int z=parse.indexOf("~",y);
while((z>0)&&(parse.charAt(z-1)=='\\'))
z=parse.indexOf("~",z+1);
if(z>0)
{
String filename=parse.substring(y+5,z).trim();
parse=parse.substring(z+1);
if((filenames!=null)&&(!filenames.contains(filename)))
filenames.addElement(filename);
results.append(parseLoads(getResourceFileData(filename).toString(),depth+1,filenames,null));
}
else
{
String filename=parse.substring(y+5).trim();
if((filenames!=null)&&(!filenames.contains(filename)))
filenames.addElement(filename);
results.append(parseLoads(getResourceFileData(filename).toString(),depth+1,filenames,null));
break;
}
}
else
{
if(nonFilenameScript!=null)
nonFilenameScript.append(parse);
results.append(parse);
break;
}
}
return results.toString();
}
protected Vector parseScripts(String text)
{
synchronized(funcH)
{
if(funcH.size()==0)
{
for(int i=0;i<funcs.length;i++)
funcH.put(funcs[i],Integer.valueOf(i+1));
for(int i=0;i<methods.length;i++)
methH.put(methods[i],Integer.valueOf(i+1));
for(int i=0;i<progs.length;i++)
progH.put(progs[i],Integer.valueOf(i+1));
for(int i=0;i<CONNECTORS.length;i++)
connH.put(CONNECTORS[i],Integer.valueOf(i));
for(int i=0;i<GSTATCODES_ADDITIONAL.length;i++)
gstatH.put(GSTATCODES_ADDITIONAL[i],Integer.valueOf(i));
for(int i=0;i<SIGNS.length;i++)
signH.put(SIGNS[i],Integer.valueOf(i));
}
}
Vector V=new Vector();
text=parseLoads(text,0,null,null);
int y=0;
while((text!=null)&&(text.length()>0))
{
y=text.indexOf("~");
while((y>0)&&(text.charAt(y-1)=='\\'))
y=text.indexOf("~",y+1);
String script="";
if(y<0)
{
script=text.trim();
text="";
}
else
{
script=text.substring(0,y).trim();
text=text.substring(y+1).trim();
}
if(script.length()>0)
V.addElement(script);
}
for(int v=0;v<V.size();v++)
{
String s=(String)V.elementAt(v);
DVector script=new DVector(2);
while(s.length()>0)
{
y=-1;
int yy=0;
while(yy<s.length())
if((s.charAt(yy)==';')&&((yy<=0)||(s.charAt(yy-1)!='\\'))) {y=yy;break;}
else
if(s.charAt(yy)=='\n'){y=yy;break;}
else
if(s.charAt(yy)=='\r'){y=yy;break;}
else yy++;
String cmd="";
if(y<0)
{
cmd=s.trim();
s="";
}
else
{
cmd=s.substring(0,y).trim();
s=s.substring(y+1).trim();
}
if((cmd.length()>0)&&(!cmd.startsWith("#")))
{
cmd=CMStrings.replaceAll(cmd,"\\~","~");
cmd=CMStrings.replaceAll(cmd,"\\=","=");
script.addElement(CMStrings.replaceAll(cmd,"\\;",";"),null);
}
}
V.setElementAt(script,v);
}
V.trimToSize();
return V;
}
protected Room getRoom(String thisName, Room imHere)
{
if(thisName.length()==0) return null;
if((imHere!=null)&&(imHere.roomID().equalsIgnoreCase(thisName)))
return imHere;
Room room=CMLib.map().getRoom(thisName);
if((room!=null)&&(room.roomID().equalsIgnoreCase(thisName)))
return room;
Vector rooms=new Vector(1);
if((imHere!=null)&&(imHere.getArea()!=null))
rooms=CMLib.map().findAreaRoomsLiberally(null, imHere.getArea(), thisName, "RIEPM",100);
if(rooms.size()==0)
rooms=CMLib.map().findWorldRoomsLiberally(null,thisName, "RIEPM",100,10);
if(rooms.size()>0) return (Room)rooms.elementAt(CMLib.dice().roll(1,rooms.size(),-1));
return room;
}
protected void logError(Environmental scripted, String cmdName, String errType, String errMsg)
{
if(scripted!=null)
{
Room R=CMLib.map().roomLocation(scripted);
Log.errOut("Scripting",scripted.name()+"/"+CMLib.map().getExtendedRoomID(R)+"/"+ cmdName+"/"+errType+"/"+errMsg);
if(R!=null) R.showHappens(CMMsg.MSG_OK_VISUAL,"Scripting Error: "+scripted.name()+"/"+CMLib.map().getExtendedRoomID(R)+"/"+CMParms.toStringList(externalFiles())+"/"+ cmdName+"/"+errType+"/"+errMsg);
}
else
Log.errOut("Scripting","*/*/"+CMParms.toStringList(externalFiles())+"/"+cmdName+"/"+errType+"/"+errMsg);
}
protected boolean simpleEvalStr(Environmental scripted,
String arg1,
String arg2,
String cmp,
String cmdName)
{
int x=arg1.compareToIgnoreCase(arg2);
Integer SIGN=(Integer)signH.get(cmp);
if(SIGN==null)
{
logError(scripted,cmdName,"Syntax",arg1+" "+cmp+" "+arg2);
return false;
}
switch(SIGN.intValue())
{
case SIGN_EQUL: return (x==0);
case SIGN_EQGT:
case SIGN_GTEQ: return (x==0)||(x>0);
case SIGN_EQLT:
case SIGN_LTEQ: return (x==0)||(x<0);
case SIGN_GRAT: return (x>0);
case SIGN_LEST: return (x<0);
case SIGN_NTEQ: return (x!=0);
default: return (x==0);
}
}
protected boolean simpleEval(Environmental scripted, String arg1, String arg2, String cmp, String cmdName)
{
long val1=CMath.s_long(arg1.trim());
long val2=CMath.s_long(arg2.trim());
Integer SIGN=(Integer)signH.get(cmp);
if(SIGN==null)
{
logError(scripted,cmdName,"Syntax",val1+" "+cmp+" "+val2);
return false;
}
switch(SIGN.intValue())
{
case SIGN_EQUL: return (val1==val2);
case SIGN_EQGT:
case SIGN_GTEQ: return val1>=val2;
case SIGN_EQLT:
case SIGN_LTEQ: return val1<=val2;
case SIGN_GRAT: return (val1>val2);
case SIGN_LEST: return (val1<val2);
case SIGN_NTEQ: return (val1!=val2);
default: return (val1==val2);
}
}
protected boolean simpleExpressionEval(Environmental scripted, String arg1, String arg2, String cmp, String cmdName)
{
double val1=CMath.s_parseMathExpression(arg1.trim());
double val2=CMath.s_parseMathExpression(arg2.trim());
Integer SIGN=(Integer)signH.get(cmp);
if(SIGN==null)
{
logError(scripted,cmdName,"Syntax",val1+" "+cmp+" "+val2);
return false;
}
switch(SIGN.intValue())
{
case SIGN_EQUL: return (val1==val2);
case SIGN_EQGT:
case SIGN_GTEQ: return val1>=val2;
case SIGN_EQLT:
case SIGN_LTEQ: return val1<=val2;
case SIGN_GRAT: return (val1>val2);
case SIGN_LEST: return (val1<val2);
case SIGN_NTEQ: return (val1!=val2);
default: return (val1==val2);
}
}
protected Vector loadMobsFromFile(Environmental scripted, String filename)
{
filename=filename.trim();
Vector monsters=(Vector)Resources.getResource("RANDOMMONSTERS-"+filename);
if(monsters!=null) return monsters;
StringBuffer buf=getResourceFileData(filename);
String thangName="null";
Room R=CMLib.map().roomLocation(scripted);
if(R!=null)
thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted);
else
if(scripted!=null)
thangName=scripted.name();
if((buf==null)||(buf.length()<20))
{
logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName);
return null;
}
if(buf.substring(0,20).indexOf("<MOBS>")<0)
{
logError(scripted,"XMLLOAD","?","Invalid XML file: '"+filename+"' in "+thangName);
return null;
}
monsters=new Vector();
String error=CMLib.coffeeMaker().addMOBsFromXML(buf.toString(),monsters,null);
if(error.length()>0)
{
logError(scripted,"XMLLOAD","?","Error in XML file: '"+filename+"'");
return null;
}
if(monsters.size()<=0)
{
logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'");
return null;
}
Resources.submitResource("RANDOMMONSTERS-"+filename,monsters);
return monsters;
}
protected Vector loadItemsFromFile(Environmental scripted, String filename)
{
filename=filename.trim();
Vector items=(Vector)Resources.getResource("RANDOMITEMS-"+filename);
if(items!=null) return items;
StringBuffer buf=getResourceFileData(filename);
String thangName="null";
Room R=CMLib.map().roomLocation(scripted);
if(R!=null)
thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted);
else
if(scripted!=null)
thangName=scripted.name();
if((buf==null)||(buf.length()<20))
{
logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName);
return null;
}
if(buf.substring(0,20).indexOf("<ITEMS>")<0)
{
logError(scripted,"XMLLOAD","?","Invalid XML file: '"+filename+"' in "+thangName);
return null;
}
items=new Vector();
String error=CMLib.coffeeMaker().addItemsFromXML(buf.toString(),items,null);
if(error.length()>0)
{
logError(scripted,"XMLLOAD","?","Error in XML file: '"+filename+"'");
return null;
}
if(items.size()<=0)
{
logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'");
return null;
}
Resources.submitResource("RANDOMITEMS-"+filename,items);
return items;
}
protected Environmental findSomethingCalledThis(String thisName, MOB meMOB, Room imHere, Vector OBJS, boolean mob)
{
if(thisName.length()==0) return null;
Environmental thing=null;
Environmental areaThing=null;
if(thisName.toUpperCase().trim().startsWith("FROMFILE "))
{
try{
Vector V=null;
if(mob)
V=loadMobsFromFile(null,CMParms.getCleanBit(thisName,1));
else
V=loadItemsFromFile(null,CMParms.getCleanBit(thisName,1));
if(V!=null)
{
String name=CMParms.getPastBitClean(thisName,1);
if(name.equalsIgnoreCase("ALL"))
OBJS=V;
else
if(name.equalsIgnoreCase("ANY"))
{
if(V.size()>0)
areaThing=(Environmental)V.elementAt(CMLib.dice().roll(1,V.size(),-1));
}
else
{
areaThing=CMLib.english().fetchEnvironmental(V,name,true);
if(areaThing==null)
areaThing=CMLib.english().fetchEnvironmental(V,name,false);
}
}
}
catch(Exception e){}
}
else
{
if(!mob)
areaThing=(meMOB!=null)?meMOB.fetchInventory(thisName):null;
try
{
if(areaThing==null)
{
Area A=imHere.getArea();
Vector all=new Vector();
if(mob)
{
all.addAll(CMLib.map().findInhabitants(A.getProperMap(),null,thisName,100));
if(all.size()==0)
all.addAll(CMLib.map().findShopStock(A.getProperMap(), null, thisName,100));
for(int a=all.size()-1;a>=0;a--)
if(!(all.elementAt(a) instanceof MOB))
all.removeElementAt(a);
if(all.size()>0)
areaThing=(Environmental)all.elementAt(CMLib.dice().roll(1,all.size(),-1));
else
{
all.addAll(CMLib.map().findInhabitants(CMLib.map().rooms(),null,thisName,100));
if(all.size()==0)
all.addAll(CMLib.map().findShopStock(CMLib.map().rooms(), null, thisName,100));
for(int a=all.size()-1;a>=0;a--)
if(!(all.elementAt(a) instanceof MOB))
all.removeElementAt(a);
if(all.size()>0)
thing=(Environmental)all.elementAt(CMLib.dice().roll(1,all.size(),-1));
}
}
if(all.size()==0)
{
all.addAll(CMLib.map().findRoomItems(A.getProperMap(), null,thisName,true,100));
if(all.size()==0)
all.addAll(CMLib.map().findInventory(A.getProperMap(), null,thisName,100));
if(all.size()==0)
all.addAll(CMLib.map().findShopStock(A.getProperMap(), null,thisName,100));
if(all.size()>0)
areaThing=(Environmental)all.elementAt(CMLib.dice().roll(1,all.size(),-1));
else
{
all.addAll(CMLib.map().findRoomItems(CMLib.map().rooms(), null,thisName,true,100));
if(all.size()==0)
all.addAll(CMLib.map().findInventory(CMLib.map().rooms(), null,thisName,100));
if(all.size()==0)
all.addAll(CMLib.map().findShopStock(CMLib.map().rooms(), null,thisName,100));
if(all.size()>0)
thing=(Environmental)all.elementAt(CMLib.dice().roll(1,all.size(),-1));
}
}
}
}catch(NoSuchElementException nse){}
}
if(areaThing!=null)
OBJS.addElement(areaThing);
else
if(thing!=null)
OBJS.addElement(thing);
if(OBJS.size()>0)
return (Environmental)OBJS.firstElement();
return null;
}
protected Environmental getArgumentMOB(String str,
MOB source,
MOB monster,
Environmental target,
Item primaryItem,
Item secondaryItem,
String msg,
Object[] tmp)
{
return getArgumentItem(str,source,monster,monster,target,primaryItem,secondaryItem,msg,tmp);
}
protected Environmental getArgumentItem(String str,
MOB source,
MOB monster,
Environmental scripted,
Environmental target,
Item primaryItem,
Item secondaryItem,
String msg,
Object[] tmp)
{
if(str.length()<2) return null;
if(str.charAt(0)=='$')
{
if(Character.isDigit(str.charAt(1)))
{
Object O=tmp[CMath.s_int(Character.toString(str.charAt(1)))];
if(O instanceof Environmental)
return (Environmental)O;
else
if((O instanceof Vector)&&(str.length()>3)&&(str.charAt(2)=='.'))
{
Vector V=(Vector)O;
String back=str.substring(2);
if(back.charAt(1)=='$')
back=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,back);
if((back.length()>1)&&Character.isDigit(back.charAt(1)))
{
int x=1;
while((x<back.length())&&(Character.isDigit(back.charAt(x)))) x++;
int y=CMath.s_int(back.substring(1,x).trim());
if((V.size()>0)&&(y>=0))
{
if(y>=V.size()) return null;
O=V.elementAt(y);
if(O instanceof Environmental) return (Environmental)O;
}
str=O.toString(); // will fall through
}
}
else
if(O!=null)
str=O.toString(); // will fall through
else
return null;
}
else
switch(str.charAt(1))
{
case 'a': return (lastKnownLocation!=null)?lastKnownLocation.getArea():null;
case 'B':
case 'b': return lastLoaded;
case 'N':
case 'n': return ((source==backupMOB)&&(backupMOB!=null)&&(monster!=scripted))?scripted:source;
case 'I':
case 'i': return scripted;
case 'T':
case 't': return ((target==backupMOB)&&(backupMOB!=null)&&(monster!=scripted))?scripted:target;
case 'O':
case 'o': return primaryItem;
case 'P':
case 'p': return secondaryItem;
case 'd':
case 'D': return lastKnownLocation;
case 'F':
case 'f': if((monster!=null)&&(monster.amFollowing()!=null))
return monster.amFollowing();
return null;
case 'r':
case 'R': return getRandPC(monster,tmp,lastKnownLocation);
case 'c':
case 'C': return getRandAnyone(monster,tmp,lastKnownLocation);
case 'w': return primaryItem!=null?primaryItem.owner():null;
case 'W': return secondaryItem!=null?secondaryItem.owner():null;
case 'x':
case 'X':
if(lastKnownLocation!=null)
{
if((str.length()>2)&&(Directions.getGoodDirectionCode(""+str.charAt(2))>=0))
return lastKnownLocation.getExitInDir(Directions.getGoodDirectionCode(""+str.charAt(2)));
int i=0;
Exit E=null;
while(((++i)<100)||(E!=null))
E=lastKnownLocation.getExitInDir(CMLib.dice().roll(1,Directions.NUM_DIRECTIONS(),-1));
return E;
}
return null;
case '[':
{
int x=str.substring(2).indexOf("]");
if(x>=0)
{
String mid=str.substring(2).substring(0,x);
int y=mid.indexOf(" ");
if(y>0)
{
int num=CMath.s_int(mid.substring(0,y).trim());
mid=mid.substring(y+1).trim();
Quest Q=getQuest(mid);
if(Q!=null) return Q.getQuestItem(num);
}
}
}
break;
case '{':
{
int x=str.substring(2).indexOf("}");
if(x>=0)
{
String mid=str.substring(2).substring(0,x).trim();
int y=mid.indexOf(" ");
if(y>0)
{
int num=CMath.s_int(mid.substring(0,y).trim());
mid=mid.substring(y+1).trim();
Quest Q=getQuest(mid);
if(Q!=null) return Q.getQuestMob(num);
}
}
}
break;
}
}
if(lastKnownLocation!=null)
{
str=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,str);
Environmental E=lastKnownLocation.fetchFromRoomFavorMOBs(null,str,Wearable.FILTER_ANY);
if(E==null) E=lastKnownLocation.fetchFromMOBRoomFavorsItems(monster,null,str,Wearable.FILTER_ANY);
if(E==null) E=lastKnownLocation.fetchAnyItem(str);
if((E==null)&&(monster!=null)) E=monster.fetchInventory(str);
if(E==null) E=CMLib.players().getPlayer(str);
return E;
}
return null;
}
private String makeNamedString(Object O)
{
if(O instanceof Vector)
return makeParsableString((Vector)O);
else
if(O instanceof Room)
return ((Room)O).roomTitle(null);
else
if(O instanceof Environmental)
return ((Environmental)O).Name();
else
if(O!=null)
return O.toString();
return "";
}
private String makeParsableString(Vector V)
{
if((V==null)||(V.size()==0)) return "";
if(V.firstElement() instanceof String) return CMParms.combineWithQuotes(V,0);
StringBuffer ret=new StringBuffer("");
String S=null;
for(int v=0;v<V.size();v++)
{
S=makeNamedString(V.elementAt(v)).trim();
if(S.length()==0)
ret.append("? ");
else
if(S.indexOf(" ")>=0)
ret.append("\""+S+"\" ");
else
ret.append(S+" ");
}
return ret.toString();
}
protected String varify(MOB source,
Environmental target,
Environmental scripted,
MOB monster,
Item primaryItem,
Item secondaryItem,
String msg,
Object[] tmp,
String varifyable)
{
int t=varifyable.indexOf("$");
if((monster!=null)&&(monster.location()!=null))
lastKnownLocation=monster.location();
if(lastKnownLocation==null) lastKnownLocation=source.location();
MOB randMOB=null;
while((t>=0)&&(t<varifyable.length()-1))
{
char c=varifyable.charAt(t+1);
String middle="";
String front=varifyable.substring(0,t);
String back=varifyable.substring(t+2);
if(Character.isDigit(c))
middle=makeNamedString(tmp[CMath.s_int(Character.toString(c))]);
else
switch(c)
{
case '@':
if((t<varifyable.length()-2)&&Character.isLetter(varifyable.charAt(t+2)))
{
Environmental E=getArgumentItem("$"+varifyable.charAt(t+2),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
middle=(E==null)?"null":""+E;
}
break;
case 'a':
if(lastKnownLocation!=null)
middle=lastKnownLocation.getArea().name();
break;
//case 'a':
case 'A':
// unnecessary, since, in coffeemud, this is part of the name
break;
case 'b': middle=lastLoaded!=null?lastLoaded.name():""; break;
case 'B': middle=lastLoaded!=null?lastLoaded.displayText():""; break;
case 'c':
case 'C':
randMOB=getRandAnyone(monster,tmp,lastKnownLocation);
if(randMOB!=null)
middle=randMOB.name();
break;
case 'd': middle=(lastKnownLocation!=null)?lastKnownLocation.roomTitle(monster):""; break;
case 'D': middle=(lastKnownLocation!=null)?lastKnownLocation.roomDescription(monster):""; break;
case 'e':
if(source!=null)
middle=source.charStats().heshe();
break;
case 'E':
if((target!=null)&&(target instanceof MOB))
middle=((MOB)target).charStats().heshe();
break;
case 'f':
if((monster!=null)&&(monster.amFollowing()!=null))
middle=monster.amFollowing().name();
break;
case 'F':
if((monster!=null)&&(monster.amFollowing()!=null))
middle=monster.amFollowing().charStats().heshe();
break;
case 'g': middle=((msg==null)?"":msg.toLowerCase()); break;
case 'G': middle=((msg==null)?"":msg); break;
case 'h':
if(monster!=null)
middle=monster.charStats().himher();
break;
case 'H':
randMOB=getRandPC(monster,tmp,lastKnownLocation);
if(randMOB!=null)
middle=randMOB.charStats().himher();
break;
case 'i':
if(monster!=null)
middle=monster.name();
break;
case 'I':
if(monster!=null)
middle=monster.displayText();
break;
case 'j':
if(monster!=null)
middle=monster.charStats().heshe();
break;
case 'J':
randMOB=getRandPC(monster,tmp,lastKnownLocation);
if(randMOB!=null)
middle=randMOB.charStats().heshe();
break;
case 'k':
if(monster!=null)
middle=monster.charStats().hisher();
break;
case 'K':
randMOB=getRandPC(monster,tmp,lastKnownLocation);
if(randMOB!=null)
middle=randMOB.charStats().hisher();
break;
case 'l':
if(lastKnownLocation!=null)
{
StringBuffer str=new StringBuffer("");
for(int i=0;i<lastKnownLocation.numInhabitants();i++)
{
MOB M=lastKnownLocation.fetchInhabitant(i);
if((M!=null)&&(M!=monster)&&(CMLib.flags().canBeSeenBy(M,monster)))
str.append("\""+M.name()+"\" ");
}
middle=str.toString();
}
break;
case 'L':
if(lastKnownLocation!=null)
{
StringBuffer str=new StringBuffer("");
for(int i=0;i<lastKnownLocation.numItems();i++)
{
Item I=lastKnownLocation.fetchItem(i);
if((I!=null)&&(I.container()==null)&&(CMLib.flags().canBeSeenBy(I,monster)))
str.append("\""+I.name()+"\" ");
}
middle=str.toString();
}
break;
case 'm':
if(source!=null)
middle=source.charStats().hisher();
break;
case 'M':
if((target!=null)&&(target instanceof MOB))
middle=((MOB)target).charStats().hisher();
break;
case 'n':
case 'N':
if(source!=null)
middle=source.name();
break;
case 'o':
case 'O':
if(primaryItem!=null)
middle=primaryItem.name();
break;
case 'p':
case 'P':
if(secondaryItem!=null)
middle=secondaryItem.name();
break;
case 'r':
case 'R':
randMOB=getRandPC(monster,tmp,lastKnownLocation);
if(randMOB!=null)
middle=randMOB.name();
break;
case 's':
if(source!=null)
middle=source.charStats().himher();
break;
case 'S':
if((target!=null)&&(target instanceof MOB))
middle=((MOB)target).charStats().himher();
break;
case 't':
case 'T':
if(target!=null)
middle=target.name();
break;
case 'w':
middle=primaryItem!=null?primaryItem.owner().Name():middle;
break;
case 'W':
middle=secondaryItem!=null?secondaryItem.owner().Name():middle;
break;
case 'x':
case 'X':
if(lastKnownLocation!=null)
{
middle="";
Exit E=null;
int dir=-1;
if((t<varifyable.length()-2)&&(Directions.getGoodDirectionCode(""+varifyable.charAt(t+2))>=0))
{
dir=Directions.getGoodDirectionCode(""+varifyable.charAt(t+2));
E=lastKnownLocation.getExitInDir(dir);
}
else
{
int i=0;
while(((++i)<100)||(E!=null))
{
dir=CMLib.dice().roll(1,Directions.NUM_DIRECTIONS(),-1);
E=lastKnownLocation.getExitInDir(dir);
}
}
if((dir>=0)&&(E!=null))
{
if(c=='x')
middle=Directions.getDirectionName(dir);
else
middle=E.name();
}
}
break;
case 'y':
if(source!=null)
middle=source.charStats().sirmadam();
break;
case 'Y':
if((target!=null)&&(target instanceof MOB))
middle=((MOB)target).charStats().sirmadam();
break;
case '<':
{
int x=back.indexOf(">");
if(x>=0)
{
String mid=back.substring(0,x);
int y=mid.indexOf(" ");
Environmental E=null;
String arg1="";
if(y>=0)
{
arg1=mid.substring(0,y).trim();
E=getArgumentItem(arg1,source,monster,monster,target,primaryItem,secondaryItem,msg,tmp);
mid=mid.substring(y+1).trim();
}
if(arg1.length()>0)
middle=getVar(E,arg1,mid,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp);
back=back.substring(x+1);
}
}
break;
case '[':
{
middle="";
int x=back.indexOf("]");
if(x>=0)
{
String mid=back.substring(0,x);
int y=mid.indexOf(" ");
if(y>0)
{
int num=CMath.s_int(mid.substring(0,y).trim());
mid=mid.substring(y+1).trim();
Quest Q=getQuest(mid);
if(Q!=null) middle=Q.getQuestItemName(num);
}
back=back.substring(x+1);
}
}
break;
case '{':
{
middle="";
int x=back.indexOf("}");
if(x>=0)
{
String mid=back.substring(0,x).trim();
int y=mid.indexOf(" ");
if(y>0)
{
int num=CMath.s_int(mid.substring(0,y).trim());
mid=mid.substring(y+1).trim();
Quest Q=getQuest(mid);
if(Q!=null) middle=Q.getQuestMobName(num);
}
back=back.substring(x+1);
}
}
break;
case '%':
{
middle="";
int x=back.indexOf("%");
if(x>=0)
{
middle=functify(monster,source,target,monster,primaryItem,secondaryItem,msg,tmp,back.substring(0,x).trim());
back=back.substring(x+1);
}
}
break;
}
if((back.startsWith("."))
&&(back.length()>1))
{
if(back.charAt(1)=='$')
back=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,back);
if(back.equalsIgnoreCase(".LENGTH#"))
{
middle=""+CMParms.parse(middle).size();
back="";
}
else
if((back.length()>1)&&Character.isDigit(back.charAt(1)))
{
int x=1;
while((x<back.length())
&&(Character.isDigit(back.charAt(x))))
x++;
int y=CMath.s_int(back.substring(1,x).trim());
back=back.substring(x);
boolean rest=back.startsWith("..");
if(rest) back=back.substring(2);
Vector V=CMParms.parse(middle);
if((V.size()>0)&&(y>=0))
{
if(y>=V.size())
middle="";
else
if(rest)
middle=CMParms.combine(V,y);
else
middle=(String)V.elementAt(y);
}
}
}
varifyable=front+middle+back;
t=varifyable.indexOf("$");
}
return varifyable;
}
protected DVector getScriptVarSet(String mobname, String varname)
{
DVector set=new DVector(2);
if(mobname.equals("*"))
{
Vector V=resources._findResourceKeys("SCRIPTVAR-");
for(int v=0;v<V.size();v++)
{
String key=(String)V.elementAt(v);
if(key.startsWith("SCRIPTVAR-"))
{
Hashtable H=(Hashtable)resources._getResource(key);
if(varname.equals("*"))
{
for(Enumeration e=H.keys();e.hasMoreElements();)
{
String vn=(String)e.nextElement();
set.addElement(key.substring(10),vn);
}
}
else
set.addElement(key.substring(10),varname);
}
}
}
else
{
Hashtable H=(Hashtable)resources._getResource("SCRIPTVAR-"+mobname);
if(varname.equals("*"))
{
for(Enumeration e=H.keys();e.hasMoreElements();)
{
String vn=(String)e.nextElement();
set.addElement(mobname,vn);
}
}
else
set.addElement(mobname,varname);
}
return set;
}
protected String getStatValue(Environmental E, String arg2)
{
boolean found=false;
String val="";
for(int i=0;i<E.getStatCodes().length;i++)
{
if(E.getStatCodes()[i].equalsIgnoreCase(arg2))
{
val=E.getStat(arg2);
found=true;
break;
}
}
if((!found)&&(E instanceof MOB))
{
MOB M=(MOB)E;
for(int i : CharStats.CODES.ALL())
if(CharStats.CODES.NAME(i).equalsIgnoreCase(arg2)||CharStats.CODES.DESC(i).equalsIgnoreCase(arg2))
{
val=""+M.charStats().getStat(CharStats.CODES.NAME(i)); //yes, this is right
found=true;
break;
}
if(!found)
for(int i=0;i<M.curState().getStatCodes().length;i++)
if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2))
{
val=M.curState().getStat(M.curState().getStatCodes()[i]);
found=true;
break;
}
if(!found)
for(int i=0;i<M.envStats().getStatCodes().length;i++)
if(M.envStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
val=M.envStats().getStat(M.envStats().getStatCodes()[i]);
found=true;
break;
}
if((!found)&&(M.playerStats()!=null))
for(int i=0;i<M.playerStats().getStatCodes().length;i++)
if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
val=M.playerStats().getStat(M.playerStats().getStatCodes()[i]);
found=true;
break;
}
if((!found)&&(arg2.toUpperCase().startsWith("BASE")))
for(int i=0;i<M.baseState().getStatCodes().length;i++)
if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4)))
{
val=M.baseState().getStat(M.baseState().getStatCodes()[i]);
found=true;
break;
}
if((!found)&&(gstatH.containsKey(arg2.toUpperCase()))) {
found=true;
switch(((Integer)gstatH.get(arg2.toUpperCase())).intValue()) {
case GSTATADD_DEITY: val=M.getWorshipCharID(); break;
case GSTATADD_CLAN: val=M.getClanID(); break;
case GSTATADD_CLANROLE: val=""+M.getClanRole(); break;
}
}
}
if(!found)return null;
return val;
}
protected String getGStatValue(Environmental E, String arg2)
{
if(E==null) return null;
boolean found=false;
String val="";
for(int i=0;i<E.getStatCodes().length;i++)
{
if(E.getStatCodes()[i].equalsIgnoreCase(arg2))
{
val=E.getStat(arg2);
found=true; break;
}
}
if(!found)
if(E instanceof MOB)
{
for(int i=0;i<GenericBuilder.GENMOBCODES.length;i++)
{
if(GenericBuilder.GENMOBCODES[i].equalsIgnoreCase(arg2))
{
val=CMLib.coffeeMaker().getGenMobStat((MOB)E,GenericBuilder.GENMOBCODES[i]);
found=true; break;
}
}
if(!found)
{
MOB M=(MOB)E;
for(int i : CharStats.CODES.ALL())
if(CharStats.CODES.NAME(i).equalsIgnoreCase(arg2)||CharStats.CODES.DESC(i).equalsIgnoreCase(arg2))
{
val=""+M.charStats().getStat(CharStats.CODES.NAME(i));
found=true;
break;
}
if(!found)
for(int i=0;i<M.curState().getStatCodes().length;i++)
if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2))
{
val=M.curState().getStat(M.curState().getStatCodes()[i]);
found=true;
break;
}
if(!found)
for(int i=0;i<M.envStats().getStatCodes().length;i++)
if(M.envStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
val=M.envStats().getStat(M.envStats().getStatCodes()[i]);
found=true;
break;
}
if((!found)&&(M.playerStats()!=null))
for(int i=0;i<M.playerStats().getStatCodes().length;i++)
if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
val=M.playerStats().getStat(M.playerStats().getStatCodes()[i]);
found=true;
break;
}
if((!found)&&(arg2.toUpperCase().startsWith("BASE")))
for(int i=0;i<M.baseState().getStatCodes().length;i++)
if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4)))
{
val=M.baseState().getStat(M.baseState().getStatCodes()[i]);
found=true;
break;
}
if((!found)&&(gstatH.containsKey(arg2.toUpperCase()))) {
found=true;
switch(((Integer)gstatH.get(arg2.toUpperCase())).intValue()) {
case GSTATADD_DEITY: val=M.getWorshipCharID(); break;
case GSTATADD_CLAN: val=M.getClanID(); break;
case GSTATADD_CLANROLE: val=""+M.getClanRole(); break;
}
}
}
}
else
if(E instanceof Item)
{
for(int i=0;i<GenericBuilder.GENITEMCODES.length;i++)
{
if(GenericBuilder.GENITEMCODES[i].equalsIgnoreCase(arg2))
{
val=CMLib.coffeeMaker().getGenItemStat((Item)E,GenericBuilder.GENITEMCODES[i]);
found=true; break;
}
}
}
if(found) return val;
return null;
}
public void setVar(String name, String key, String val)
{
DVector V=getScriptVarSet(name,key);
for(int v=0;v<V.size();v++)
{
name=(String)V.elementAt(v,1);
key=((String)V.elementAt(v,2)).toUpperCase();
Hashtable H=(Hashtable)resources._getResource("SCRIPTVAR-"+name);
if((H==null)&&(defaultQuestName!=null)&&(defaultQuestName.length()>0))
{
MOB M=CMLib.players().getPlayer(name);
if(M!=null)
for(int s=0;s<M.numScripts();s++)
{
ScriptingEngine E=M.fetchScript(s);
if((E!=null)
&&(E!=this)
&&(defaultQuestName.equalsIgnoreCase(E.defaultQuestName()))
&&(E.isVar(name,key)))
{
E.setVar(name,key,val);
return;
}
}
}
if(H==null)
{
if(val.length()==0)
continue;
H=new Hashtable();
resources._submitResource("SCRIPTVAR-"+name,H);
}
if(val.equals("++"))
{
String num=(String)H.get(key);
if(num==null) num="0";
val=Integer.toString(CMath.s_int(num.trim())+1);
}
else
if(val.equals("--"))
{
String num=(String)H.get(key);
if(num==null) num="0";
val=Integer.toString(CMath.s_int(num.trim())-1);
}
else
if(val.startsWith("+"))
{
// add via +number form
val=val.substring(1);
int amount=CMath.s_int(val.trim());
String num=(String)H.get(key);
if(num==null) num="0";
val=Integer.toString(CMath.s_int(num.trim())+amount);
}
else
if(val.startsWith("-"))
{
// subtract -number form
val=val.substring(1);
int amount=CMath.s_int(val.trim());
String num=(String)H.get(key);
if(num==null) num="0";
val=Integer.toString(CMath.s_int(num.trim())-amount);
}
else
if(val.startsWith("*"))
{
// multiply via *number form
val=val.substring(1);
int amount=CMath.s_int(val.trim());
String num=(String)H.get(key);
if(num==null) num="0";
val=Integer.toString(CMath.s_int(num.trim())*amount);
}
else
if(val.startsWith("/"))
{
// divide /number form
val=val.substring(1);
int amount=CMath.s_int(val.trim());
String num=(String)H.get(key);
if(num==null) num="0";
val=Integer.toString(CMath.s_int(num.trim())/amount);
}
if(H.containsKey(key))
H.remove(key);
if(val.trim().length()>0)
H.put(key,val);
if(H.size()==0)
resources._removeResource("SCRIPTVAR-"+name);
}
}
public String[] parseEval(String evaluable) throws ScriptParseException
{
final int STATE_MAIN=0;
final int STATE_INFUNCTION=1;
final int STATE_INFUNCQUOTE=2;
final int STATE_POSTFUNCTION=3;
final int STATE_POSTFUNCEVAL=4;
final int STATE_POSTFUNCQUOTE=5;
final int STATE_MAYFUNCTION=6;
Vector V=new Vector();
if((evaluable==null)||(evaluable.trim().length()==0))
return new String[]{};
char[] evalC=evaluable.toCharArray();
int state=0;
int dex=0;
char lastQuote='\0';
String s=null;
int depth=0;
for(int c=0;c<evalC.length;c++)
switch(state) {
case STATE_MAIN:
{
if(Character.isWhitespace(evalC[c]))
{
s=new String(evalC,dex,c-dex).trim();
if(s.length()>0)
{
s=s.toUpperCase();
V.addElement(s);
dex=c+1;
if(funcH.containsKey(s))
state=STATE_MAYFUNCTION;
else
if(!connH.containsKey(s))
throw new ScriptParseException("Unknown keyword: "+s);
}
}
else
if(Character.isLetter(evalC[c]))
{ /* move along */ }
else
switch(evalC[c])
{
case '!':
{
if(c==evalC.length-1)
throw new ScriptParseException("Bad Syntax on last !");
V.addElement("NOT");
dex=c+1;
break;
}
case '(':
{
s=new String(evalC,dex,c-dex).trim();
if(s.length()>0)
{
s=s.toUpperCase();
V.addElement(s);
V.addElement("(");
dex=c+1;
if(funcH.containsKey(s))
state=STATE_INFUNCTION;
else
if(connH.containsKey(s))
state=STATE_MAIN;
else
throw new ScriptParseException("Unknown keyword: "+s);
}
else
{
V.addElement("(");
depth++;
dex=c+1;
}
break;
}
case ')':
s=new String(evalC,dex,c-dex).trim();
if(s.length()>0)
throw new ScriptParseException("Bad syntax before ) at: "+s);
if(depth==0)
throw new ScriptParseException("Unmatched ) character");
V.addElement(")");
depth--;
dex=c+1;
break;
default:
throw new ScriptParseException("Unknown character at: "+new String(evalC,dex,c-dex+1).trim()+": "+evaluable);
}
break;
}
case STATE_MAYFUNCTION:
{
if(evalC[c]=='(')
{
V.addElement("(");
dex=c+1;
state=STATE_INFUNCTION;
}
else
if(!Character.isWhitespace(evalC[c]))
throw new ScriptParseException("Expected ( at "+evalC[c]+": "+evaluable);
break;
}
case STATE_POSTFUNCTION:
{
if(!Character.isWhitespace(evalC[c]))
switch(evalC[c])
{
case '=': case '>': case '<': case '!':
{
if(c==evalC.length-1)
throw new ScriptParseException("Bad Syntax on last "+evalC[c]);
if(!Character.isWhitespace(evalC[c+1]))
{
s=new String(evalC,c,2);
if((!signH.containsKey(s))&&(evalC[c]!='!'))
s=""+evalC[c];
}
else
s=""+evalC[c];
if(!signH.containsKey(s))
{
c=dex-1;
state=STATE_MAIN;
break;
}
V.addElement(s);
dex=c+(s.length());
c=c+(s.length()-1);
state=STATE_POSTFUNCEVAL;
break;
}
default:
c=dex-1;
state=STATE_MAIN;
break;
}
break;
}
case STATE_INFUNCTION:
{
if(evalC[c]==')')
{
V.addElement(new String(evalC,dex,c-dex));
V.addElement(")");
dex=c+1;
state=STATE_POSTFUNCTION;
}
else
if((evalC[c]=='\'')||(evalC[c]=='`'))
{
lastQuote=evalC[c];
state=STATE_INFUNCQUOTE;
}
break;
}
case STATE_INFUNCQUOTE:
{
if(evalC[c]==lastQuote)
state=STATE_INFUNCTION;
break;
}
case STATE_POSTFUNCQUOTE:
{
if(evalC[c]==lastQuote)
{
if((V.size()>2)
&&(signH.containsKey((String)V.lastElement()))
&&(((String)V.elementAt(V.size()-2)).equals(")")))
{
String sign=(String)V.lastElement();
V.removeElementAt(V.size()-1);
V.removeElementAt(V.size()-1);
String prev=(String)V.lastElement();
if(prev.equals("("))
s=sign+" "+new String(evalC,dex+1,c-dex);
else
{
V.removeElementAt(V.size()-1);
s=prev+" "+sign+" "+new String(evalC,dex+1,c-dex);
}
V.addElement(s);
V.addElement(")");
dex=c+1;
state=STATE_MAIN;
}
else
throw new ScriptParseException("Bad postfunc Eval somewhere");
}
break;
}
case STATE_POSTFUNCEVAL:
{
if(Character.isWhitespace(evalC[c]))
{
s=new String(evalC,dex,c-dex).trim();
if(s.length()>0)
{
if((V.size()>1)
&&(signH.containsKey((String)V.lastElement()))
&&(((String)V.elementAt(V.size()-2)).equals(")")))
{
String sign=(String)V.lastElement();
V.removeElementAt(V.size()-1);
V.removeElementAt(V.size()-1);
String prev=(String)V.lastElement();
if(prev.equals("("))
s=sign+" "+new String(evalC,dex+1,c-dex);
else
{
V.removeElementAt(V.size()-1);
s=prev+" "+sign+" "+new String(evalC,dex+1,c-dex);
}
V.addElement(s);
V.addElement(")");
dex=c+1;
state=STATE_MAIN;
}
else
throw new ScriptParseException("Bad postfunc Eval somewhere");
}
}
else
if(Character.isLetterOrDigit(evalC[c]))
{ /* move along */ }
else
if((evalC[c]=='\'')||(evalC[c]=='`'))
{
s=new String(evalC,dex,c-dex).trim();
if(s.length()==0)
{
lastQuote=evalC[c];
state=STATE_POSTFUNCQUOTE;
}
}
break;
}
}
if((state==STATE_POSTFUNCQUOTE)
||(state==STATE_INFUNCQUOTE))
throw new ScriptParseException("Unclosed "+lastQuote+" somewhere");
if(depth>0)
throw new ScriptParseException("Unclosed ( somewhere");
return CMParms.toStringArray(V);
}
public void pushEvalBoolean(Vector stack, boolean trueFalse)
{
if(stack.size()>0)
{
Object O=stack.elementAt(stack.size()-1);
if(O instanceof Integer)
{
int connector=((Integer)O).intValue();
stack.removeElementAt(stack.size()-1);
if((stack.size()>0)
&&((stack.elementAt(stack.size()-1) instanceof Boolean)))
{
boolean preTrueFalse=((Boolean)stack.elementAt(stack.size()-1)).booleanValue();
stack.removeElementAt(stack.size()-1);
switch(connector)
{
case CONNECTOR_AND: trueFalse=preTrueFalse&&trueFalse; break;
case CONNECTOR_OR: trueFalse=preTrueFalse||trueFalse; break;
case CONNECTOR_ANDNOT: trueFalse=preTrueFalse&&(!trueFalse); break;
case CONNECTOR_NOT:
case CONNECTOR_ORNOT: trueFalse=preTrueFalse||(!trueFalse); break;
}
}
else
switch(connector)
{
case CONNECTOR_ANDNOT:
case CONNECTOR_NOT:
case CONNECTOR_ORNOT: trueFalse=!trueFalse; break;
default: break;
}
}
else
if(O instanceof Boolean)
{
boolean preTrueFalse=((Boolean)stack.elementAt(stack.size()-1)).booleanValue();
stack.removeElementAt(stack.size()-1);
trueFalse=preTrueFalse&&trueFalse;
}
}
stack.addElement(trueFalse?Boolean.TRUE:Boolean.FALSE);
}
public boolean eval(Environmental scripted,
MOB source,
Environmental target,
MOB monster,
Item primaryItem,
Item secondaryItem,
String msg,
Object[] tmp,
String[][] eval,
int startEval)
{
String[] tt=(String[])eval[0];
if(tmp == null) tmp = newObjs();
Vector stack=new Vector();
for(int t=startEval;t<tt.length;t++)
if(tt[t].equals("("))
stack.addElement(tt[t]);
else
if(tt[t].equals(")"))
{
if((!(stack.lastElement() instanceof Boolean))
||(stack.size()==1)
||(!(stack.elementAt(stack.size()-2)).equals("(")))
{
logError(scripted,"EVAL","SYNTAX",") Format error: "+CMParms.toStringList(tt));
return false;
}
boolean b=((Boolean)stack.lastElement()).booleanValue();
stack.removeElementAt(stack.size()-1);
stack.removeElementAt(stack.size()-1);
pushEvalBoolean(stack,b);
}
else
if(connH.containsKey(tt[t]))
{
Integer curr=(Integer)connH.get(tt[t]);
if((stack.size()>0)&&(stack.lastElement() instanceof Integer))
{
int old=((Integer)stack.lastElement()).intValue();
stack.removeElementAt(stack.size()-1);
curr=Integer.valueOf(CONNECTOR_MAP[old][curr.intValue()]);
}
stack.addElement(curr);
}
else
if(funcH.containsKey(tt[t]))
{
Integer funcCode=(Integer)funcH.get(tt[t]);
if((t==tt.length-1)
||(!tt[t+1].equals("(")))
{
logError(scripted,"EVAL","SYNTAX","No ( for fuction "+tt[t]+": "+CMParms.toStringList(tt));
return false;
}
t+=2;
int tlen=0;
while(((t+tlen)<tt.length)&&(!tt[t+tlen].equals(")")))
tlen++;
if((t+tlen)==tt.length)
{
logError(scripted,"EVAL","SYNTAX","No ) for fuction "+tt[t-1]+": "+CMParms.toStringList(tt));
return false;
}
tickStatus=Tickable.STATUS_MISC+funcCode.intValue();
String funcParms=tt[t];
boolean returnable=false;
switch(funcCode.intValue())
{
case 1: // rand
{
String num=funcParms;
if(num.endsWith("%")) num=num.substring(0,num.length()-1);
int arg=CMath.s_int(num);
if(CMLib.dice().rollPercentage()<arg)
returnable=true;
else
returnable=false;
break;
}
case 2: // has
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"HAS","Syntax",funcParms);
return returnable;
}
Environmental E2=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
if(E instanceof MOB)
{
if(E2!=null)
returnable=((MOB)E).isMine(E2);
else
returnable=(((MOB)E).fetchInventory(arg2)!=null);
}
else
if(E instanceof Item)
returnable=CMLib.english().containsString(E.name(),arg2);
else
if(E instanceof Room)
{
if(E2 instanceof Item)
returnable=((Room)E).isContent((Item)E2);
else
returnable=(((Room)E).fetchItem(null,arg2)!=null);
}
else
returnable=false;
break;
}
case 74: // hasnum
{
if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
String arg1=tt[t+0];
String item=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
String cmp=tt[t+2];
String value=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((value.length()==0)||(item.length()==0)||(cmp.length()==0))
{
logError(scripted,"HASNUM","Syntax",funcParms);
return returnable;
}
Item I=null;
int num=0;
if(E==null)
returnable=false;
else
if(E instanceof MOB)
{
MOB M=(MOB)E;
for(int i=0;i<M.inventorySize();i++)
{
I=M.fetchInventory(i);
if(I==null) break;
if((item.equalsIgnoreCase("all"))
||(CMLib.english().containsString(I.Name(),item)))
num++;
}
returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM");
}
else
if(E instanceof Item)
{
num=CMLib.english().containsString(E.name(),item)?1:0;
returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM");
}
else
if(E instanceof Room)
{
Room R=(Room)E;
for(int i=0;i<R.numItems();i++)
{
I=R.fetchItem(i);
if(I==null) break;
if((item.equalsIgnoreCase("all"))
||(CMLib.english().containsString(I.Name(),item)))
num++;
}
returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM");
}
else
returnable=false;
break;
}
case 67: // hastitle
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"HASTITLE","Syntax",funcParms);
return returnable;
}
if(E instanceof MOB)
{
MOB M=(MOB)E;
returnable=(M.playerStats()!=null)&&(M.playerStats().getTitles().contains(arg2));
}
else
returnable=false;
break;
}
case 3: // worn
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"WORN","Syntax",funcParms);
return returnable;
}
if(E==null)
returnable=false;
else
if(E instanceof MOB)
returnable=(((MOB)E).fetchWornItem(arg2)!=null);
else
if(E instanceof Item)
returnable=(CMLib.english().containsString(E.name(),arg2)&&(!((Item)E).amWearingAt(Wearable.IN_INVENTORY)));
else
returnable=false;
break;
}
case 4: // isnpc
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
returnable=((MOB)E).isMonster();
break;
}
case 87: // isbirthday
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
MOB mob=(MOB)E;
if(mob.playerStats()==null)
returnable=false;
else
{
int tage=mob.baseCharStats().getMyRace().getAgingChart()[Race.AGE_YOUNGADULT]
+CMLib.time().globalClock().getYear()
-mob.playerStats().getBirthday()[2];
int month=CMLib.time().globalClock().getMonth();
int day=CMLib.time().globalClock().getDayOfMonth();
int bday=mob.playerStats().getBirthday()[0];
int bmonth=mob.playerStats().getBirthday()[1];
if((tage>mob.baseCharStats().getStat(CharStats.STAT_AGE))
&&((month==bmonth)&&(day==bday)))
returnable=true;
else
returnable=false;
}
}
break;
}
case 5: // ispc
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
returnable=!((MOB)E).isMonster();
break;
}
case 6: // isgood
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
returnable=CMLib.flags().isGood(E);
break;
}
case 8: // isevil
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
returnable=CMLib.flags().isEvil(E);
break;
}
case 9: // isneutral
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
returnable=CMLib.flags().isNeutral(E);
break;
}
case 54: // isalive
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead()))
returnable=true;
else
returnable=false;
break;
}
case 58: // isable
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead()))
{
ExpertiseLibrary X=(ExpertiseLibrary)CMLib.expertises().findDefinition(arg2,true);
if(X!=null)
returnable=((MOB)E).fetchExpertise(X.ID())!=null;
else
returnable=((MOB)E).findAbility(arg2)!=null;
}
else
returnable=false;
break;
}
case 59: // isopen
{
String arg1=CMParms.cleanBit(funcParms);
int dir=Directions.getGoodDirectionCode(arg1);
returnable=false;
if(dir<0)
{
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof Container))
returnable=((Container)E).isOpen();
else
if((E!=null)&&(E instanceof Exit))
returnable=((Exit)E).isOpen();
}
else
if(lastKnownLocation!=null)
{
Exit E=lastKnownLocation.getExitInDir(dir);
if(E!=null) returnable= E.isOpen();
}
break;
}
case 60: // islocked
{
String arg1=CMParms.cleanBit(funcParms);
int dir=Directions.getGoodDirectionCode(arg1);
returnable=false;
if(dir<0)
{
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof Container))
returnable=((Container)E).isLocked();
else
if((E!=null)&&(E instanceof Exit))
returnable=((Exit)E).isLocked();
}
else
if(lastKnownLocation!=null)
{
Exit E=lastKnownLocation.getExitInDir(dir);
if(E!=null) returnable= E.isLocked();
}
break;
}
case 10: // isfight
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
returnable=((MOB)E).isInCombat();
break;
}
case 11: // isimmort
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
returnable=CMSecurity.isAllowed(((MOB)E),lastKnownLocation,"IMMORT");
break;
}
case 12: // ischarmed
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
returnable=CMLib.flags().flaggedAffects(E,Ability.FLAG_CHARMING).size()>0;
break;
}
case 15: // isfollow
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
if(((MOB)E).amFollowing()==null)
returnable=false;
else
if(((MOB)E).amFollowing().location()!=lastKnownLocation)
returnable=false;
else
returnable=true;
break;
}
case 73: // isservant
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB))||(lastKnownLocation==null))
returnable=false;
else
if((((MOB)E).getLiegeID()==null)||(((MOB)E).getLiegeID().length()==0))
returnable=false;
else
if(lastKnownLocation.fetchInhabitant("$"+((MOB)E).getLiegeID()+"$")==null)
returnable=false;
else
returnable=true;
break;
}
case 55: // ispkill
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
if(CMath.bset(((MOB)E).getBitmap(),MOB.ATT_PLAYERKILL))
returnable=true;
else
returnable=false;
break;
}
case 7: // isname
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
returnable=CMLib.english().containsString(E.name(),arg2);
break;
}
case 56: // name
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
returnable=simpleEvalStr(scripted,E.Name(),arg3,arg2,"NAME");
break;
}
case 75: // currency
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
returnable=simpleEvalStr(scripted,CMLib.beanCounter().getCurrency(E),arg3,arg2,"CURRENCY");
break;
}
case 61: // strin
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
Vector V=CMParms.parse(arg1.toUpperCase());
returnable=V.contains(arg2.toUpperCase());
break;
}
case 62: // callfunc
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
String found=null;
boolean validFunc=false;
Vector scripts=getScripts();
String trigger=null;
String[] ttrigger=null;
for(int v=0;v<scripts.size();v++)
{
DVector script2=(DVector)scripts.elementAt(v);
if(script2.size()<1) continue;
trigger=((String)script2.elementAt(0,1)).toUpperCase().trim();
ttrigger=(String[])script2.elementAt(0,2);
if(getTriggerCode(trigger,ttrigger)==17)
{
String fnamed=
(ttrigger!=null)
?ttrigger[1]
:CMParms.getCleanBit(trigger,1);
if(fnamed.equalsIgnoreCase(arg1))
{
validFunc=true;
found=
execute(scripted,
source,
target,
monster,
primaryItem,
secondaryItem,
script2,
varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2),
tmp);
if(found==null) found="";
break;
}
}
}
if(!validFunc)
logError(scripted,"CALLFUNC","Unknown","Function: "+arg1);
else
if(found!=null)
returnable=!(found.trim().length()==0);
else
returnable=false;
break;
}
case 14: // affected
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
{
Ability A=CMClass.findAbility(arg2);
if(A!=null) arg2=A.ID();
returnable=(E.fetchEffect(arg2)!=null);
}
break;
}
case 69: // isbehave
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
{
Behavior B=CMClass.findBehavior(arg2);
if(B!=null) arg2=B.ID();
returnable=(E.fetchBehavior(arg2)!=null);
}
break;
}
case 70: // ipaddress
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB))||(((MOB)E).isMonster()))
returnable=false;
else
returnable=simpleEvalStr(scripted,((MOB)E).session().getAddress(),arg3,arg2,"ADDRESS");
break;
}
case 28: // questwinner
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=tt[t+1];
Environmental E=getArgumentMOB(tt[t+0],source,monster,target,primaryItem,secondaryItem,msg,tmp);
Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
{
if(E!=null) arg1=E.Name();
returnable=Q.wasWinner(arg1);
}
break;
}
case 93: // questscripted
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
Environmental E=getArgumentMOB(tt[t+0],source,monster,target,primaryItem,secondaryItem,msg,tmp);
String arg2=tt[t+1];
Quest Q=getQuest(arg2);
returnable=false;
if((Q!=null)&&(E!=null))
{
for(int i=0;i<E.numScripts();i++)
{
ScriptingEngine S=E.fetchScript(i);
if((S!=null)&&(S.defaultQuestName().equalsIgnoreCase(Q.name())))
returnable=true;
}
}
break;
}
case 94: // questroom
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=tt[t+1];
Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
returnable=(Q.getQuestRoomIndex(arg1)>=0);
break;
}
case 29: // questmob
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=tt[t+1];
Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
returnable=(Q.getQuestMobIndex(arg1)>=0);
break;
}
case 31: // isquestmobalive
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=tt[t+1];
Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
{
MOB M=null;
if(CMath.s_int(arg1.trim())>0)
M=Q.getQuestMob(CMath.s_int(arg1.trim()));
else
M=Q.getQuestMob(Q.getQuestMobIndex(arg1));
if(M==null) returnable=false;
else returnable=!M.amDead();
}
break;
}
case 32: // nummobsinarea
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase();
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
int num=0;
Vector MASK=null;
if((arg3.toUpperCase().startsWith("MASK")&&(arg3.substring(4).trim().startsWith("="))))
{
arg3=arg3.substring(4).trim();
arg3=arg3.substring(1).trim();
MASK=CMLib.masking().maskCompile(arg3);
}
for(Enumeration e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
{
Room R=(Room)e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
MOB M=R.fetchInhabitant(m);
if(M==null) continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.name(),arg1))
num++;
}
}
returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMMOBSINAREA");
break;
}
case 33: // nummobs
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase();
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
int num=0;
Vector MASK=null;
if((arg3.toUpperCase().startsWith("MASK")&&(arg3.substring(4).trim().startsWith("="))))
{
arg3=arg3.substring(4).trim();
arg3=arg3.substring(1).trim();
MASK=CMLib.masking().maskCompile(arg3);
}
try
{
for(Enumeration e=CMLib.map().rooms();e.hasMoreElements();)
{
Room R=(Room)e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
MOB M=R.fetchInhabitant(m);
if(M==null) continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.name(),arg1))
num++;
}
}
}catch(NoSuchElementException nse){}
returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMMOBS");
break;
}
case 34: // numracesinarea
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase();
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
int num=0;
Room R=null;
MOB M=null;
for(Enumeration e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
{
R=(Room)e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
M=R.fetchInhabitant(m);
if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1)))
num++;
}
}
returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMRACESINAREA");
break;
}
case 35: // numraces
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase();
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
int num=0;
try
{
for(Enumeration e=CMLib.map().rooms();e.hasMoreElements();)
{
Room R=(Room)e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
MOB M=R.fetchInhabitant(m);
if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1)))
num++;
}
}
}catch(NoSuchElementException nse){}
returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMRACES");
break;
}
case 30: // questobj
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=tt[t+1];
Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
returnable=(Q.getQuestItemIndex(arg1)>=0);
break;
}
case 85: // islike
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=tt[t+1];
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
returnable=CMLib.masking().maskCheck(arg2, E,false);
break;
}
case 86: // strcontains
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
returnable=CMParms.stringContains(arg1,arg2)>=0;
break;
}
case 92: // isodd
{
String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).trim();
boolean isodd = false;
if( CMath.isLong( val ) )
{
isodd = (CMath.s_long(val) %2 == 1);
}
returnable = isodd;
break;
}
case 16: // hitprcnt
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"HITPRCNT","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
double hitPctD=CMath.div(((MOB)E).curState().getHitPoints(),((MOB)E).maxState().getHitPoints());
int val1=(int)Math.round(hitPctD*100.0);
returnable=simpleEval(scripted,""+val1,arg3,arg2,"HITPRCNT");
}
break;
}
case 50: // isseason
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
returnable=false;
if(monster.location()!=null)
for(int a=0;a<TimeClock.SEASON_DESCS.length;a++)
if((TimeClock.SEASON_DESCS[a]).startsWith(arg1.toUpperCase())
&&(monster.location().getArea().getTimeObj().getSeasonCode()==a))
{returnable=true; break;}
break;
}
case 51: // isweather
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
returnable=false;
if(monster.location()!=null)
for(int a=0;a<Climate.WEATHER_DESCS.length;a++)
if((Climate.WEATHER_DESCS[a]).startsWith(arg1.toUpperCase())
&&(monster.location().getArea().getClimateObj().weatherType(monster.location())==a))
{returnable=true; break;}
break;
}
case 57: // ismoon
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
returnable=false;
if(monster.location()!=null)
{
if(arg1.length()==0)
returnable=monster.location().getArea().getClimateObj().canSeeTheStars(monster.location());
else
for(int a=0;a<TimeClock.PHASE_DESC.length;a++)
if((TimeClock.PHASE_DESC[a]).startsWith(arg1.toUpperCase())
&&(monster.location().getArea().getTimeObj().getMoonPhase()==a))
{
returnable=true;
break;
}
}
break;
}
case 38: // istime
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toLowerCase().trim();
if(monster.location()==null)
returnable=false;
else
if(("daytime").startsWith(arg1)
&&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TIME_DAY))
returnable=true;
else
if(("dawn").startsWith(arg1)
&&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TIME_DAWN))
returnable=true;
else
if(("dusk").startsWith(arg1)
&&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TIME_DUSK))
returnable=true;
else
if(("nighttime").startsWith(arg1)
&&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TIME_NIGHT))
returnable=true;
else
if((monster.location().getArea().getTimeObj().getTimeOfDay()==CMath.s_int(arg1)))
returnable=true;
else
returnable=false;
break;
}
case 39: // isday
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if((monster.location()!=null)&&(monster.location().getArea().getTimeObj().getDayOfMonth()==CMath.s_int(arg1.trim())))
returnable=true;
else
returnable=false;
break;
}
case 45: // nummobsroom
{
if(tlen==1)
{
if(CMParms.numBits(funcParms)>2)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
else
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
}
int num=0;
int startbit=0;
if(lastKnownLocation!=null)
{
num=lastKnownLocation.numInhabitants();
if(signH.containsKey(tt[t+1]))
{
String name=tt[t+0];
startbit++;
if(!name.equalsIgnoreCase("*"))
{
num=0;
Vector MASK=null;
if((name.toUpperCase().startsWith("MASK")&&(name.substring(4).trim().startsWith("="))))
{
name=name.substring(4).trim();
name=name.substring(1).trim();
MASK=CMLib.masking().maskCompile(name);
}
for(int i=0;i<lastKnownLocation.numInhabitants();i++)
{
MOB M=lastKnownLocation.fetchInhabitant(i);
if(M==null) continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.Name(),name)
||CMLib.english().containsString(M.displayText(),name))
num++;
}
}
}
}
else
if(!signH.containsKey(tt[t+0]))
{
logError(scripted,"NUMMOBSROOM","Syntax","No SIGN found: "+funcParms);
return returnable;
}
String comp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+startbit]);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+startbit+1]);
if(lastKnownLocation!=null)
returnable=simpleEval(scripted,""+num,arg2,comp,"NUMMOBSROOM");
break;
}
case 63: // numpcsroom
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
if(lastKnownLocation!=null)
returnable=simpleEval(scripted,""+lastKnownLocation.numPCInhabitants(),arg2,arg1,"NUMPCSROOM");
break;
}
case 79: // numpcsarea
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
if(lastKnownLocation!=null)
{
int num=0;
for(int s=0;s<CMLib.sessions().size();s++)
{
Session S=CMLib.sessions().elementAt(s);
if((S!=null)&&(S.mob()!=null)&&(S.mob().location()!=null)&&(S.mob().location().getArea()==lastKnownLocation.getArea()))
num++;
}
returnable=simpleEval(scripted,""+num,arg2,arg1,"NUMPCSAREA");
}
break;
}
case 77: // explored
{
if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String where=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
String cmp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
Environmental E=getArgumentMOB(whom,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
{
logError(scripted,"EXPLORED","Unknown Code",whom);
return returnable;
}
Area A=null;
if(!where.equalsIgnoreCase("world"))
{
A=CMLib.map().getArea(where);
if(A==null)
{
Environmental E2=getArgumentItem(where,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E2 != null)
A=CMLib.map().areaLocation(E2);
}
if(A==null)
{
logError(scripted,"EXPLORED","Unknown Area",where);
return returnable;
}
}
if(lastKnownLocation!=null)
{
int pct=0;
MOB M=(MOB)E;
if(M.playerStats()!=null)
pct=M.playerStats().percentVisited(M,A);
returnable=simpleEval(scripted,""+pct,arg2,cmp,"EXPLORED");
}
break;
}
case 72: // faction
{
if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
String cmp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
Environmental E=getArgumentMOB(whom,source,monster,target,primaryItem,secondaryItem,msg,tmp);
Faction F=CMLib.factions().getFaction(arg1);
if((E==null)||(!(E instanceof MOB)))
{
logError(scripted,"FACTION","Unknown Code",whom);
return returnable;
}
if(F==null)
{
logError(scripted,"FACTION","Unknown Faction",arg1);
return returnable;
}
MOB M=(MOB)E;
String value=null;
if(!M.hasFaction(F.factionID()))
value="";
else
{
int myfac=M.fetchFaction(F.factionID());
if(CMath.isNumber(arg2.trim()))
value=Integer.toString(myfac);
else
{
Faction.FactionRange FR=CMLib.factions().getRange(F.factionID(),myfac);
if(FR==null)
value="";
else
value=FR.name();
}
}
if(lastKnownLocation!=null)
returnable=simpleEval(scripted,value,arg2,cmp,"FACTION");
break;
}
case 46: // numitemsroom
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
int ct=0;
if(lastKnownLocation!=null)
for(int i=0;i<lastKnownLocation.numItems();i++)
{
Item I=lastKnownLocation.fetchItem(i);
if((I!=null)&&(I.container()==null))
ct++;
}
returnable=simpleEval(scripted,""+ct,arg2,arg1,"NUMITEMSROOM");
break;
}
case 47: //mobitem
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
MOB M=null;
if(lastKnownLocation!=null)
M=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
Item which=null;
int ct=1;
if(M!=null)
for(int i=0;i<M.inventorySize();i++)
{
Item I=M.fetchInventory(i);
if((I!=null)&&(I.container()==null))
{
if(ct==CMath.s_int(arg2.trim()))
{ which=I; break;}
ct++;
}
}
if(which==null)
returnable=false;
else
returnable=(CMLib.english().containsString(which.name(),arg3)
||CMLib.english().containsString(which.Name(),arg3)
||CMLib.english().containsString(which.displayText(),arg3));
break;
}
case 49: // hastattoo
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"HASTATTOO","Syntax",funcParms);
break;
}
else
if((E!=null)&&(E instanceof MOB))
returnable=(((MOB)E).fetchTattoo(arg2)!=null);
else
returnable=false;
break;
}
case 48: // numitemsmob
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
MOB which=null;
if(lastKnownLocation!=null)
which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
int ct=1;
if(which!=null)
for(int i=0;i<which.inventorySize();i++)
{
Item I=which.fetchInventory(i);
if((I!=null)&&(I.container()==null))
ct++;
}
returnable=simpleEval(scripted,""+ct,arg3,arg2,"NUMITEMSMOB");
break;
}
case 43: // roommob
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
Environmental which=null;
if(lastKnownLocation!=null)
which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
if(which==null)
returnable=false;
else
returnable=(CMLib.english().containsString(which.name(),arg2)
||CMLib.english().containsString(which.Name(),arg2)
||CMLib.english().containsString(which.displayText(),arg2));
break;
}
case 44: // roomitem
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
Environmental which=null;
int ct=1;
if(lastKnownLocation!=null)
for(int i=0;i<lastKnownLocation.numItems();i++)
{
Item I=lastKnownLocation.fetchItem(i);
if((I!=null)&&(I.container()==null))
{
if(ct==CMath.s_int(arg1.trim()))
{ which=I; break;}
ct++;
}
}
if(which==null)
returnable=false;
else
returnable=(CMLib.english().containsString(which.name(),arg2)
||CMLib.english().containsString(which.Name(),arg2)
||CMLib.english().containsString(which.displayText(),arg2));
break;
}
case 36: // ishere
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if(lastKnownLocation!=null)
returnable=((lastKnownLocation.fetchAnyItem(arg1)!=null)||(lastKnownLocation.fetchInhabitant(arg1)!=null));
else
returnable=false;
break;
}
case 17: // inroom
{
if(tlen==1) tt=parseSpecial3PartEval(eval,t);
String comp="==";
Environmental E=monster;
String arg2;
if(signH.containsKey(tt[t+1]))
{
E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
comp=tt[t+1];
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
}
else
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
Room R=null;
if(arg2.startsWith("$"))
R=CMLib.map().roomLocation(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(R==null)
R=getRoom(arg2,lastKnownLocation);
if(E==null)
returnable=false;
else
{
Room R2=CMLib.map().roomLocation(E);
if((R==null)&&((arg2.length()==0)||(R2==null)))
returnable=true;
else
if((R==null)||(R2==null))
returnable=false;
else
returnable=simpleEvalStr(scripted,CMLib.map().getExtendedRoomID(R2),CMLib.map().getExtendedRoomID(R),comp,"INROOM");
}
break;
}
case 90: // inarea
{
if(tlen==1) tt=parseSpecial3PartEval(eval,t);
String comp="==";
Environmental E=monster;
String arg2;
if(signH.containsKey(tt[t+1]))
{
E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
comp=tt[t+1];
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
}
else
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
Room R=null;
if(arg2.startsWith("$"))
R=CMLib.map().roomLocation(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(R==null)
try
{
if((lastKnownLocation!=null)&&(lastKnownLocation.getArea().Name().equalsIgnoreCase(arg2)))
R=lastKnownLocation;
if(R==null)
for(Enumeration a=CMLib.map().areas();a.hasMoreElements();)
{
Area A=(Area)a.nextElement();
if((A!=null)&&(A.Name().equalsIgnoreCase(arg2)))
{
if((lastKnownLocation!=null)&&(lastKnownLocation.getArea().Name().equals(A.Name())))
R=lastKnownLocation;
else
R=A.getRandomProperRoom();
}
}
for(Enumeration a=CMLib.map().areas();a.hasMoreElements();)
{
Area A=(Area)a.nextElement();
if((A!=null)&&(CMLib.english().containsString(A.Name(),arg2)))
{
if((lastKnownLocation!=null)&&(lastKnownLocation.getArea().Name().equals(A.Name())))
R=lastKnownLocation;
else
R=A.getRandomProperRoom();
}
}
}catch(NoSuchElementException nse){}
if(R==null)
R=getRoom(arg2,lastKnownLocation);
if(E==null)
returnable=false;
else
{
Room R2=CMLib.map().roomLocation(E);
if((R==null)&&((arg2.length()==0)||(R2==null)))
returnable=true;
else
if((R==null)||(R2==null))
returnable=false;
else
returnable=simpleEvalStr(scripted,R2.getArea().Name(),R.getArea().Name(),comp,"INAREA");
}
break;
}
case 89: // isrecall
{
if(tlen==1) tt=parseSpecial3PartEval(eval,t);
String comp="==";
Environmental E=monster;
String arg2;
if(signH.containsKey(tt[t+1]))
{
E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
comp=tt[t+1];
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
}
else
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
Room R=null;
if(arg2.startsWith("$"))
R=CMLib.map().getStartRoom(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(R==null)
R=getRoom(arg2,lastKnownLocation);
if(E==null)
returnable=false;
else
{
Room R2=CMLib.map().getStartRoom(E);
if((R==null)&&((arg2.length()==0)||(R2==null)))
returnable=true;
else
if((R==null)||(R2==null))
returnable=false;
else
returnable=simpleEvalStr(scripted,CMLib.map().getExtendedRoomID(R2),CMLib.map().getExtendedRoomID(R),comp,"ISRECALL");
}
break;
}
case 37: // inlocale
{
if(tlen==1)
{
if(CMParms.numBits(funcParms)>1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
else
{
int numBits=2;
String[] parsed=null;
if(CMParms.cleanBit(funcParms).equals(funcParms))
parsed=parseBits("'"+funcParms+"'"+CMStrings.repeat(" .",numBits-1),"cr");
else
parsed=parseBits(funcParms+CMStrings.repeat(" .",numBits-1),"cr");
tt=insertStringArray(tt,parsed,t);
eval[0]=tt;
}
}
String arg2=null;
Environmental E=monster;
if(tt[t+1].equals("."))
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
else
{
E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
}
if(E==null)
returnable=false;
else
if(arg2.length()==0)
returnable=true;
else
{
Room R=CMLib.map().roomLocation(E);
if(R==null)
returnable=false;
else
if(CMClass.classID(R).toUpperCase().indexOf(arg2.toUpperCase())>=0)
returnable=true;
else
returnable=false;
}
break;
}
case 18: // sex
{
if(tlen==1) tt=parseBits(eval,t,"CcR"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=tt[t+1];
String arg3=tt[t+2];
if(CMath.isNumber(arg3.trim()))
switch(CMath.s_int(arg3.trim()))
{
case 0: arg3="NEUTER"; break;
case 1: arg3="MALE"; break;
case 2: arg3="FEMALE"; break;
}
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"SEX","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
String sex=(""+((char)((MOB)E).charStats().getStat(CharStats.STAT_GENDER))).toUpperCase();
if(arg2.equals("=="))
returnable=arg3.startsWith(sex);
else
if(arg2.equals("!="))
returnable=!arg3.startsWith(sex);
else
{
logError(scripted,"SEX","Syntax",funcParms);
return returnable;
}
}
break;
}
case 91: // datetime
{
if(tlen==1) tt=parseBits(eval,t,"Ccr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=tt[t+2];
int index=CMParms.indexOf(ScriptingEngine.DATETIME_ARGS,arg1.trim());
if(index<0)
logError(scripted,"DATETIME","Syntax","Unknown arg: "+arg1+" for "+scripted.name());
else
if(CMLib.map().areaLocation(scripted)!=null)
{
String val=null;
switch(index)
{
case 2: val=""+CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth(); break;
case 3: val=""+CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth(); break;
case 4: val=""+CMLib.map().areaLocation(scripted).getTimeObj().getMonth(); break;
case 5: val=""+CMLib.map().areaLocation(scripted).getTimeObj().getYear(); break;
default:
val=""+CMLib.map().areaLocation(scripted).getTimeObj().getTimeOfDay(); break;
}
returnable=simpleEval(scripted,val,arg3,arg2,"DATETIME");
}
break;
}
case 13: // stat
{
if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=tt[t+2];
String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"STAT","Syntax",funcParms);
break;
}
if(E==null)
returnable=false;
else
{
String val=getStatValue(E,arg2);
if(val==null)
{
logError(scripted,"STAT","Syntax","Unknown stat: "+arg2+" for "+E.name());
break;
}
if(arg3.equals("=="))
returnable=val.equalsIgnoreCase(arg4);
else
if(arg3.equals("!="))
returnable=!val.equalsIgnoreCase(arg4);
else
returnable=simpleEval(scripted,val,arg4,arg3,"STAT");
}
break;
}
case 52: // gstat
{
if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=tt[t+2];
String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"GSTAT","Syntax",funcParms);
break;
}
if(E==null)
returnable=false;
else
{
String val=getGStatValue(E,arg2);
if(val==null)
{
logError(scripted,"GSTAT","Syntax","Unknown stat: "+arg2+" for "+E.name());
break;
}
if(arg3.equals("=="))
returnable=val.equalsIgnoreCase(arg4);
else
if(arg3.equals("!="))
returnable=!val.equalsIgnoreCase(arg4);
else
returnable=simpleEval(scripted,val,arg4,arg3,"GSTAT");
}
break;
}
case 19: // position
{
if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=tt[t+2];
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"POSITION","Syntax",funcParms);
return returnable;
}
if(E==null)
returnable=false;
else
{
String sex="STANDING";
if(CMLib.flags().isSleeping(E))
sex="SLEEPING";
else
if(CMLib.flags().isSitting(E))
sex="SITTING";
if(arg2.equals("=="))
returnable=sex.startsWith(arg3);
else
if(arg2.equals("!="))
returnable=!sex.startsWith(arg3);
else
{
logError(scripted,"POSITION","Syntax",funcParms);
return returnable;
}
}
break;
}
case 20: // level
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"LEVEL","Syntax",funcParms);
return returnable;
}
if(E==null)
returnable=false;
else
{
int val1=E.envStats().level();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"LEVEL");
}
break;
}
case 80: // questpoints
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"QUESTPOINTS","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
int val1=((MOB)E).getQuestPoint();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"QUESTPOINTS");
}
break;
}
case 83: // qvar
{
if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
String arg3=tt[t+2];
String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
Quest Q=getQuest(arg1);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"QVAR","Syntax",funcParms);
return returnable;
}
if(Q==null)
returnable=false;
else
returnable=simpleEvalStr(scripted,Q.getStat(arg2),arg4,arg3,"QVAR");
break;
}
case 84: // math
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
if(!CMath.isMathExpression(arg1))
{
logError(scripted,"MATH","Syntax",funcParms);
return returnable;
}
if(!CMath.isMathExpression(arg3))
{
logError(scripted,"MATH","Syntax",funcParms);
return returnable;
}
returnable=simpleExpressionEval(scripted,arg1,arg3,arg2,"MATH");
break;
}
case 81: // trains
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"TRAINS","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
int val1=((MOB)E).getTrains();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"TRAINS");
}
break;
}
case 82: // pracs
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"PRACS","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
int val1=((MOB)E).getPractices();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"PRACS");
}
break;
}
case 66: // clanrank
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"CLANRANK","Syntax",funcParms);
return returnable;
}
if(E==null)
returnable=false;
else
{
int val1=(E instanceof MOB)?((MOB)E).getClanRole():-1;
returnable=simpleEval(scripted,""+val1,arg3,arg2,"CLANRANK");
}
break;
}
case 64: // deity
{
if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"DEITY","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
String sex=((MOB)E).getWorshipCharID();
if(arg2.equals("=="))
returnable=sex.equalsIgnoreCase(arg3);
else
if(arg2.equals("!="))
returnable=!sex.equalsIgnoreCase(arg3);
else
{
logError(scripted,"DEITY","Syntax",funcParms);
return returnable;
}
}
break;
}
case 68: // clandata
{
if(tlen==1) tt=parseBits(eval,t,"cccR"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=tt[t+2];
String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"CLANDATA","Syntax",funcParms);
return returnable;
}
String clanID=null;
if((E!=null)&&(E instanceof MOB))
clanID=((MOB)E).getClanID();
else
clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1);
Clan C=CMLib.clans().findClan(clanID);
if(C!=null)
{
if(!C.isStat(arg2))
logError(scripted,"CLANDATA","RunTime",arg2+" is not a valid clan variable.");
else
{
String whichVal=C.getStat(arg2).trim();
if(CMath.isNumber(whichVal)&&CMath.isNumber(arg4.trim()))
returnable=simpleEval(scripted,whichVal,arg4,arg3,"CLANDATA");
else
returnable=simpleEvalStr(scripted,whichVal,arg4,arg3,"CLANDATA");
}
}
break;
}
case 65: // clan
{
if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"CLAN","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
String sex=((MOB)E).getClanID();
if(arg2.equals("=="))
returnable=sex.equalsIgnoreCase(arg3);
else
if(arg2.equals("!="))
returnable=!sex.equalsIgnoreCase(arg3);
else
{
logError(scripted,"CLAN","Syntax",funcParms);
return returnable;
}
}
break;
}
case 88: // mood
{
if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"MOOD","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
if(E.fetchEffect("Mood")!=null)
{
String sex=E.fetchEffect("Mood").text();
if(arg2.equals("=="))
returnable=sex.equalsIgnoreCase(arg3);
else
if(arg2.equals("!="))
returnable=!sex.equalsIgnoreCase(arg3);
else
{
logError(scripted,"MOOD","Syntax",funcParms);
return returnable;
}
}
break;
}
case 21: // class
{
if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"CLASS","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
String sex=((MOB)E).charStats().displayClassName().toUpperCase();
if(arg2.equals("=="))
returnable=sex.startsWith(arg3);
else
if(arg2.equals("!="))
returnable=!sex.startsWith(arg3);
else
{
logError(scripted,"CLASS","Syntax",funcParms);
return returnable;
}
}
break;
}
case 22: // baseclass
{
if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"CLASS","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
String sex=((MOB)E).charStats().getCurrentClass().baseClass().toUpperCase();
if(arg2.equals("=="))
returnable=sex.startsWith(arg3);
else
if(arg2.equals("!="))
returnable=!sex.startsWith(arg3);
else
{
logError(scripted,"CLASS","Syntax",funcParms);
return returnable;
}
}
break;
}
case 23: // race
{
if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"RACE","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
String sex=((MOB)E).charStats().raceName().toUpperCase();
if(arg2.equals("=="))
returnable=sex.startsWith(arg3);
else
if(arg2.equals("!="))
returnable=!sex.startsWith(arg3);
else
{
logError(scripted,"RACE","Syntax",funcParms);
return returnable;
}
}
break;
}
case 24: //racecat
{
if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"RACECAT","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
String sex=((MOB)E).charStats().getMyRace().racialCategory().toUpperCase();
if(arg2.equals("=="))
returnable=sex.startsWith(arg3);
else
if(arg2.equals("!="))
returnable=!sex.startsWith(arg3);
else
{
logError(scripted,"RACECAT","Syntax",funcParms);
return returnable;
}
}
break;
}
case 25: // goldamt
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"GOLDAMT","Syntax",funcParms);
break;
}
if(E==null)
returnable=false;
else
{
int val1=0;
if(E instanceof MOB)
val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,CMLib.beanCounter().getCurrency(scripted)));
else
if(E instanceof Coins)
val1=(int)Math.round(((Coins)E).getTotalValue());
else
if(E instanceof Item)
val1=((Item)E).value();
else
{
logError(scripted,"GOLDAMT","Syntax",funcParms);
return returnable;
}
returnable=simpleEval(scripted,""+val1,arg3,arg2,"GOLDAMT");
}
break;
}
case 78: // exp
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"EXP","Syntax",funcParms);
break;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
int val1=((MOB)E).getExperience();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"EXP");
}
break;
}
case 76: // value
{
if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
String arg1=tt[t+0];
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
String arg3=tt[t+2];
String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
if((arg2.length()==0)||(arg3.length()==0)||(arg4.length()==0))
{
logError(scripted,"VALUE","Syntax",funcParms);
break;
}
if(!CMLib.beanCounter().getAllCurrencies().contains(arg2.toUpperCase()))
{
logError(scripted,"VALUE","Syntax",arg2+" is not a valid designated currency.");
break;
}
if(E==null)
returnable=false;
else
{
int val1=0;
if(E instanceof MOB)
val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,arg2.toUpperCase()));
else
if(E instanceof Coins)
{
if(((Coins)E).getCurrency().equalsIgnoreCase(arg2))
val1=(int)Math.round(((Coins)E).getTotalValue());
}
else
if(E instanceof Item)
val1=((Item)E).value();
else
{
logError(scripted,"VALUE","Syntax",funcParms);
return returnable;
}
returnable=simpleEval(scripted,""+val1,arg4,arg3,"GOLDAMT");
}
break;
}
case 26: // objtype
{
if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"OBJTYPE","Syntax",funcParms);
return returnable;
}
if(E==null)
returnable=false;
else
{
String sex=CMClass.classID(E).toUpperCase();
if(arg2.equals("=="))
returnable=sex.indexOf(arg3)>=0;
else
if(arg2.equals("!="))
returnable=sex.indexOf(arg3)<0;
else
{
logError(scripted,"OBJTYPE","Syntax",funcParms);
return returnable;
}
}
break;
}
case 27: // var
{
if(tlen==1) tt=parseBits(eval,t,"cCcr"); /* tt[t+0] */
String arg1=tt[t+0];
String arg2=tt[t+1];
String arg3=tt[t+2];
String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"VAR","Syntax",funcParms);
return returnable;
}
String val=getVar(E,arg1,arg2,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp);
if(arg3.equals("=="))
returnable=val.equals(arg4);
else
if(arg3.equals("!="))
returnable=!val.equals(arg4);
else
if(arg3.equals(">"))
returnable=CMath.s_int(val.trim())>CMath.s_int(arg4.trim());
else
if(arg3.equals("<"))
returnable=CMath.s_int(val.trim())<CMath.s_int(arg4.trim());
else
if(arg3.equals(">="))
returnable=CMath.s_int(val.trim())>=CMath.s_int(arg4.trim());
else
if(arg3.equals("<="))
returnable=CMath.s_int(val.trim())<=CMath.s_int(arg4.trim());
else
{
logError(scripted,"VAR","Syntax",funcParms);
return returnable;
}
break;
}
case 41: // eval
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
String arg3=tt[t+1];
String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
if(arg3.length()==0)
{
logError(scripted,"EVAL","Syntax",funcParms);
return returnable;
}
if(arg3.equals("=="))
returnable=val.equals(arg4);
else
if(arg3.equals("!="))
returnable=!val.equals(arg4);
else
if(arg3.equals(">"))
returnable=CMath.s_int(val.trim())>CMath.s_int(arg4.trim());
else
if(arg3.equals("<"))
returnable=CMath.s_int(val.trim())<CMath.s_int(arg4.trim());
else
if(arg3.equals(">="))
returnable=CMath.s_int(val.trim())>=CMath.s_int(arg4.trim());
else
if(arg3.equals("<="))
returnable=CMath.s_int(val.trim())<=CMath.s_int(arg4.trim());
else
{
logError(scripted,"EVAL","Syntax",funcParms);
return returnable;
}
break;
}
case 40: // number
{
String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).trim();
boolean isnumber=(val.length()>0);
for(int i=0;i<val.length();i++)
if(!Character.isDigit(val.charAt(i)))
{ isnumber=false; break;}
returnable=isnumber;
break;
}
case 42: // randnum
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase().trim();
int arg1=0;
if(CMath.isMathExpression(arg1s.trim()))
arg1=CMath.s_parseIntExpression(arg1s.trim());
else
arg1=CMParms.parse(arg1s.trim()).size();
String arg2=tt[t+1];
String arg3s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]).trim();
int arg3=0;
if(CMath.isMathExpression(arg3s.trim()))
arg3=CMath.s_parseIntExpression(arg3s.trim());
else
arg3=CMParms.parse(arg3s.trim()).size();
arg3=CMLib.dice().roll(1,arg3,0);
returnable=simpleEval(scripted,""+arg1,""+arg3,arg2,"RANDNUM");
break;
}
case 71: // rand0num
{
if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase().trim();
int arg1=0;
if(CMath.isMathExpression(arg1s))
arg1=CMath.s_parseIntExpression(arg1s);
else
arg1=CMParms.parse(arg1s).size();
String arg2=tt[t+1];
String arg3s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]).trim();
int arg3=0;
if(CMath.isMathExpression(arg3s))
arg3=CMath.s_parseIntExpression(arg3s);
else
arg3=CMParms.parse(arg3s).size();
arg3=CMLib.dice().roll(1,arg3,-1);
returnable=simpleEval(scripted,""+arg1,""+arg3,arg2,"RAND0NUM");
break;
}
case 53: // incontainer
{
if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=tt[t+0];
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String arg2=tt[t+1];
Environmental E2=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
if(E instanceof MOB)
{
if(arg2.length()==0)
returnable=(((MOB)E).riding()==null);
else
if(E2!=null)
returnable=(((MOB)E).riding()==E2);
else
returnable=false;
}
else
if(E instanceof Item)
{
if(arg2.length()==0)
returnable=(((Item)E).container()==null);
else
if(E2!=null)
returnable=(((Item)E).container()==E2);
else
returnable=false;
}
else
returnable=false;
break;
}
default:
logError(scripted,"EVAL","UNKNOWN",CMParms.toStringList(tt));
return false;
}
pushEvalBoolean(stack,returnable);
while((t<tt.length)&&(!tt[t].equals(")")))
t++;
}
else
{
logError(scripted,"EVAL","SYNTAX","BAD CONJUCTOR "+tt[t]+": "+CMParms.toStringList(tt));
return false;
}
if((stack.size()!=1)||(!(stack.firstElement() instanceof Boolean)))
{
logError(scripted,"EVAL","SYNTAX","Unmatched (: "+CMParms.toStringList(tt));
return false;
}
return ((Boolean)stack.firstElement()).booleanValue();
}
protected String functify(Environmental scripted,
MOB source,
Environmental target,
MOB monster,
Item primaryItem,
Item secondaryItem,
String msg,
Object[] tmp,
String evaluable)
{
String uevaluable=evaluable.toUpperCase().trim();
StringBuffer results = new StringBuffer("");
while(evaluable.length()>0)
{
int y=evaluable.indexOf("(");
int z=evaluable.indexOf(")");
String preFab=(y>=0)?uevaluable.substring(0,y).trim():"";
Integer funcCode=(Integer)funcH.get(preFab);
if(funcCode==null) funcCode=Integer.valueOf(0);
if(y==0)
{
int depth=0;
int i=0;
while((++i)<evaluable.length())
{
char c=evaluable.charAt(i);
if((c==')')&&(depth==0))
{
String expr=evaluable.substring(1,i);
evaluable=evaluable.substring(i+1);
uevaluable=uevaluable.substring(i+1);
results.append(functify(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,expr));
break;
}
else
if(c=='(') depth++;
else
if(c==')') depth--;
}
z=evaluable.indexOf(")");
}
else
if((y<0)||(z<y))
{
logError(scripted,"()","Syntax",evaluable);
break;
}
else
{
tickStatus=Tickable.STATUS_MISC2+funcCode.intValue();
String funcParms=evaluable.substring(y+1,z).trim();
switch(funcCode.intValue())
{
case 1: // rand
{
results.append(CMLib.dice().rollPercentage());
break;
}
case 2: // has
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
Vector choices=new Vector();
if(E==null)
choices=new Vector();
else
if(E instanceof MOB)
{
for(int i=0;i<((MOB)E).inventorySize();i++)
{
Item I=((MOB)E).fetchInventory(i);
if((I!=null)&&(I.amWearingAt(Wearable.IN_INVENTORY))&&(I.container()==null))
choices.addElement(I);
}
}
else
if(E instanceof Item)
{
choices.addElement(E);
if(E instanceof Container)
choices=((Container)E).getContents();
}
else
if(E instanceof Room)
{
for(int i=0;i<((Room)E).numItems();i++)
{
Item I=((Room)E).fetchItem(i);
if((I!=null)&&(I.container()==null))
choices.addElement(I);
}
}
if(choices.size()>0)
results.append(((Item)choices.elementAt(CMLib.dice().roll(1,choices.size(),-1))).name());
break;
}
case 74: // hasnum
{
String arg1=CMParms.getCleanBit(funcParms,0);
String item=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,1));
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((item.length()==0)||(E==null))
logError(scripted,"HASNUM","Syntax",funcParms);
else
{
Item I=null;
int num=0;
if(E instanceof MOB)
{
MOB M=(MOB)E;
for(int i=0;i<M.inventorySize();i++)
{
I=M.fetchInventory(i);
if(I==null) break;
if((item.equalsIgnoreCase("all"))
||(CMLib.english().containsString(I.Name(),item)))
num++;
}
results.append(""+num);
}
else
if(E instanceof Item)
{
num=CMLib.english().containsString(E.name(),item)?1:0;
results.append(""+num);
}
else
if(E instanceof Room)
{
Room R=(Room)E;
for(int i=0;i<R.numItems();i++)
{
I=R.fetchItem(i);
if(I==null) break;
if((item.equalsIgnoreCase("all"))
||(CMLib.english().containsString(I.Name(),item)))
num++;
}
results.append(""+num);
}
}
break;
}
case 3: // worn
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
Vector choices=new Vector();
if(E==null)
choices=new Vector();
else
if(E instanceof MOB)
{
for(int i=0;i<((MOB)E).inventorySize();i++)
{
Item I=((MOB)E).fetchInventory(i);
if((I!=null)&&(!I.amWearingAt(Wearable.IN_INVENTORY))&&(I.container()==null))
choices.addElement(I);
}
}
else
if((E instanceof Item)&&(!(((Item)E).amWearingAt(Wearable.IN_INVENTORY))))
{
choices.addElement(E);
if(E instanceof Container)
choices=((Container)E).getContents();
}
if(choices.size()>0)
results.append(((Item)choices.elementAt(CMLib.dice().roll(1,choices.size(),-1))).name());
break;
}
case 4: // isnpc
case 5: // ispc
results.append("[unimplemented function]");
break;
case 87: // isbirthday
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)&&(((MOB)E).playerStats().getBirthday()!=null))
{
MOB mob=(MOB)E;
TimeClock C=CMLib.time().globalClock();
int day=C.getDayOfMonth();
int month=C.getMonth();
int year=C.getYear();
int bday=mob.playerStats().getBirthday()[0];
int bmonth=mob.playerStats().getBirthday()[1];
if((month>bmonth)||((month==bmonth)&&(day>bday)))
year++;
StringBuffer timeDesc=new StringBuffer("");
if(C.getDaysInWeek()>0)
{
long x=((long)year)*((long)C.getMonthsInYear())*C.getDaysInMonth();
x=x+((long)(bmonth-1))*((long)C.getDaysInMonth());
x=x+bmonth;
timeDesc.append(C.getWeekNames()[(int)(x%C.getDaysInWeek())]+", ");
}
timeDesc.append("the "+bday+CMath.numAppendage(bday));
timeDesc.append(" day of "+C.getMonthNames()[bmonth-1]);
if(C.getYearNames().length>0)
timeDesc.append(", "+CMStrings.replaceAll(C.getYearNames()[year%C.getYearNames().length],"#",""+year));
results.append(timeDesc.toString());
}
break;
}
case 6: // isgood
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB)))
{
Faction.FactionRange FR=CMLib.factions().getRange(CMLib.factions().AlignID(),((MOB)E).fetchFaction(CMLib.factions().AlignID()));
if(FR!=null)
results.append(FR.name());
else
results.append(((MOB)E).fetchFaction(CMLib.factions().AlignID()));
}
break;
}
case 8: // isevil
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB)))
results.append(CMStrings.capitalizeAndLower(CMLib.flags().getAlignmentName(E)).toLowerCase());
break;
}
case 9: // isneutral
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB)))
results.append(((MOB)E).fetchFaction(CMLib.factions().AlignID()));
break;
}
case 11: // isimmort
results.append("[unimplemented function]");
break;
case 54: // isalive
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead()))
results.append(((MOB)E).healthText(null));
else
if(E!=null)
results.append(E.name()+" is dead.");
break;
}
case 58: // isable
{
String arg1=CMParms.getCleanBit(funcParms,0);
String arg2=CMParms.getPastBitClean(funcParms,0);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead()))
{
ExpertiseLibrary X=(ExpertiseLibrary)CMLib.expertises().findDefinition(arg2,true);
if(X!=null)
{
String s=((MOB)E).fetchExpertise(X.ID());
if(s!=null) results.append(s);
}
else
{
Ability A=((MOB)E).findAbility(arg2);
if(A!=null) results.append(""+A.proficiency());
}
}
break;
}
case 59: // isopen
{
String arg1=CMParms.cleanBit(funcParms);
int dir=Directions.getGoodDirectionCode(arg1);
boolean returnable=false;
if(dir<0)
{
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof Container))
returnable=((Container)E).isOpen();
else
if((E!=null)&&(E instanceof Exit))
returnable=((Exit)E).isOpen();
}
else
if(lastKnownLocation!=null)
{
Exit E=lastKnownLocation.getExitInDir(dir);
if(E!=null) returnable= E.isOpen();
}
results.append(""+returnable);
break;
}
case 60: // islocked
{
String arg1=CMParms.cleanBit(funcParms);
int dir=Directions.getGoodDirectionCode(arg1);
if(dir<0)
{
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof Container))
results.append(((Container)E).keyName());
else
if((E!=null)&&(E instanceof Exit))
results.append(((Exit)E).keyName());
}
else
if(lastKnownLocation!=null)
{
Exit E=lastKnownLocation.getExitInDir(dir);
if(E!=null)
results.append(E.keyName());
}
break;
}
case 62: // callfunc
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0));
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
String found=null;
boolean validFunc=false;
Vector scripts=getScripts();
String trigger=null;
String[] ttrigger=null;
for(int v=0;v<scripts.size();v++)
{
DVector script2=(DVector)scripts.elementAt(v);
if(script2.size()<1) continue;
trigger=((String)script2.elementAt(0,1)).toUpperCase().trim();
ttrigger=(String[])script2.elementAt(0,2);
if(getTriggerCode(trigger,ttrigger)==17)
{
String fnamed=CMParms.getCleanBit(trigger,1);
if(fnamed.equalsIgnoreCase(arg1))
{
validFunc=true;
found=
execute(scripted,
source,
target,
monster,
primaryItem,
secondaryItem,
script2,
varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2),
tmp);
if(found==null) found="";
break;
}
}
}
if(!validFunc)
logError(scripted,"CALLFUNC","Unknown","Function: "+arg1);
else
results.append(found);
break;
}
case 61: // strin
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0));
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
Vector V=CMParms.parse(arg1.toUpperCase());
results.append(V.indexOf(arg2.toUpperCase()));
break;
}
case 55: // ispkill
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
results.append("false");
else
if(CMath.bset(((MOB)E).getBitmap(),MOB.ATT_PLAYERKILL))
results.append("true");
else
results.append("false");
break;
}
case 10: // isfight
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB))&&(((MOB)E).isInCombat()))
results.append(((MOB)E).getVictim().name());
break;
}
case 12: // ischarmed
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
Vector V=CMLib.flags().flaggedAffects(E,Ability.FLAG_CHARMING);
for(int v=0;v<V.size();v++)
results.append((((Ability)V.elementAt(v)).name())+" ");
}
break;
}
case 15: // isfollow
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(((MOB)E).amFollowing()!=null)
&&(((MOB)E).amFollowing().location()==lastKnownLocation))
results.append(((MOB)E).amFollowing().name());
break;
}
case 73: // isservant
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(((MOB)E).getLiegeID()!=null)&&(((MOB)E).getLiegeID().length()>0))
results.append(((MOB)E).getLiegeID());
break;
}
case 56: // name
case 7: // isname
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null) results.append(E.name());
break;
}
case 75: // currency
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)results.append(CMLib.beanCounter().getCurrency(E));
break;
}
case 14: // affected
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
{
if(((MOB)E).numAllEffects()>0)
results.append(E.fetchEffect(CMLib.dice().roll(1,((MOB)E).numAllEffects(),-1)).name());
}
else
if((E!=null)&&(E.numEffects()>0))
results.append(E.fetchEffect(CMLib.dice().roll(1,E.numEffects(),-1)).name());
break;
}
case 69: // isbehave
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
for(int i=0;i<E.numBehaviors();i++)
results.append(E.fetchBehavior(i).ID()+" ");
break;
}
case 70: // ipaddress
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster()))
results.append(((MOB)E).session().getAddress());
break;
}
case 28: // questwinner
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster()))
for(int q=0;q<CMLib.quests().numQuests();q++)
{
Quest Q=CMLib.quests().fetchQuest(q);
if((Q!=null)&&(Q.wasWinner(E.Name())))
results.append(Q.name()+" ");
}
break;
}
case 93: // questscripted
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster()))
{
for(int s=0;s<E.numScripts();s++)
{
ScriptingEngine S=E.fetchScript(s);
if((S!=null)&&(S.defaultQuestName()!=null)&&(S.defaultQuestName().length()>0))
{
Quest Q=CMLib.quests().fetchQuest(S.defaultQuestName());
if(Q!=null)
results.append(Q.name()+" ");
else
results.append(S.defaultQuestName()+" ");
}
}
}
break;
}
case 30: // questobj
{
String questName=CMParms.cleanBit(funcParms);
questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName);
Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName);
break;
}
StringBuffer list=new StringBuffer("");
int num=1;
Environmental E=Q.getQuestItem(num);
while(E!=null)
{
if(E.Name().indexOf(' ')>=0)
list.append("\""+E.Name()+"\" ");
else
list.append(E.Name()+" ");
num++;
E=Q.getQuestItem(num);
}
results.append(list.toString().trim());
break;
}
case 94: // questroom
{
String questName=CMParms.cleanBit(funcParms);
questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName);
Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName);
break;
}
StringBuffer list=new StringBuffer("");
int num=1;
Environmental E=Q.getQuestRoom(num);
while(E!=null)
{
String roomID=CMLib.map().getExtendedRoomID((Room)E);
if(roomID.indexOf(' ')>=0)
list.append("\""+roomID+"\" ");
else
list.append(roomID+" ");
num++;
E=Q.getQuestRoom(num);
}
results.append(list.toString().trim());
}
case 29: // questmob
{
String questName=CMParms.cleanBit(funcParms);
questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName);
Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName);
break;
}
StringBuffer list=new StringBuffer("");
int num=1;
Environmental E=Q.getQuestMob(num);
while(E!=null)
{
if(E.Name().indexOf(' ')>=0)
list.append("\""+E.Name()+"\" ");
else
list.append(E.Name()+" ");
num++;
E=Q.getQuestMob(num);
}
results.append(list.toString().trim());
break;
}
case 31: // isquestmobalive
{
String questName=CMParms.cleanBit(funcParms);
questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName);
Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName);
break;
}
StringBuffer list=new StringBuffer("");
int num=1;
Environmental E=Q.getQuestMob(num);
while(E!=null)
{
if(CMLib.flags().isInTheGame(E,true))
{
if(E.Name().indexOf(' ')>=0)
list.append("\""+E.Name()+"\" ");
else
list.append(E.Name()+" ");
}
num++;
E=Q.getQuestMob(num);
}
results.append(list.toString().trim());
break;
}
case 32: // nummobsinarea
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
int num=0;
Vector MASK=null;
if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("="))))
{
arg1=arg1.substring(4).trim();
arg1=arg1.substring(1).trim();
MASK=CMLib.masking().maskCompile(arg1);
}
for(Enumeration e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
{
Room R=(Room)e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
MOB M=R.fetchInhabitant(m);
if(M==null) continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.name(),arg1))
num++;
}
}
results.append(num);
break;
}
case 33: // nummobs
{
int num=0;
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
Vector MASK=null;
if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("="))))
{
arg1=arg1.substring(4).trim();
arg1=arg1.substring(1).trim();
MASK=CMLib.masking().maskCompile(arg1);
}
try
{
for(Enumeration e=CMLib.map().rooms();e.hasMoreElements();)
{
Room R=(Room)e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
MOB M=R.fetchInhabitant(m);
if(M==null) continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.name(),arg1))
num++;
}
}
}catch(NoSuchElementException nse){}
results.append(num);
break;
}
case 34: // numracesinarea
{
int num=0;
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
Room R=null;
MOB M=null;
for(Enumeration e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
{
R=(Room)e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
M=R.fetchInhabitant(m);
if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1)))
num++;
}
}
results.append(num);
break;
}
case 35: // numraces
{
int num=0;
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
Room R=null;
MOB M=null;
try
{
for(Enumeration e=CMLib.map().rooms();e.hasMoreElements();)
{
R=(Room)e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
M=R.fetchInhabitant(m);
if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1)))
num++;
}
}
}catch(NoSuchElementException nse){}
results.append(num);
break;
}
case 16: // hitprcnt
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
{
double hitPctD=CMath.div(((MOB)E).curState().getHitPoints(),((MOB)E).maxState().getHitPoints());
int val1=(int)Math.round(hitPctD*100.0);
results.append(val1);
}
break;
}
case 50: // isseason
{
if(monster.location()!=null)
results.append(TimeClock.SEASON_DESCS[monster.location().getArea().getTimeObj().getSeasonCode()]);
break;
}
case 51: // isweather
{
if(monster.location()!=null)
results.append(Climate.WEATHER_DESCS[monster.location().getArea().getClimateObj().weatherType(monster.location())]);
break;
}
case 57: // ismoon
{
if(monster.location()!=null)
results.append(TimeClock.PHASE_DESC[monster.location().getArea().getTimeObj().getMoonPhase()]);
break;
}
case 38: // istime
{
if(lastKnownLocation!=null)
results.append(TimeClock.TOD_DESC[lastKnownLocation.getArea().getTimeObj().getTODCode()].toLowerCase());
break;
}
case 39: // isday
{
if(lastKnownLocation!=null)
results.append(""+lastKnownLocation.getArea().getTimeObj().getDayOfMonth());
break;
}
case 43: // roommob
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
Environmental which=null;
if(lastKnownLocation!=null)
{
which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
if(which!=null)
{
Vector list=new Vector();
for(int i=0;i<lastKnownLocation.numInhabitants();i++)
{
MOB M=lastKnownLocation.fetchInhabitant(i);
if(M!=null) list.addElement(M);
}
results.append(CMLib.english().getContextName(list,which));
}
}
break;
}
case 44: // roomitem
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
Environmental which=null;
int ct=1;
if(lastKnownLocation!=null)
{
Vector list=new Vector();
for(int i=0;i<lastKnownLocation.numItems();i++)
{
Item I=lastKnownLocation.fetchItem(i);
if((I!=null)&&(I.container()==null))
{
list.addElement(I);
if(ct==CMath.s_int(arg1.trim()))
{ which=I; break;}
ct++;
}
}
if(which!=null)
results.append(CMLib.english().getContextName(list,which));
}
break;
}
case 45: // nummobsroom
{
int num=0;
if(lastKnownLocation!=null)
{
num=lastKnownLocation.numInhabitants();
String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if((name.length()>0)&&(!name.equalsIgnoreCase("*")))
{
num=0;
Vector MASK=null;
if((name.toUpperCase().startsWith("MASK")&&(name.substring(4).trim().startsWith("="))))
{
name=name.substring(4).trim();
name=name.substring(1).trim();
MASK=CMLib.masking().maskCompile(name);
}
for(int i=0;i<lastKnownLocation.numInhabitants();i++)
{
MOB M=lastKnownLocation.fetchInhabitant(i);
if(M==null) continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.Name(),name)
||CMLib.english().containsString(M.displayText(),name))
num++;
}
}
}
results.append(""+num);
break;
}
case 63: // numpcsroom
{
if(lastKnownLocation!=null)
results.append(""+lastKnownLocation.numPCInhabitants());
break;
}
case 79: // numpcsarea
{
if(lastKnownLocation!=null)
{
int num=0;
for(int s=0;s<CMLib.sessions().size();s++)
{
Session S=CMLib.sessions().elementAt(s);
if((S!=null)&&(S.mob()!=null)&&(S.mob().location()!=null)&&(S.mob().location().getArea()==lastKnownLocation.getArea()))
num++;
}
results.append(""+num);
}
break;
}
case 77: // explored
{
String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0));
String where=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,1));
Environmental E=getArgumentMOB(whom,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
{
Area A=null;
if(!where.equalsIgnoreCase("world"))
{
A=CMLib.map().getArea(where);
if(A==null)
{
Environmental E2=getArgumentItem(where,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E2!=null)
A=CMLib.map().areaLocation(E2);
}
}
if((lastKnownLocation!=null)
&&((A!=null)||(where.equalsIgnoreCase("world"))))
{
int pct=0;
MOB M=(MOB)E;
if(M.playerStats()!=null)
pct=M.playerStats().percentVisited(M,A);
results.append(""+pct);
}
}
break;
}
case 72: // faction
{
String arg1=CMParms.getCleanBit(funcParms,0);
String arg2=CMParms.getPastBit(funcParms,0);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
Faction F=CMLib.factions().getFaction(arg2);
if(F==null)
logError(scripted,"FACTION","Unknown Faction",arg1);
else
if((E!=null)&&(E instanceof MOB)&&(((MOB)E).hasFaction(F.factionID())))
{
int value=((MOB)E).fetchFaction(F.factionID());
Faction.FactionRange FR=CMLib.factions().getRange(F.factionID(),value);
if(FR!=null)
results.append(FR.name());
}
break;
}
case 46: // numitemsroom
{
int ct=0;
if(lastKnownLocation!=null)
for(int i=0;i<lastKnownLocation.numItems();i++)
{
Item I=lastKnownLocation.fetchItem(i);
if((I!=null)&&(I.container()==null))
ct++;
}
results.append(""+ct);
break;
}
case 47: //mobitem
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0));
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
MOB M=null;
if(lastKnownLocation!=null)
M=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
Item which=null;
int ct=1;
if(M!=null)
for(int i=0;i<M.inventorySize();i++)
{
Item I=M.fetchInventory(i);
if((I!=null)&&(I.container()==null))
{
if(ct==CMath.s_int(arg2.trim()))
{ which=I; break;}
ct++;
}
}
if(which!=null)
results.append(which.name());
break;
}
case 48: // numitemsmob
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
MOB which=null;
if(lastKnownLocation!=null)
which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
int ct=1;
if(which!=null)
for(int i=0;i<which.inventorySize();i++)
{
Item I=which.fetchInventory(i);
if((I!=null)&&(I.container()==null))
ct++;
}
results.append(""+ct);
break;
}
case 36: // ishere
{
if(lastKnownLocation!=null)
results.append(lastKnownLocation.getArea().name());
break;
}
case 17: // inroom
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||arg1.length()==0)
results.append(CMLib.map().getExtendedRoomID(lastKnownLocation));
else
results.append(CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(E)));
break;
}
case 90: // inarea
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||arg1.length()==0)
results.append(lastKnownLocation==null?"Nowhere":lastKnownLocation.getArea().Name());
else
{
Room R=CMLib.map().roomLocation(E);
results.append(R==null?"Nowhere":R.getArea().Name());
}
break;
}
case 89: // isrecall
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null) results.append(CMLib.map().getExtendedRoomID(CMLib.map().getStartRoom(E)));
break;
}
case 37: // inlocale
{
String parms=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if(parms.trim().length()==0)
{
if(lastKnownLocation!=null)
results.append(lastKnownLocation.name());
}
else
{
Environmental E=getArgumentItem(parms,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
Room R=CMLib.map().roomLocation(E);
if(R!=null)
results.append(R.name());
}
}
break;
}
case 18: // sex
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
results.append(((MOB)E).charStats().genderName());
break;
}
case 91: // datetime
{
String arg1=CMParms.getCleanBit(funcParms,0);
int index=CMParms.indexOf(ScriptingEngine.DATETIME_ARGS,arg1.toUpperCase().trim());
if(index<0)
logError(scripted,"DATETIME","Syntax","Unknown arg: "+arg1+" for "+scripted.name());
else
if(CMLib.map().areaLocation(scripted)!=null)
switch(index)
{
case 2: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth()); break;
case 3: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth()); break;
case 4: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getMonth()); break;
case 5: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getYear()); break;
default:
results.append(CMLib.map().areaLocation(scripted).getTimeObj().getTimeOfDay()); break;
}
break;
}
case 13: // stat
{
String arg1=CMParms.getCleanBit(funcParms,0);
String arg2=CMParms.getPastBitClean(funcParms,0);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
String val=getStatValue(E,arg2);
if(val==null)
{
logError(scripted,"STAT","Syntax","Unknown stat: "+arg2+" for "+E.name());
break;
}
results.append(val);
break;
}
break;
}
case 52: // gstat
{
String arg1=CMParms.getCleanBit(funcParms,0);
String arg2=CMParms.getPastBitClean(funcParms,0);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
String val=getGStatValue(E,arg2);
if(val==null)
{
logError(scripted,"GSTAT","Syntax","Unknown stat: "+arg2+" for "+E.name());
break;
}
results.append(val);
break;
}
break;
}
case 19: // position
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
String sex="STANDING";
if(CMLib.flags().isSleeping(E))
sex="SLEEPING";
else
if(CMLib.flags().isSitting(E))
sex="SITTING";
results.append(sex);
break;
}
break;
}
case 20: // level
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
results.append(E.envStats().level());
break;
}
case 80: // questpoints
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
results.append(((MOB)E).getQuestPoint());
break;
}
case 83: // qvar
{
String arg1=CMParms.getCleanBit(funcParms,0);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
if((arg1.length()!=0)&&(arg2.length()!=0))
{
Quest Q=getQuest(arg1);
if(Q!=null) results.append(Q.getStat(arg2));
}
break;
}
case 84: // math
{
String arg1=CMParms.cleanBit(funcParms);
results.append(""+Math.round(CMath.s_parseMathExpression(arg1)));
break;
}
case 85: // islike
{
String arg1=CMParms.cleanBit(funcParms);
results.append(CMLib.masking().maskDesc(arg1));
break;
}
case 86: // strcontains
{
results.append("[unimplemented function]");
break;
}
case 81: // trains
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
results.append(((MOB)E).getTrains());
break;
}
case 92: // isodd
{
String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp ,CMParms.cleanBit(funcParms)).trim();
boolean isodd = false;
if( CMath.isLong( val ) )
{
isodd = (CMath.s_long(val) %2 == 1);
}
if( isodd )
{
results.append( CMath.s_long( val.trim() ) );
}
break;
}
case 82: // pracs
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
results.append(((MOB)E).getPractices());
break;
}
case 68: // clandata
{
String arg1=CMParms.getCleanBit(funcParms,0);
String arg2=CMParms.getPastBitClean(funcParms,0);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String clanID=null;
if((E!=null)&&(E instanceof MOB))
clanID=((MOB)E).getClanID();
else
clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1);
Clan C=CMLib.clans().findClan(clanID);
if(C!=null)
{
if(!C.isStat(arg2))
logError(scripted,"CLANDATA","RunTime",arg2+" is not a valid clan variable.");
else
results.append(C.getStat(arg2));
}
break;
}
case 67: // hastitle
{
String arg1=CMParms.getCleanBit(funcParms,0);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()>0)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null))
{
MOB M=(MOB)E;
results.append(M.playerStats().getActiveTitle());
}
break;
}
case 66: // clanrank
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
results.append(((MOB)E).getClanRole()+"");
break;
}
case 21: // class
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
results.append(((MOB)E).charStats().displayClassName());
break;
}
case 64: // deity
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
{
String sex=((MOB)E).getWorshipCharID();
results.append(sex);
}
break;
}
case 65: // clan
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
{
String sex=((MOB)E).getClanID();
results.append(sex);
}
break;
}
case 88: // mood
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(E.fetchEffect("Mood")!=null))
results.append(CMStrings.capitalizeAndLower(E.fetchEffect("Mood").text()));
break;
}
case 22: // baseclass
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
results.append(((MOB)E).charStats().getCurrentClass().baseClass());
break;
}
case 23: // race
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
results.append(((MOB)E).charStats().raceName());
break;
}
case 24: //racecat
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
results.append(((MOB)E).charStats().getMyRace().racialCategory());
break;
}
case 25: // goldamt
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
results.append(false);
else
{
int val1=0;
if(E instanceof MOB)
val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,CMLib.beanCounter().getCurrency(scripted)));
else
if(E instanceof Coins)
val1=(int)Math.round(((Coins)E).getTotalValue());
else
if(E instanceof Item)
val1=((Item)E).value();
else
{
logError(scripted,"GOLDAMT","Syntax",funcParms);
return results.toString();
}
results.append(val1);
}
break;
}
case 78: // exp
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
results.append(false);
else
{
int val1=0;
if(E instanceof MOB)
val1=((MOB)E).getExperience();
results.append(val1);
}
break;
}
case 76: // value
{
String arg1=CMParms.getCleanBit(funcParms,0);
String arg2=CMParms.getPastBitClean(funcParms,0);
if(!CMLib.beanCounter().getAllCurrencies().contains(arg2.toUpperCase()))
{
logError(scripted,"VALUE","Syntax",arg2+" is not a valid designated currency.");
return results.toString();
}
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
results.append(false);
else
{
int val1=0;
if(E instanceof MOB)
val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,arg2));
else
if(E instanceof Coins)
{
if(((Coins)E).getCurrency().equalsIgnoreCase(arg2))
val1=(int)Math.round(((Coins)E).getTotalValue());
}
else
if(E instanceof Item)
val1=((Item)E).value();
else
{
logError(scripted,"GOLDAMT","Syntax",funcParms);
return results.toString();
}
results.append(val1);
}
break;
}
case 26: // objtype
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
String sex=CMClass.classID(E).toLowerCase();
results.append(sex);
}
break;
}
case 53: // incontainer
{
String arg1=CMParms.cleanBit(funcParms);
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
if(E instanceof MOB)
{
if(((MOB)E).riding()!=null)
results.append(((MOB)E).riding().Name());
}
else
if(E instanceof Item)
{
if(((Item)E).riding()!=null)
results.append(((Item)E).riding().Name());
else
if(((Item)E).container()!=null)
results.append(((Item)E).container().Name());
else
if(E instanceof Container)
{
Vector V=((Container)E).getContents();
for(int v=0;v<V.size();v++)
results.append("\""+((Item)V.elementAt(v)).Name()+"\" ");
}
}
}
break;
}
case 27: // var
{
String arg1=CMParms.getCleanBit(funcParms,0);
String arg2=CMParms.getPastBitClean(funcParms,0).toUpperCase();
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String val=getVar(E,arg1,arg2,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp);
results.append(val);
break;
}
case 41: // eval
results.append("[unimplemented function]");
break;
case 40: // number
{
String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).trim();
boolean isnumber=(val.length()>0);
for(int i=0;i<val.length();i++)
if(!Character.isDigit(val.charAt(i)))
{ isnumber=false; break;}
if(isnumber)
results.append(CMath.s_long(val.trim()));
break;
}
case 42: // randnum
{
String arg1String=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toUpperCase();
int arg1=0;
if(CMath.isMathExpression(arg1String))
arg1=CMath.s_parseIntExpression(arg1String.trim());
else
arg1=CMParms.parse(arg1String.trim()).size();
results.append(CMLib.dice().roll(1,arg1,0));
break;
}
case 71: // rand0num
{
String arg1String=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toUpperCase();
int arg1=0;
if(CMath.isMathExpression(arg1String))
arg1=CMath.s_parseIntExpression(arg1String.trim());
else
arg1=CMParms.parse(arg1String.trim()).size();
results.append(CMLib.dice().roll(1,arg1,-1));
break;
}
default:
logError(scripted,"Unknown Val",preFab,evaluable);
return results.toString();
}
}
if((z>=0)&&(z<=evaluable.length()))
{
evaluable=evaluable.substring(z+1).trim();
uevaluable=uevaluable.substring(z+1).trim();
}
}
return results.toString();
}
protected MOB getRandPC(MOB monster, Object[] tmp, Room room)
{
if((tmp[SPECIAL_RANDPC]==null)||(tmp[SPECIAL_RANDPC]==monster)) {
MOB M=null;
if(room!=null) {
Vector choices = new Vector();
for(int p=0;p<room.numInhabitants();p++)
{
M=room.fetchInhabitant(p);
if((!M.isMonster())&&(M!=monster))
{
HashSet seen=new HashSet();
while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M)))
{
seen.add(M);
M=M.amFollowing();
}
choices.addElement(M);
}
}
if(choices.size() > 0)
tmp[SPECIAL_RANDPC] = choices.elementAt(CMLib.dice().roll(1,choices.size(),-1));
}
}
return (MOB)tmp[SPECIAL_RANDPC];
}
protected MOB getRandAnyone(MOB monster, Object[] tmp, Room room)
{
if((tmp[SPECIAL_RANDANYONE]==null)||(tmp[SPECIAL_RANDANYONE]==monster)) {
MOB M=null;
if(room!=null) {
Vector choices = new Vector();
for(int p=0;p<room.numInhabitants();p++)
{
M=room.fetchInhabitant(p);
if(M!=monster)
{
HashSet seen=new HashSet();
while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M)))
{
seen.add(M);
M=M.amFollowing();
}
choices.addElement(M);
}
}
if(choices.size() > 0)
tmp[SPECIAL_RANDANYONE] = choices.elementAt(CMLib.dice().roll(1,choices.size(),-1));
}
}
return (MOB)tmp[SPECIAL_RANDANYONE];
}
public String execute(Environmental scripted,
MOB source,
Environmental target,
MOB monster,
Item primaryItem,
Item secondaryItem,
DVector script,
String msg,
Object[] tmp)
{
tickStatus=Tickable.STATUS_START;
String s=null;
String[] tt=null;
String cmd=null;
for(int si=1;si<script.size();si++)
{
s=((String)script.elementAt(si,1)).trim();
tt=(String[])script.elementAt(si,2);
if(tt!=null)
cmd=tt[0];
else
cmd=CMParms.getCleanBit(s,0).toUpperCase();
if(cmd.length()==0) continue;
Integer methCode=(Integer)methH.get(cmd);
if((methCode==null)&&(cmd.startsWith("MP")))
for(int i=0;i<methods.length;i++)
if(methods[i].startsWith(cmd))
methCode=Integer.valueOf(i);
if(methCode==null) methCode=Integer.valueOf(0);
tickStatus=Tickable.STATUS_MISC3+methCode.intValue();
switch(methCode.intValue())
{
case 57: // <SCRIPT>
{
if(tt==null) tt=parseBits(script,si,"C");
StringBuffer jscript=new StringBuffer("");
while((++si)<script.size())
{
s=((String)script.elementAt(si,1)).trim();
tt=(String[])script.elementAt(si,2);
if(tt!=null)
cmd=tt[0];
else
cmd=CMParms.getCleanBit(s,0).toUpperCase();
if(cmd.equals("</SCRIPT>"))
{
if(tt==null) tt=parseBits(script,si,"C");
break;
}
jscript.append(s+"\n");
}
if(CMSecurity.isApprovedJScript(jscript))
{
Context cx = Context.enter();
try
{
JScriptEvent scope = new JScriptEvent(this,scripted,source,target,monster,primaryItem,secondaryItem,msg);
cx.initStandardObjects(scope);
String[] names = { "host", "source", "target", "monster", "item", "item2", "message" ,"getVar", "setVar", "toJavaString"};
scope.defineFunctionProperties(names, JScriptEvent.class,
ScriptableObject.DONTENUM);
cx.evaluateString(scope, jscript.toString(),"<cmd>", 1, null);
}
catch(Exception e)
{
Log.errOut("Scripting",scripted.name()+"/"+CMLib.map().getExtendedRoomID(lastKnownLocation)+"/JSCRIPT Error: "+e.getMessage());
}
Context.exit();
}
else
if(CMProps.getIntVar(CMProps.SYSTEMI_JSCRIPTS)==1)
{
if(lastKnownLocation!=null)
lastKnownLocation.showHappens(CMMsg.MSG_OK_ACTION,"A Javascript was not authorized. Contact an Admin to use MODIFY JSCRIPT to authorize this script.");
}
break;
}
case 19: // if
{
if(tt==null){
try {
String[] ttParms=parseEval(s.substring(2));
tt=new String[ttParms.length+1];
tt[0]="IF";
for(int i=0;i<ttParms.length;i++)
tt[i+1]=ttParms[i];
script.setElementAt(si,2,tt);
} catch(Exception e) {
logError(scripted,"IF","Syntax",e.getMessage());
tickStatus=Tickable.STATUS_END;
return null;
}
}
String[][] EVAL={tt};
boolean condition=eval(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,EVAL,1);
if(EVAL[0]!=tt)
{
tt=EVAL[0];
script.setElementAt(si,2,tt);
}
DVector V=new DVector(2);
V.addElement("",null);
int depth=0;
boolean foundendif=false;
boolean ignoreUntilEndScript=false;
si++;
while(si<script.size())
{
s=((String)script.elementAt(si,1)).trim();
tt=(String[])script.elementAt(si,2);
if(tt!=null)
cmd=tt[0];
else
cmd=CMParms.getCleanBit(s,0).toUpperCase();
if(cmd.equals("<SCRIPT>"))
{
if(tt==null) tt=parseBits(script,si,"C");
ignoreUntilEndScript=true;
}
else
if(cmd.equals("</SCRIPT>"))
{
if(tt==null) tt=parseBits(script,si,"C");
ignoreUntilEndScript=false;
}
else
if(ignoreUntilEndScript){}
else
if(cmd.equals("ENDIF")&&(depth==0))
{
if(tt==null) tt=parseBits(script,si,"C");
foundendif=true;
break;
}
else
if(cmd.equals("ELSE")&&(depth==0))
{
condition=!condition;
if(s.substring(4).trim().length()>0)
{
script.setElementAt(si,1,"ELSE");
script.setElementAt(si,2,new String[]{"ELSE"});
script.insertElementAt(si+1,s.substring(4).trim(),null);
}
else
if(tt==null)
tt=parseBits(script,si,"C");
}
else
{
if(cmd.equals("IF"))
depth++;
else
if(cmd.equals("ENDIF"))
{
if(tt==null)
tt=parseBits(script,si,"C");
depth--;
}
if(condition)
V.addSharedElements(script.elementsAt(si));
}
si++;
}
if(!foundendif)
{
logError(scripted,"IF","Syntax"," Without ENDIF!");
tickStatus=Tickable.STATUS_END;
return null;
}
if(V.size()>1)
{
//source.tell("Starting "+conditionStr);
//for(int v=0;v<V.size();v++)
// source.tell("Statement "+((String)V.elementAt(v)));
String response=execute(scripted,source,target,monster,primaryItem,secondaryItem,V,msg,tmp);
if(response!=null)
{
tickStatus=Tickable.STATUS_END;
return response;
}
//source.tell("Stopping "+conditionStr);
}
break;
}
case 70: // switch
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]).trim();
DVector V=new DVector(2);
V.addElement("",null);
int depth=0;
boolean foundendif=false;
boolean ignoreUntilEndScript=false;
boolean inCase=false;
boolean matchedCase=false;
si++;
String s2=null;
while(si<script.size())
{
s=((String)script.elementAt(si,1)).trim();
tt=(String[])script.elementAt(si,2);
if(tt!=null)
cmd=tt[0];
else
cmd=CMParms.getCleanBit(s,0).toUpperCase();
if(cmd.equals("<SCRIPT>"))
{
if(tt==null) tt=parseBits(script,si,"C");
ignoreUntilEndScript=true;
}
else
if(cmd.equals("</SCRIPT>"))
{
if(tt==null) tt=parseBits(script,si,"C");
ignoreUntilEndScript=false;
}
else
if(ignoreUntilEndScript){}
else
if(cmd.equals("ENDSWITCH")&&(depth==0))
{
if(tt==null) tt=parseBits(script,si,"C");
foundendif=true;
break;
}
else
if(cmd.equals("CASE")&&(depth==0))
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]).trim();
inCase=var.equalsIgnoreCase(s2);
matchedCase=matchedCase||inCase;
}
else
if(cmd.equals("DEFAULT")&&(depth==0))
{
inCase=!matchedCase;
}
else
{
if(inCase)
V.addElement(s,tt);
if(cmd.equals("SWITCH"))
{
if(tt==null) tt=parseBits(script,si,"Cr");
depth++;
}
else
if(cmd.equals("ENDSWITCH"))
{
if(tt==null) tt=parseBits(script,si,"C");
depth--;
}
}
si++;
}
if(!foundendif)
{
logError(scripted,"SWITCH","Syntax"," Without ENDSWITCH!");
tickStatus=Tickable.STATUS_END;
return null;
}
if(V.size()>1)
{
String response=execute(scripted,source,target,monster,primaryItem,secondaryItem,V,msg,tmp);
if(response!=null)
{
tickStatus=Tickable.STATUS_END;
return response;
}
}
break;
}
case 62: // for x = 1 to 100
{
if(tt==null)
{
tt=parseBits(script,si,"CcccCr");
if(tt==null) return null;
}
if(tt[5].length()==0)
{
logError(scripted,"FOR","Syntax","5 parms required!");
tickStatus=Tickable.STATUS_END;
return null;
}
String varStr=tt[1];
if((varStr.length()!=2)||(varStr.charAt(0)!='$')||(!Character.isDigit(varStr.charAt(1))))
{
logError(scripted,"FOR","Syntax","'"+varStr+"' is not a tmp var $1, $2..");
tickStatus=Tickable.STATUS_END;
return null;
}
int whichVar=CMath.s_int(Character.toString(varStr.charAt(1)));
if((tmp[whichVar] instanceof String)
&&(((String)tmp[whichVar]).length()>0)
&&(CMath.isInteger(((String)tmp[whichVar]).trim())))
{
logError(scripted,"FOR","Syntax","'"+whichVar+"' is already in use! Use a different one!");
tickStatus=Tickable.STATUS_END;
return null;
}
if(!tt[2].equals("="))
{
logError(scripted,"FOR","Syntax","'"+s+"' is illegal for syntax!");
tickStatus=Tickable.STATUS_END;
return null;
}
int toAdd=0;
if(tt[4].equals("TO<"))
toAdd=-1;
else
if(tt[4].equals("TO>"))
toAdd=1;
else
if(!tt[4].equals("TO"))
{
logError(scripted,"FOR","Syntax","'"+s+"' is illegal for syntax!");
tickStatus=Tickable.STATUS_END;
return null;
}
String from=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]).trim();
String to=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[5]).trim();
if((!CMath.isInteger(from))||(!CMath.isInteger(to)))
{
logError(scripted,"FOR","Syntax","'"+from+"-"+to+"' is illegal range!");
tickStatus=Tickable.STATUS_END;
return null;
}
DVector V=new DVector(2);
V.addElement("",null);
int depth=0;
boolean foundnext=false;
boolean ignoreUntilEndScript=false;
si++;
while(si<script.size())
{
s=((String)script.elementAt(si,1)).trim();
tt=(String[])script.elementAt(si,2);
if(tt!=null)
cmd=tt[0];
else
cmd=CMParms.getCleanBit(s,0).toUpperCase();
if(cmd.equals("<SCRIPT>"))
{
if(tt==null) tt=parseBits(script,si,"C");
ignoreUntilEndScript=true;
}
else
if(cmd.equals("</SCRIPT>"))
{
if(tt==null) tt=parseBits(script,si,"C");
ignoreUntilEndScript=false;
}
else
if(ignoreUntilEndScript){}
else
if(cmd.equals("NEXT")&&(depth==0))
{
if(tt==null) tt=parseBits(script,si,"C");
foundnext=true;
break;
}
else
{
if(cmd.equals("FOR"))
{
if(tt==null) tt=parseBits(script,si,"CcccCr");
depth++;
}
else
if(cmd.equals("NEXT"))
{
if(tt==null) tt=parseBits(script,si,"C");
depth--;
}
V.addSharedElements(script.elementsAt(si));
}
si++;
}
if(!foundnext)
{
logError(scripted,"FOR","Syntax"," Without NEXT!");
tickStatus=Tickable.STATUS_END;
return null;
}
if(V.size()>1)
{
//source.tell("Starting "+conditionStr);
//for(int v=0;v<V.size();v++)
// source.tell("Statement "+((String)V.elementAt(v)));
int fromInt=CMath.s_int(from);
int toInt=CMath.s_int(to);
int increment=(toInt>=fromInt)?1:-1;
String response=null;
if(((increment>0)&&(fromInt<=(toInt+toAdd)))
||((increment<0)&&(fromInt>=(toInt+toAdd))))
{
toInt+=toAdd;
long tm=System.currentTimeMillis()+(10 * 1000);
for(int forLoop=fromInt;forLoop!=toInt;forLoop+=increment)
{
tmp[whichVar]=""+forLoop;
response=execute(scripted,source,target,monster,primaryItem,secondaryItem,V,msg,tmp);
if(response!=null) break;
if(System.currentTimeMillis()>tm)
{
logError(scripted,"FOR","Runtime","For loop violates 10 second rule: " +s);
break;
}
}
tmp[whichVar]=""+toInt;
response=execute(scripted,source,target,monster,primaryItem,secondaryItem,V,msg,tmp);
}
if(response!=null)
{
tickStatus=Tickable.STATUS_END;
return response;
}
tmp[whichVar]=null;
//source.tell("Stopping "+conditionStr);
}
break;
}
case 50: // break;
if(tt==null) tt=parseBits(script,si,"C");
tickStatus=Tickable.STATUS_END;
return null;
case 1: // mpasound
{
if(tt==null){
tt=parseBits(script,si,"Cp");
if(tt==null) return null;
}
String echo=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
//lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,echo);
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
Room R2=lastKnownLocation.getRoomInDir(d);
Exit E2=lastKnownLocation.getExitInDir(d);
if((R2!=null)&&(E2!=null)&&(E2.isOpen()))
R2.showOthers(monster,null,null,CMMsg.MSG_OK_ACTION,echo);
}
break;
}
case 4: // mpjunk
{
if(tt==null){
tt=parseBits(script,si,"CR");
if(tt==null) return null;
}
if(tt[1].equals("ALL") && (monster!=null))
{
while(monster.inventorySize()>0)
{
Item I=monster.fetchInventory(0);
if(I!=null)
{
if(I.owner()==null) I.setOwner(monster);
I.destroy();
}
else
break;
}
}
else
{
Environmental E=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
Item I=null;
if(E instanceof Item)
I=(Item)E;
if((I==null)&&(monster!=null))
I=monster.fetchInventory(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]));
if((I==null)&&(scripted instanceof Room))
I=((Room)scripted).fetchAnyItem(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]));
if(I!=null)
I.destroy();
}
break;
}
case 2: // mpecho
{
if(tt==null){
tt=parseBits(script,si,"Cp");
if(tt==null) return null;
}
if(lastKnownLocation!=null)
lastKnownLocation.show(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]));
break;
}
case 13: // mpunaffect
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String which=tt[2];
if(newTarget!=null)
if(which.equalsIgnoreCase("all")||(which.length()==0))
{
for(int a=newTarget.numEffects()-1;a>=0;a--)
{
Ability A=newTarget.fetchEffect(a);
if(A!=null)
A.unInvoke();
}
}
else
{
Ability A2=CMClass.findAbility(which);
if(A2!=null) which=A2.ID();
Ability A=newTarget.fetchEffect(which);
if(A!=null)
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" was MPUNAFFECTED by "+A.Name());
A.unInvoke();
if(newTarget.fetchEffect(which)==A)
newTarget.delEffect(A);
}
}
break;
}
case 3: // mpslay
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(newTarget instanceof MOB))
CMLib.combat().postDeath(monster,(MOB)newTarget,null);
break;
}
case 73: // mpsetinternal
{
if(tt==null){
tt=parseBits(script,si,"CCr");
if(tt==null) return null;
}
String arg2=tt[1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if(arg2.equals("SCOPE"))
setVarScope(arg3);
else
if(arg2.equals("NODELAY"))
noDelay=CMath.s_bool(arg3);
else
if(arg2.equals("DEFAULTQUEST"))
registerDefaultQuest(arg3);
else
if(arg2.equals("SAVABLE"))
setSavable(CMath.s_bool(arg3));
else
logError(scripted,"MPSETINTERNAL","Syntax","Unknown stat: "+arg2);
break;
}
case 74: // mpprompt
{
if(tt==null){
tt=parseBits(script,si,"CCCr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
String promptStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if((newTarget!=null)&&(newTarget instanceof MOB)&&((((MOB)newTarget).session()!=null)))
{
try {
String value=((MOB)newTarget).session().prompt(promptStr);
setVar(newTarget.Name(),var,value);
} catch(Exception e) { return "";}
}
break;
}
case 75: // mpconfirm
{
if(tt==null){
tt=parseBits(script,si,"CCCCr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
String defaultVal=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
String promptStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]);
if((newTarget!=null)&&(newTarget instanceof MOB)&&((((MOB)newTarget).session()!=null)))
{
try {
String value=((MOB)newTarget).session().confirm(promptStr,defaultVal)?"Y":"N";
setVar(newTarget.Name(),var,value);
} catch(Exception e) { return "";}
}
break;
}
case 76: // mpchoose
{
if(tt==null){
tt=parseBits(script,si,"CCCCCr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
String choices=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
String defaultVal=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]);
String promptStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[5]);
if((newTarget!=null)&&(newTarget instanceof MOB)&&((((MOB)newTarget).session()!=null)))
{
try {
String value=((MOB)newTarget).session().choose(promptStr,choices,defaultVal);
setVar(newTarget.Name(),var,value);
} catch(Exception e) { return "";}
}
break;
}
case 16: // mpset
{
if(tt==null){
tt=parseBits(script,si,"CCcr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String arg2=tt[2];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if(newTarget!=null)
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" has "+arg2+" MPSETTED to "+arg3);
boolean found=false;
for(int i=0;i<newTarget.getStatCodes().length;i++)
{
if(newTarget.getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))+1);
if(arg3.equals("--")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))-1);
newTarget.setStat(arg2,arg3);
found=true;
break;
}
}
if((!found)&&(newTarget instanceof MOB))
{
MOB M=(MOB)newTarget;
for(int i : CharStats.CODES.ALL())
if(CharStats.CODES.NAME(i).equalsIgnoreCase(arg2)||CharStats.CODES.DESC(i).equalsIgnoreCase(arg2))
{
if(arg3.equals("++")) arg3=""+(M.baseCharStats().getStat(i)+1);
if(arg3.equals("--")) arg3=""+(M.baseCharStats().getStat(i)-1);
M.baseCharStats().setStat(i,CMath.s_int(arg3.trim()));
M.recoverCharStats();
if(arg2.equalsIgnoreCase("RACE"))
M.charStats().getMyRace().startRacing(M,false);
found=true;
break;
}
if(!found)
for(int i=0;i<M.curState().getStatCodes().length;i++)
if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))+1);
if(arg3.equals("--")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))-1);
M.curState().setStat(arg2,arg3);
found=true;
break;
}
if(!found)
for(int i=0;i<M.baseEnvStats().getStatCodes().length;i++)
if(M.baseEnvStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++")) arg3=""+(CMath.s_int(M.baseEnvStats().getStat(M.baseEnvStats().getStatCodes()[i]))+1);
if(arg3.equals("--")) arg3=""+(CMath.s_int(M.baseEnvStats().getStat(M.baseEnvStats().getStatCodes()[i]))-1);
M.baseEnvStats().setStat(arg2,arg3);
found=true;
break;
}
if((!found)&&(M.playerStats()!=null))
for(int i=0;i<M.playerStats().getStatCodes().length;i++)
if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))+1);
if(arg3.equals("--")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))-1);
M.playerStats().setStat(arg2,arg3);
found=true;
break;
}
if((!found)&&(arg2.toUpperCase().startsWith("BASE")))
for(int i=0;i<M.baseState().getStatCodes().length;i++)
if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4)))
{
if(arg3.equals("++")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))+1);
if(arg3.equals("--")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))-1);
M.baseState().setStat(arg2.substring(4),arg3);
found=true;
break;
}
if((!found)&&(gstatH.containsKey(arg2.toUpperCase()))) {
found=true;
switch(((Integer)gstatH.get(arg2.toUpperCase())).intValue()) {
case GSTATADD_DEITY: M.setWorshipCharID(arg3); break;
case GSTATADD_CLAN: M.setClanID(arg3); break;
case GSTATADD_CLANROLE: M.setClanRole(CMath.s_int(arg3)); break;
}
}
}
if(!found)
{
logError(scripted,"MPSET","Syntax","Unknown stat: "+arg2+" for "+newTarget.Name());
break;
}
if(newTarget instanceof MOB)
((MOB)newTarget).recoverCharStats();
newTarget.recoverEnvStats();
if(newTarget instanceof MOB)
{
((MOB)newTarget).recoverMaxState();
if(arg2.equalsIgnoreCase("LEVEL"))
{
CMLib.leveler().fillOutMOB(((MOB)newTarget),((MOB)newTarget).baseEnvStats().level());
((MOB)newTarget).recoverMaxState();
((MOB)newTarget).recoverCharStats();
((MOB)newTarget).recoverEnvStats();
((MOB)newTarget).resetToMaxState();
}
}
}
break;
}
case 63: // mpargset
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
String arg1=tt[1];
String arg2=tt[2];
if((arg1.length()!=2)||(!arg1.startsWith("$")))
{
logError(scripted,"MPARGSET","Syntax","Mangled argument var: "+arg1+" for "+scripted.Name());
break;
}
Object O=getArgumentMOB(arg2,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(O==null) O=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((O==null)
&&((!arg2.trim().startsWith("$"))
||(arg2.length()<2)
||((!Character.isDigit(arg2.charAt(1)))
&&(!Character.isLetter(arg2.charAt(1))))))
O=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2);
char c=arg1.charAt(1);
if(Character.isDigit(c))
{
if((O instanceof String)&&(((String)O).equalsIgnoreCase("null")))
O=null;
tmp[CMath.s_int(Character.toString(c))]=O;
}
else
switch(arg1.charAt(1))
{
case 'N':
case 'n': if(O instanceof MOB) source=(MOB)O; break;
case 'B':
case 'b': if(O instanceof Environmental)
lastLoaded=(Environmental)O;
break;
case 'I':
case 'i': if(O instanceof Environmental) scripted=(Environmental)O;
if(O instanceof MOB) monster=(MOB)O;
break;
case 'T':
case 't': if(O instanceof Environmental) target=(Environmental)O; break;
case 'O':
case 'o': if(O instanceof Item) primaryItem=(Item)O; break;
case 'P':
case 'p': if(O instanceof Item) secondaryItem=(Item)O; break;
case 'd':
case 'D': if(O instanceof Room) lastKnownLocation=(Room)O; break;
case 'g':
case 'G': if(O instanceof String) msg=(String)O; break;
default:
logError(scripted,"MPARGSET","Syntax","Invalid argument var: "+arg1+" for "+scripted.Name());
break;
}
break;
}
case 35: // mpgset
{
if(tt==null){
tt=parseBits(script,si,"Cccr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String arg2=tt[2];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if(newTarget!=null)
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" has "+arg2+" MPGSETTED to "+arg3);
boolean found=false;
for(int i=0;i<newTarget.getStatCodes().length;i++)
{
if(newTarget.getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))+1);
if(arg3.equals("--")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))-1);
newTarget.setStat(newTarget.getStatCodes()[i],arg3);
found=true; break;
}
}
if(!found)
if(newTarget instanceof MOB)
{
for(int i=0;i<GenericBuilder.GENMOBCODES.length;i++)
{
if(GenericBuilder.GENMOBCODES[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenMobStat((MOB)newTarget,GenericBuilder.GENMOBCODES[i]))+1);
if(arg3.equals("--")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenMobStat((MOB)newTarget,GenericBuilder.GENMOBCODES[i]))-1);
CMLib.coffeeMaker().setGenMobStat((MOB)newTarget,GenericBuilder.GENMOBCODES[i],arg3);
found=true;
break;
}
}
if(!found)
{
MOB M=(MOB)newTarget;
for(int i : CharStats.CODES.ALL())
{
if(CharStats.CODES.NAME(i).equalsIgnoreCase(arg2)||CharStats.CODES.DESC(i).equalsIgnoreCase(arg2))
{
if(arg3.equals("++")) arg3=""+(M.baseCharStats().getStat(i)+1);
if(arg3.equals("--")) arg3=""+(M.baseCharStats().getStat(i)-1);
if((arg3.length()==1)&&(Character.isLetter(arg3.charAt(0))))
M.baseCharStats().setStat(i,arg3.charAt(0));
else
M.baseCharStats().setStat(i,CMath.s_int(arg3.trim()));
M.recoverCharStats();
if(arg2.equalsIgnoreCase("RACE"))
M.charStats().getMyRace().startRacing(M,false);
found=true;
break;
}
}
if(!found)
for(int i=0;i<M.curState().getStatCodes().length;i++)
{
if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))+1);
if(arg3.equals("--")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))-1);
M.curState().setStat(arg2,arg3);
found=true;
break;
}
}
if(!found)
for(int i=0;i<M.baseEnvStats().getStatCodes().length;i++)
{
if(M.baseEnvStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++")) arg3=""+(CMath.s_int(M.baseEnvStats().getStat(M.baseEnvStats().getStatCodes()[i]))+1);
if(arg3.equals("--")) arg3=""+(CMath.s_int(M.baseEnvStats().getStat(M.baseEnvStats().getStatCodes()[i]))-1);
M.baseEnvStats().setStat(arg2,arg3);
found=true;
break;
}
}
if((!found)&&(M.playerStats()!=null))
for(int i=0;i<M.playerStats().getStatCodes().length;i++)
if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))+1);
if(arg3.equals("--")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))-1);
M.playerStats().setStat(arg2,arg3);
found=true;
break;
}
if((!found)&&(arg2.toUpperCase().startsWith("BASE")))
for(int i=0;i<M.baseState().getStatCodes().length;i++)
if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4)))
{
if(arg3.equals("++")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))+1);
if(arg3.equals("--")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))-1);
M.baseState().setStat(arg2.substring(4),arg3);
found=true;
break;
}
if((!found)&&(gstatH.containsKey(arg2.toUpperCase()))) {
found=true;
switch(((Integer)gstatH.get(arg2.toUpperCase())).intValue()) {
case GSTATADD_DEITY: M.setWorshipCharID(arg3); break;
case GSTATADD_CLAN: M.setClanID(arg3); break;
case GSTATADD_CLANROLE: M.setClanRole(CMath.s_int(arg3)); break;
}
}
}
}
else
if(newTarget instanceof Item)
{
for(int i=0;i<GenericBuilder.GENITEMCODES.length;i++)
{
if(GenericBuilder.GENITEMCODES[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenItemStat((Item)newTarget,GenericBuilder.GENITEMCODES[i]))+1);
if(arg3.equals("--")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenItemStat((Item)newTarget,GenericBuilder.GENITEMCODES[i]))-1);
CMLib.coffeeMaker().setGenItemStat((Item)newTarget,GenericBuilder.GENITEMCODES[i],arg3);
found=true;
break;
}
}
}
if(!found)
{
logError(scripted,"MPGSET","Syntax","Unknown stat: "+arg2+" for "+newTarget.Name());
break;
}
if(newTarget instanceof MOB)
((MOB)newTarget).recoverCharStats();
newTarget.recoverEnvStats();
if(newTarget instanceof MOB)
{
((MOB)newTarget).recoverMaxState();
if(arg2.equalsIgnoreCase("LEVEL"))
{
CMLib.leveler().fillOutMOB(((MOB)newTarget),((MOB)newTarget).baseEnvStats().level());
((MOB)newTarget).recoverMaxState();
((MOB)newTarget).recoverCharStats();
((MOB)newTarget).recoverEnvStats();
((MOB)newTarget).resetToMaxState();
}
}
}
break;
}
case 11: // mpexp
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String amtStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
int t=CMath.s_int(amtStr);
if((newTarget!=null)&&(newTarget instanceof MOB))
{
if((amtStr.endsWith("%"))
&&(((MOB)newTarget).getExpNeededLevel()<Integer.MAX_VALUE))
{
int baseLevel=newTarget.baseEnvStats().level();
int lastLevelExpNeeded=(baseLevel<=1)?0:CMLib.leveler().getLevelExperience(baseLevel-1);
int thisLevelExpNeeded=CMLib.leveler().getLevelExperience(baseLevel);
t=(int)Math.round(CMath.mul(thisLevelExpNeeded-lastLevelExpNeeded,
CMath.div(CMath.s_int(amtStr.substring(0,amtStr.length()-1)),100.0)));
}
if(t!=0) CMLib.leveler().postExperience((MOB)newTarget,null,null,t,false);
}
break;
}
case 77: // mpmoney
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentMOB(tt[1],source,monster,scripted,primaryItem,secondaryItem,msg,tmp);
if(newTarget==null) newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String amtStr=tt[2];
amtStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,amtStr).trim();
boolean plus=!amtStr.startsWith("-");
if(amtStr.startsWith("+")||amtStr.startsWith("-"))
amtStr=amtStr.substring(1).trim();
String currency = CMLib.english().numPossibleGoldCurrency(source, amtStr);
long amt = CMLib.english().numPossibleGold(source, amtStr);
double denomination = CMLib.english().numPossibleGoldDenomination(source, currency, amtStr);
Item container = null;
if(newTarget instanceof Item)
{
container = (newTarget instanceof Container)?(Item)newTarget:null;
newTarget = ((Item)newTarget).owner();
}
if(newTarget instanceof MOB)
{
if(plus)
CMLib.beanCounter().giveSomeoneMoney((MOB)newTarget, currency, amt * denomination);
else
CMLib.beanCounter().subtractMoney((MOB)newTarget, currency, amt * denomination);
}
else
{
if(!(newTarget instanceof Room))
newTarget=lastKnownLocation;
if(plus)
CMLib.beanCounter().dropMoney((Room)newTarget, container, currency, amt * denomination);
else
CMLib.beanCounter().removeMoney((Room)newTarget, container, currency, amt * denomination);
}
break;
}
case 59: // mpquestpoints
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
if(newTarget instanceof MOB)
{
if(CMath.isNumber(val))
((MOB)newTarget).setQuestPoint(CMath.s_int(val));
else
if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim())))
((MOB)newTarget).setQuestPoint(((MOB)newTarget).getQuestPoint()+CMath.s_int(val.substring(2).trim()));
else
if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim())))
((MOB)newTarget).setQuestPoint(((MOB)newTarget).getQuestPoint()-CMath.s_int(val.substring(2).trim()));
else
logError(scripted,"QUESTPOINTS","Syntax","Bad syntax "+val+" for "+scripted.Name());
}
break;
}
case 65: // MPQSET
{
if(tt==null){
tt=parseBits(script,si,"Cccr");
if(tt==null) return null;
}
String qstr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
Environmental obj=getArgumentItem(tt[3],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
Quest Q=getQuest(qstr);
if(Q==null)
logError(scripted,"MPQSET","Syntax","Unknown quest "+qstr+" for "+scripted.Name());
else
if(var.equalsIgnoreCase("QUESTOBJ"))
{
if(obj==null)
logError(scripted,"MPQSET","Syntax","Unknown object "+tt[3]+" for "+scripted.Name());
else
{
obj.baseEnvStats().setDisposition(obj.baseEnvStats().disposition()|EnvStats.IS_UNSAVABLE);
obj.recoverEnvStats();
Q.runtimeRegisterObject(obj);
}
}
else
if(var.equalsIgnoreCase("STATISTICS")&&(val.equalsIgnoreCase("ACCEPTED")))
CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTACCEPTED);
else
if(var.equalsIgnoreCase("STATISTICS")&&(val.equalsIgnoreCase("SUCCESS")||val.equalsIgnoreCase("WON")))
CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTSUCCESS);
else
if(var.equalsIgnoreCase("STATISTICS")&&(val.equalsIgnoreCase("FAILED")))
CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTFAILED);
else
{
if(val.equals("++")) val=""+(CMath.s_int(Q.getStat(var))+1);
if(val.equals("--")) val=""+(CMath.s_int(Q.getStat(var))-1);
Q.setStat(var,val);
}
break;
}
case 66: // MPLOG
{
if(tt==null){
tt=parseBits(script,si,"CCcr");
if(tt==null) return null;
}
String type=tt[1];
String head=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if(type.startsWith("E")) Log.errOut("Script","["+head+"] "+val);
else
if(type.startsWith("I")||type.startsWith("S")) Log.infoOut("Script","["+head+"] "+val);
else
if(type.startsWith("D")) Log.debugOut("Script","["+head+"] "+val);
else
logError(scripted,"MPLOG","Syntax","Unknown log type "+type+" for "+scripted.Name());
break;
}
case 67: // MPCHANNEL
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
String channel=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
boolean sysmsg=channel.startsWith("!");
if(sysmsg) channel=channel.substring(1);
String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if(CMLib.channels().getChannelCodeNumber(channel)<0)
logError(scripted,"MPCHANNEL","Syntax","Unknown channel "+channel+" for "+scripted.Name());
else
CMLib.commands().postChannel(monster,channel,val,sysmsg);
break;
}
case 68: // unload
{
if(tt==null){
tt=parseBits(script,si,"Cc");
if(tt==null) return null;
}
String scriptname=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
if(!new CMFile(Resources.makeFileResourceName(scriptname),null,false,true).exists())
logError(scripted,"MPUNLOADSCRIPT","Runtime","File does not exist: "+Resources.makeFileResourceName(scriptname));
else
{
Vector delThese=new Vector();
boolean foundKey=false;
scriptname=scriptname.toUpperCase().trim();
String parmname=scriptname;
Vector V=Resources.findResourceKeys(parmname);
for(Enumeration e=V.elements();e.hasMoreElements();)
{
String key=(String)e.nextElement();
if(key.startsWith("PARSEDPRG: ")&&(key.toUpperCase().endsWith(parmname)))
{ foundKey=true; delThese.addElement(key);}
}
if(foundKey)
for(int i=0;i<delThese.size();i++)
Resources.removeResource((String)delThese.elementAt(i));
}
break;
}
case 60: // trains
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
if(newTarget instanceof MOB)
{
if(CMath.isNumber(val))
((MOB)newTarget).setTrains(CMath.s_int(val));
else
if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim())))
((MOB)newTarget).setTrains(((MOB)newTarget).getTrains()+CMath.s_int(val.substring(2).trim()));
else
if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim())))
((MOB)newTarget).setTrains(((MOB)newTarget).getTrains()-CMath.s_int(val.substring(2).trim()));
else
logError(scripted,"TRAINS","Syntax","Bad syntax "+val+" for "+scripted.Name());
}
break;
}
case 61: // pracs
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
if(newTarget instanceof MOB)
{
if(CMath.isNumber(val))
((MOB)newTarget).setPractices(CMath.s_int(val));
else
if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim())))
((MOB)newTarget).setPractices(((MOB)newTarget).getPractices()+CMath.s_int(val.substring(2).trim()));
else
if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim())))
((MOB)newTarget).setPractices(((MOB)newTarget).getPractices()-CMath.s_int(val.substring(2).trim()));
else
logError(scripted,"PRACS","Syntax","Bad syntax "+val+" for "+scripted.Name());
}
break;
}
case 5: // mpmload
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
Vector Ms=new Vector();
MOB m=CMClass.getMOB(name);
if(m!=null) Ms.addElement(m);
if(lastKnownLocation!=null)
{
if(Ms.size()==0)
findSomethingCalledThis(name,monster,lastKnownLocation,Ms,true);
for(int i=0;i<Ms.size();i++)
{
if(Ms.elementAt(i) instanceof MOB)
{
m=(MOB)((MOB)Ms.elementAt(i)).copyOf();
m.text();
m.recoverEnvStats();
m.recoverCharStats();
m.resetToMaxState();
m.bringToLife(lastKnownLocation,true);
lastLoaded=m;
}
}
}
break;
}
case 6: // mpoload
{
// if not mob
if((scripted instanceof MOB)&&(monster != null))
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
int containerIndex=name.toUpperCase().indexOf(" INTO ");
Container container=null;
if(containerIndex>=0)
{
Vector containers=new Vector();
findSomethingCalledThis(name.substring(containerIndex+6).trim(),monster,lastKnownLocation,containers,false);
for(int c=0;c<containers.size();c++)
if((containers.elementAt(c) instanceof Container)
&&(((Container)containers.elementAt(c)).capacity()>0))
{
container=(Container)containers.elementAt(c);
name=name.substring(0,containerIndex).trim();
break;
}
}
long coins=CMLib.english().numPossibleGold(null,name);
if(coins>0)
{
String currency=CMLib.english().numPossibleGoldCurrency(scripted,name);
double denom=CMLib.english().numPossibleGoldDenomination(scripted,currency,name);
Coins C=CMLib.beanCounter().makeCurrency(currency,denom,coins);
monster.addInventory(C);
C.putCoinsBack();
}
else
if(lastKnownLocation!=null)
{
Vector Is=new Vector();
Item m=CMClass.getItem(name);
if(m!=null)
Is.addElement(m);
else
findSomethingCalledThis(name,(MOB)scripted,lastKnownLocation,Is,false);
for(int i=0;i<Is.size();i++)
{
if(Is.elementAt(i) instanceof Item)
{
m=(Item)Is.elementAt(i);
if((m!=null)&&(!(m instanceof ArchonOnly)))
{
m=(Item)m.copyOf();
m.recoverEnvStats();
m.setContainer(container);
if(container instanceof MOB)
((MOB)container.owner()).addInventory(m);
else
if(container instanceof Room)
((Room)container.owner()).addItemRefuse(m,CMProps.getIntVar(CMProps.SYSTEMI_EXPIRE_PLAYER_DROP));
else
monster.addInventory(m);
lastLoaded=m;
}
}
}
lastKnownLocation.recoverRoomStats();
monster.recoverCharStats();
monster.recoverEnvStats();
monster.recoverMaxState();
}
}
break;
}
case 41: // mpoloadroom
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
if(lastKnownLocation!=null)
{
Vector Is=new Vector();
int containerIndex=name.toUpperCase().indexOf(" INTO ");
Container container=null;
if(containerIndex>=0)
{
Vector containers=new Vector();
findSomethingCalledThis(name.substring(containerIndex+6).trim(),null,lastKnownLocation,containers,false);
for(int c=0;c<containers.size();c++)
if((containers.elementAt(c) instanceof Container)
&&(((Container)containers.elementAt(c)).capacity()>0))
{
container=(Container)containers.elementAt(c);
name=name.substring(0,containerIndex).trim();
break;
}
}
long coins=CMLib.english().numPossibleGold(null,name);
if(coins>0)
{
String currency=CMLib.english().numPossibleGoldCurrency(monster,name);
double denom=CMLib.english().numPossibleGoldDenomination(monster,currency,name);
Coins C=CMLib.beanCounter().makeCurrency(currency,denom,coins);
Is.addElement(C);
}
else
{
Item I=CMClass.getItem(name);
if(I!=null)
Is.addElement(I);
else
findSomethingCalledThis(name,monster,lastKnownLocation,Is,false);
}
for(int i=0;i<Is.size();i++)
{
if(Is.elementAt(i) instanceof Item)
{
Item I=(Item)Is.elementAt(i);
if((I!=null)&&(!(I instanceof ArchonOnly)))
{
I=(Item)I.copyOf();
I.recoverEnvStats();
lastKnownLocation.addItemRefuse(I,CMProps.getIntVar(CMProps.SYSTEMI_EXPIRE_MONSTER_EQ));
I.setContainer(container);
if(I instanceof Coins)
((Coins)I).putCoinsBack();
if(I instanceof RawMaterial)
((RawMaterial)I).rebundle();
lastLoaded=I;
}
}
}
lastKnownLocation.recoverRoomStats();
}
break;
}
case 42: // mphide
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(newTarget!=null)
{
newTarget.baseEnvStats().setDisposition(newTarget.baseEnvStats().disposition()|EnvStats.IS_NOT_SEEN);
newTarget.recoverEnvStats();
if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats();
}
break;
}
case 58: // mpreset
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
String arg=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
if(arg.equalsIgnoreCase("area"))
{
if(lastKnownLocation!=null)
CMLib.map().resetArea(lastKnownLocation.getArea());
}
else
if(arg.equalsIgnoreCase("room"))
{
if(lastKnownLocation!=null)
CMLib.map().resetRoom(lastKnownLocation, true);
}
else
{
Room R=CMLib.map().getRoom(arg);
if(R!=null)
CMLib.map().resetRoom(R, true);
else
{
Area A=CMLib.map().findArea(arg);
if(A!=null)
CMLib.map().resetArea(A);
else
logError(scripted,"MPRESET","Syntax","Unknown location: "+arg+" for "+scripted.Name());
}
}
break;
}
case 71: // mprejuv
{
if(tt==null)
{
String rest=CMParms.getPastBitClean(s,1);
if(rest.equals("item")||rest.equals("items"))
tt=parseBits(script,si,"Ccr");
else
if(rest.equals("mob")||rest.equals("mobs"))
tt=parseBits(script,si,"Ccr");
else
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
String next=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
String rest=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
int tickID=0;
if(rest.equalsIgnoreCase("item")||rest.equalsIgnoreCase("items"))
tickID=Tickable.TICKID_ROOM_ITEM_REJUV;
else
if(rest.equalsIgnoreCase("mob")||rest.equalsIgnoreCase("mobs"))
tickID=Tickable.TICKID_MOB;
if(next.equalsIgnoreCase("area"))
{
if(lastKnownLocation!=null)
for(Enumeration e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
CMLib.threads().rejuv((Room)e.nextElement(),tickID);
}
else
if(next.equalsIgnoreCase("room"))
{
if(lastKnownLocation!=null)
CMLib.threads().rejuv(lastKnownLocation,tickID);
}
else
{
Room R=CMLib.map().getRoom(next);
if(R!=null)
CMLib.threads().rejuv(R,tickID);
else
{
Area A=CMLib.map().findArea(next);
if(A!=null)
for(Enumeration e=A.getProperMap();e.hasMoreElements();)
CMLib.threads().rejuv((Room)e.nextElement(),tickID);
else
logError(scripted,"MPREJUV","Syntax","Unknown location: "+next+" for "+scripted.Name());
}
}
break;
}
case 56: // mpstop
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
Vector V=new Vector();
String who=tt[1];
if(who.equalsIgnoreCase("all"))
{
for(int i=0;i<lastKnownLocation.numInhabitants();i++)
V.addElement(lastKnownLocation.fetchInhabitant(i));
}
else
{
Environmental newTarget=getArgumentItem(who,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(newTarget instanceof MOB)
V.addElement(newTarget);
}
for(int v=0;v<V.size();v++)
{
Environmental newTarget=(Environmental)V.elementAt(v);
if(newTarget instanceof MOB)
{
MOB mob=(MOB)newTarget;
Ability A=null;
for(int a=mob.numEffects()-1;a>=0;a--)
{
A=mob.fetchEffect(a);
if((A!=null)
&&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_COMMON_SKILL)
&&(A.canBeUninvoked())
&&(!A.isAutoInvoked()))
A.unInvoke();
}
mob.makePeace();
if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats();
}
}
break;
}
case 43: // mpunhide
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(CMath.bset(newTarget.baseEnvStats().disposition(),EnvStats.IS_NOT_SEEN)))
{
newTarget.baseEnvStats().setDisposition(newTarget.baseEnvStats().disposition()-EnvStats.IS_NOT_SEEN);
newTarget.recoverEnvStats();
if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats();
}
break;
}
case 44: // mpopen
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget instanceof Exit)&&(((Exit)newTarget).hasADoor()))
{
Exit E=(Exit)newTarget;
E.setDoorsNLocks(E.hasADoor(),true,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked());
if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats();
}
else
if((newTarget instanceof Container)&&(((Container)newTarget).hasALid()))
{
Container E=(Container)newTarget;
E.setLidsNLocks(E.hasALid(),true,E.hasALock(),false);
if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats();
}
break;
}
case 45: // mpclose
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget instanceof Exit)&&(((Exit)newTarget).hasADoor())&&(((Exit)newTarget).isOpen()))
{
Exit E=(Exit)newTarget;
E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked());
if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats();
}
else
if((newTarget instanceof Container)&&(((Container)newTarget).hasALid())&&(((Container)newTarget).isOpen()))
{
Container E=(Container)newTarget;
E.setLidsNLocks(E.hasALid(),false,E.hasALock(),false);
if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats();
}
break;
}
case 46: // mplock
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget instanceof Exit)&&(((Exit)newTarget).hasALock()))
{
Exit E=(Exit)newTarget;
E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),true,E.defaultsLocked());
if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats();
}
else
if((newTarget instanceof Container)&&(((Container)newTarget).hasALock()))
{
Container E=(Container)newTarget;
E.setLidsNLocks(E.hasALid(),false,E.hasALock(),true);
if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats();
}
break;
}
case 47: // mpunlock
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget instanceof Exit)&&(((Exit)newTarget).isLocked()))
{
Exit E=(Exit)newTarget;
E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked());
if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats();
}
else
if((newTarget instanceof Container)&&(((Container)newTarget).isLocked()))
{
Container E=(Container)newTarget;
E.setLidsNLocks(E.hasALid(),false,E.hasALock(),false);
if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats();
}
break;
}
case 48: // return
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
tickStatus=Tickable.STATUS_END;
return varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
case 7: // mpechoat
{
if(tt==null){
tt=parseBits(script,si,"Ccp");
if(tt==null) return null;
}
String parm=tt[1];
Environmental newTarget=getArgumentMOB(parm,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(newTarget instanceof MOB)&&(lastKnownLocation!=null))
{
if(newTarget==monster)
lastKnownLocation.showSource(monster,null,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
else
lastKnownLocation.show(monster,newTarget,null,CMMsg.MSG_OK_ACTION,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]),CMMsg.NO_EFFECT,null);
}
else
if(parm.equalsIgnoreCase("world"))
{
lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
for(Enumeration e=CMLib.map().rooms();e.hasMoreElements();)
{
Room R=(Room)e.nextElement();
if(R.numInhabitants()>0)
R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
}
}
else
if(parm.equalsIgnoreCase("area")&&(lastKnownLocation!=null))
{
lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
for(Enumeration e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
{
Room R=(Room)e.nextElement();
if(R.numInhabitants()>0)
R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
}
}
else
if(CMLib.map().getRoom(parm)!=null)
CMLib.map().getRoom(parm).show(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
else
if(CMLib.map().findArea(parm)!=null)
{
lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
for(Enumeration e=CMLib.map().findArea(parm).getMetroMap();e.hasMoreElements();)
{
Room R=(Room)e.nextElement();
if(R.numInhabitants()>0)
R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
}
}
break;
}
case 8: // mpechoaround
{
if(tt==null){
tt=parseBits(script,si,"Ccp");
if(tt==null) return null;
}
Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(newTarget instanceof MOB)&&(lastKnownLocation!=null))
{
lastKnownLocation.showOthers((MOB)newTarget,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
}
break;
}
case 9: // mpcast
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
Environmental newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
Ability A=null;
if(cast!=null) A=CMClass.findAbility(cast);
if((newTarget!=null)&&(A!=null))
{
A.setProficiency(100);
A.invoke(monster,newTarget,false,0);
}
break;
}
case 30: // mpaffect
{
if(tt==null){
tt=parseBits(script,si,"Cccp");
if(tt==null) return null;
}
String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
Environmental newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
Ability A=null;
if(cast!=null) A=CMClass.findAbility(cast);
if((newTarget!=null)&&(A!=null))
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" was MPAFFECTED by "+A.Name());
A.setMiscText(m2);
if((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_PROPERTY)
newTarget.addNonUninvokableEffect(A);
else
A.invoke(monster,CMParms.parse(m2),newTarget,true,0);
}
break;
}
case 31: // mpbehave
{
if(tt==null){
tt=parseBits(script,si,"Cccp");
if(tt==null) return null;
}
String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
Environmental newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
Behavior B=null;
Behavior B2=(cast==null)?null:CMClass.findBehavior(cast);
if(B2!=null) cast=B2.ID();
if((cast!=null)&&(newTarget!=null))
{
B=newTarget.fetchBehavior(cast);
if(B==null) B=CMClass.getBehavior(cast);
}
if((newTarget!=null)&&(B!=null))
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" was MPBEHAVED with "+B.name());
B.setParms(m2);
if(newTarget.fetchBehavior(B.ID())==null)
{
newTarget.addBehavior(B);
if((defaultQuestName()!=null)&&(defaultQuestName().length()>0))
B.registerDefaultQuest(defaultQuestName());
}
}
break;
}
case 72: // mpscript
{
if(tt==null){
tt=parseBits(script,si,"Ccp");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
boolean proceed=true;
boolean savable=false;
boolean execute=false;
String scope=getVarScope();
while(proceed)
{
proceed=false;
if(m2.toUpperCase().startsWith("SAVABLE"))
{
savable=true;
m2=m2.substring(8).trim();
proceed=true;
}
else
if(m2.toUpperCase().startsWith("EXECUTE"))
{
execute=true;
m2=m2.substring(8).trim();
proceed=true;
}
else
if(m2.toUpperCase().startsWith("GLOBAL"))
{
scope="";
proceed=true;
m2=m2.substring(6).trim();
}
else
if(m2.toUpperCase().startsWith("INDIVIDUAL"))
{
scope="*";
proceed=true;
m2=m2.substring(10).trim();
}
}
if((newTarget!=null)&&(m2.length()>0))
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" was MPSCRIPTED: "+defaultQuestName);
ScriptingEngine S=(ScriptingEngine)CMClass.getCommon("DefaultScriptingEngine");
S.setSavable(savable);
S.setVarScope(scope);
S.setScript(m2);
if((defaultQuestName()!=null)&&(defaultQuestName().length()>0))
S.registerDefaultQuest(defaultQuestName());
newTarget.addScript(S);
if(execute)
{
S.tick(newTarget,Tickable.TICKID_MOB);
for(int i=0;i<5;i++)
S.dequeResponses();
newTarget.delScript(S);
}
}
break;
}
case 32: // mpunbehave
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
Environmental newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(cast!=null))
{
Behavior B=CMClass.findBehavior(cast);
if(B!=null) cast=B.ID();
B=newTarget.fetchBehavior(cast);
if(B!=null) newTarget.delBehavior(B);
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())&&(B!=null))
Log.sysOut("Scripting",newTarget.Name()+" was MPUNBEHAVED with "+B.name());
}
break;
}
case 33: // mptattoo
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String tattooName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if((newTarget!=null)&&(tattooName.length()>0)&&(newTarget instanceof MOB))
{
MOB themob=(MOB)newTarget;
boolean tattooMinus=tattooName.startsWith("-");
if(tattooMinus) tattooName=tattooName.substring(1);
String tattoo=tattooName;
if((tattoo.length()>0)
&&(Character.isDigit(tattoo.charAt(0)))
&&(tattoo.indexOf(" ")>0)
&&(CMath.isNumber(tattoo.substring(0,tattoo.indexOf(" ")).trim())))
tattoo=tattoo.substring(tattoo.indexOf(" ")+1).trim();
if(themob.fetchTattoo(tattoo)!=null)
{
if(tattooMinus)
themob.delTattoo(tattooName);
}
else
if(!tattooMinus)
themob.addTattoo(tattooName);
}
break;
}
case 55: // mpnotrigger
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
String trigger=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
String time=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
int triggerCode=-1;
for(int i=0;i<progs.length;i++)
if(trigger.equalsIgnoreCase(progs[i]))
triggerCode=i;
if(triggerCode<0)
logError(scripted,"MPNOTRIGGER","RunTime",trigger+" is not a valid trigger name.");
else
if(!CMath.isInteger(time.trim()))
logError(scripted,"MPNOTRIGGER","RunTime",time+" is not a valid milisecond time.");
else
{
noTrigger.remove(Integer.valueOf(triggerCode));
noTrigger.put(Integer.valueOf(triggerCode),Long.valueOf(System.currentTimeMillis()+CMath.s_long(time.trim())));
}
break;
}
case 54: // mpfaction
{
if(tt==null){
tt=parseBits(script,si,"Cccr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
String faction=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
String range=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]).trim();
Faction F=CMLib.factions().getFaction(faction);
if((newTarget!=null)&&(F!=null)&&(newTarget instanceof MOB))
{
MOB themob=(MOB)newTarget;
if((range.startsWith("--"))&&(CMath.isInteger(range.substring(2).trim())))
{
int amt=CMath.s_int(range.substring(2).trim());
themob.tell("You lose "+amt+" faction with "+F.name()+".");
range=""+(themob.fetchFaction(faction)-amt);
}
else
if((range.startsWith("+"))&&(CMath.isInteger(range.substring(1).trim())))
{
int amt=CMath.s_int(range.substring(1).trim());
themob.tell("You gain "+amt+" faction with "+F.name()+".");
range=""+(themob.fetchFaction(faction)+amt);
}
else
if(CMath.isInteger(range))
themob.tell("Your faction with "+F.name()+" is now "+CMath.s_int(range.trim())+".");
if(CMath.isInteger(range))
themob.addFaction(F.factionID(),CMath.s_int(range.trim()));
else
{
Faction.FactionRange FR=null;
Enumeration e=CMLib.factions().getRanges(CMLib.factions().AlignID());
if(e!=null)
for(;e.hasMoreElements();)
{
Faction.FactionRange FR2=(Faction.FactionRange)e.nextElement();
if(FR2.name().equalsIgnoreCase(range))
{ FR=FR2; break;}
}
if(FR==null)
logError(scripted,"MPFACTION","RunTime",range+" is not a valid range for "+F.name()+".");
else
{
themob.tell("Your faction with "+F.name()+" is now "+FR.name()+".");
themob.addFaction(F.factionID(),FR.low()+((FR.high()-FR.low())/2));
}
}
}
break;
}
case 49: // mptitle
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String tattooName=tt[2];
if((newTarget!=null)&&(tattooName.length()>0)&&(newTarget instanceof MOB))
{
MOB themob=(MOB)newTarget;
boolean tattooMinus=tattooName.startsWith("-");
if(tattooMinus) tattooName=tattooName.substring(1);
String tattoo=tattooName;
if((tattoo.length()>0)
&&(Character.isDigit(tattoo.charAt(0)))
&&(tattoo.indexOf(" ")>0)
&&(CMath.isNumber(tattoo.substring(0,tattoo.indexOf(" ")).trim())))
tattoo=tattoo.substring(tattoo.indexOf(" ")+1).trim();
if(themob.playerStats()!=null)
{
if(themob.playerStats().getTitles().contains(tattoo))
{
if(tattooMinus)
themob.playerStats().getTitles().removeElement(tattooName);
}
else
if(!tattooMinus)
themob.playerStats().getTitles().insertElementAt(tattooName,0);
}
}
break;
}
case 10: // mpkill
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(newTarget instanceof MOB)&&(monster!=null))
monster.setVictim((MOB)newTarget);
break;
}
case 51: // mpsetclandata
{
if(tt==null){
tt=parseBits(script,si,"Cccr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String clanID=null;
if((newTarget!=null)&&(newTarget instanceof MOB))
clanID=((MOB)newTarget).getClanID();
else
clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
String clanvar=tt[2];
String clanval=tt[3];
Clan C=CMLib.clans().getClan(clanID);
if(C!=null)
{
if(!C.isStat(clanvar))
logError(scripted,"MPSETCLANDATA","RunTime",clanvar+" is not a valid clan variable.");
else
{
C.setStat(clanvar,clanval.trim());
if(C.getStat(clanvar).equalsIgnoreCase(clanval))
C.update();
}
}
break;
}
case 52: // mpplayerclass
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(newTarget instanceof MOB))
{
Vector V=CMParms.parse(tt[2]);
for(int i=0;i<V.size();i++)
{
if(CMath.isInteger(((String)V.elementAt(i)).trim()))
((MOB)newTarget).baseCharStats().setClassLevel(((MOB)newTarget).baseCharStats().getCurrentClass(),CMath.s_int(((String)V.elementAt(i)).trim()));
else
{
CharClass C=CMClass.findCharClass((String)V.elementAt(i));
if(C!=null)
((MOB)newTarget).baseCharStats().setCurrentClass(C);
}
}
((MOB)newTarget).recoverCharStats();
}
break;
}
case 12: // mppurge
{
if(lastKnownLocation!=null)
{
int flag=0;
if(tt==null)
{
String s2=CMParms.getCleanBit(s,1).toLowerCase();
if(s2.equals("room"))
tt=parseBits(script,si,"Ccr");
else
if(s2.equals("my"))
tt=parseBits(script,si,"Ccr");
else
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
String s2=tt[1];
if(s2.equalsIgnoreCase("room"))
{
flag=1;
s2=tt[2];
}
else
if(s2.equalsIgnoreCase("my"))
{
flag=2;
s2=tt[2];
}
Environmental E=null;
if(s2.equalsIgnoreCase("self")||s2.equalsIgnoreCase("me"))
E=scripted;
else
if(flag==1)
{
s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s2);
E=lastKnownLocation.fetchFromRoomFavorItems(null,s2,Wearable.FILTER_ANY);
}
else
if(flag==2)
{
s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s2);
if(monster!=null)
E=monster.fetchInventory(s2);
}
else
E=getArgumentItem(s2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
if(E instanceof MOB)
{
if(!((MOB)E).isMonster())
{
if(((MOB)E).getStartRoom()!=null)
((MOB)E).getStartRoom().bringMobHere((MOB)E,false);
((MOB)E).session().kill(false,false,false);
}
else
if(((MOB)E).getStartRoom()!=null)
((MOB)E).killMeDead(false);
else
((MOB)E).destroy();
}
else
if(E instanceof Item)
{
Environmental oE=((Item)E).owner();
((Item)E).destroy();
if(oE!=null) oE.recoverEnvStats();
}
}
lastKnownLocation.recoverRoomStats();
}
break;
}
case 14: // mpgoto
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
String roomID=tt[1].trim();
if((roomID.length()>0)&&(lastKnownLocation!=null))
{
Room goHere=null;
if(roomID.startsWith("$"))
goHere=CMLib.map().roomLocation(this.getArgumentItem(roomID,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(goHere==null)
goHere=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomID),lastKnownLocation);
if(goHere!=null)
{
if(scripted instanceof MOB)
goHere.bringMobHere((MOB)scripted,true);
else
if(scripted instanceof Item)
goHere.bringItemHere((Item)scripted,CMProps.getIntVar(CMProps.SYSTEMI_EXPIRE_PLAYER_DROP),true);
else
{
goHere.bringMobHere(monster,true);
if(!(scripted instanceof MOB))
goHere.delInhabitant(monster);
}
if(CMLib.map().roomLocation(scripted)==goHere)
lastKnownLocation=goHere;
}
}
break;
}
case 15: // mpat
if(lastKnownLocation!=null)
{
if(tt==null){
tt=parseBits(script,si,"Ccp");
if(tt==null) return null;
}
Room lastPlace=lastKnownLocation;
String roomName=tt[1];
if(roomName.length()>0)
{
String doWhat=tt[2].trim();
Room goHere=null;
if(roomName.startsWith("$"))
goHere=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(goHere==null)
goHere=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation);
if(goHere!=null)
{
goHere.bringMobHere(monster,true);
DVector DV=new DVector(2);
DV.addElement("",null);
DV.addElement(doWhat,null);
lastKnownLocation=goHere;
execute(scripted,source,target,monster,primaryItem,secondaryItem,DV,msg,tmp);
lastKnownLocation=lastPlace;
lastPlace.bringMobHere(monster,true);
if(!(scripted instanceof MOB))
{
goHere.delInhabitant(monster);
lastPlace.delInhabitant(monster);
}
}
}
}
break;
case 17: // mptransfer
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
String mobName=tt[1];
String roomName=tt[2].trim();
Room newRoom=null;
if(roomName.startsWith("$"))
newRoom=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if((roomName.length()==0)&&(lastKnownLocation!=null))
roomName=lastKnownLocation.roomID();
if(roomName.length()>0)
{
if(newRoom==null)
newRoom=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation);
if(newRoom!=null)
{
Vector V=new Vector();
if(mobName.startsWith("$"))
{
Environmental E=getArgumentItem(mobName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null) V.addElement(E);
}
if(V.size()==0)
{
mobName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,mobName);
if(mobName.equalsIgnoreCase("all"))
{
if(lastKnownLocation!=null)
{
for(int x=0;x<lastKnownLocation.numInhabitants();x++)
{
MOB m=lastKnownLocation.fetchInhabitant(x);
if((m!=null)&&(m!=monster)&&(!V.contains(m)))
V.addElement(m);
}
}
}
else
{
MOB findOne=null;
Area A=null;
if(lastKnownLocation!=null)
{
findOne=lastKnownLocation.fetchInhabitant(mobName);
A=lastKnownLocation.getArea();
if((findOne!=null)&&(findOne!=monster))
V.addElement(findOne);
}
if(findOne==null)
{
findOne=CMLib.players().getPlayer(mobName);
if((findOne!=null)&&(!CMLib.flags().isInTheGame(findOne,true)))
findOne=null;
if((findOne!=null)&&(findOne!=monster))
V.addElement(findOne);
}
if((findOne==null)&&(A!=null))
for(Enumeration r=A.getProperMap();r.hasMoreElements();)
{
Room R=(Room)r.nextElement();
findOne=R.fetchInhabitant(mobName);
if((findOne!=null)&&(findOne!=monster))
V.addElement(findOne);
}
}
}
for(int v=0;v<V.size();v++)
{
if(V.elementAt(v) instanceof MOB)
{
MOB mob=(MOB)V.elementAt(v);
HashSet H=mob.getGroupMembers(new HashSet());
for(Iterator e=H.iterator();e.hasNext();)
{
MOB M=(MOB)e.next();
if((!V.contains(M))&&(M.location()==mob.location()))
V.addElement(M);
}
}
}
for(int v=0;v<V.size();v++)
{
if(V.elementAt(v) instanceof MOB)
{
MOB follower=(MOB)V.elementAt(v);
Room thisRoom=follower.location();
// scripting guide calls for NO text -- empty is probably req tho
CMMsg enterMsg=CMClass.getMsg(follower,newRoom,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER," "+CMProps.msp("appear.wav",10));
CMMsg leaveMsg=CMClass.getMsg(follower,thisRoom,null,CMMsg.MSG_LEAVE," ");
if(thisRoom.okMessage(follower,leaveMsg)&&newRoom.okMessage(follower,enterMsg))
{
if(follower.isInCombat())
{
CMLib.commands().postFlee(follower,("NOWHERE"));
follower.makePeace();
}
thisRoom.send(follower,leaveMsg);
newRoom.bringMobHere(follower,false);
newRoom.send(follower,enterMsg);
follower.tell("\n\r\n\r");
CMLib.commands().postLook(follower,true);
}
}
else
if((V.elementAt(v) instanceof Item)
&&(newRoom!=CMLib.map().roomLocation((Environmental)V.elementAt(v))))
newRoom.bringItemHere((Item)V.elementAt(v),CMProps.getIntVar(CMProps.SYSTEMI_EXPIRE_PLAYER_DROP),true);
if(V.elementAt(v)==scripted)
lastKnownLocation=newRoom;
}
}
}
break;
}
case 25: // mpbeacon
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
String roomName=tt[1];
Room newRoom=null;
if((roomName.length()>0)&&(lastKnownLocation!=null))
{
String beacon=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if(roomName.startsWith("$"))
newRoom=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(newRoom==null)
newRoom=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation);
if((newRoom!=null)&&(lastKnownLocation!=null))
{
Vector V=new Vector();
if(beacon.equalsIgnoreCase("all"))
{
for(int x=0;x<lastKnownLocation.numInhabitants();x++)
{
MOB m=lastKnownLocation.fetchInhabitant(x);
if((m!=null)&&(m!=monster)&&(!m.isMonster())&&(!V.contains(m)))
V.addElement(m);
}
}
else
{
MOB findOne=lastKnownLocation.fetchInhabitant(beacon);
if((findOne!=null)&&(findOne!=monster)&&(!findOne.isMonster()))
V.addElement(findOne);
}
for(int v=0;v<V.size();v++)
{
MOB follower=(MOB)V.elementAt(v);
if(!follower.isMonster())
follower.setStartRoom(newRoom);
}
}
}
break;
}
case 18: // mpforce
{
if(tt==null){
tt=parseBits(script,si,"Ccp");
if(tt==null) return null;
}
Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
String force=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
if(newTarget!=null)
{
DVector vscript=new DVector(2);
vscript.addElement("FUNCTION_PROG MPFORCE_"+System.currentTimeMillis()+Math.random(),null);
vscript.addElement(force,null);
// this can not be permanently parsed because it is variable
execute(newTarget, source, target, getMakeMOB(newTarget), primaryItem, secondaryItem, vscript, msg, tmp);
}
break;
}
case 20: // mpsetvar
{
if(tt==null){
tt=parseBits(script,si,"Cccr");
if(tt==null) return null;
}
String which=tt[1];
Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if(!which.equals("*"))
{
if(E==null)
which=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,which);
else
if(E instanceof Room)
which=CMLib.map().getExtendedRoomID((Room)E);
else
which=E.Name();
}
if((which.length()>0)&&(arg2.length()>0))
setVar(which,arg2,arg3);
break;
}
case 36: // mpsavevar
{
if(tt==null){
tt=parseBits(script,si,"CcR");
if(tt==null) return null;
}
String which=tt[1];
String arg2=tt[2];
Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
which=getVarHost(E,which,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp);
if((which.length()>0)&&(arg2.length()>0))
{
DVector V=getScriptVarSet(which,arg2);
for(int v=0;v<V.size();v++)
{
which=(String)V.elementAt(0,1);
arg2=((String)V.elementAt(0,2)).toUpperCase();
Hashtable H=(Hashtable)resources._getResource("SCRIPTVAR-"+which);
String val="";
if(H!=null)
{
val=(String)H.get(arg2);
if(val==null) val="";
}
if(val.length()>0)
CMLib.database().DBReCreateData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2,val);
else
CMLib.database().DBDeleteData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2);
}
}
break;
}
case 39: // mploadvar
{
if(tt==null){
tt=parseBits(script,si,"CcR");
if(tt==null) return null;
}
String which=tt[1];
String arg2=tt[2];
Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()>0)
{
Vector V=null;
which=getVarHost(E,which,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp);
if(arg2.equals("*"))
V=CMLib.database().DBReadData(which,"SCRIPTABLEVARS");
else
V=CMLib.database().DBReadData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2);
if((V!=null)&&(V.size()>0))
for(int v=0;v<V.size();v++)
{
DatabaseEngine.PlayerData VAR=(DatabaseEngine.PlayerData)V.elementAt(v);
String varName=VAR.key;
if(varName.startsWith(which.toUpperCase()+"_SCRIPTABLEVARS_"))
varName=varName.substring((which+"_SCRIPTABLEVARS_").length());
setVar(which,varName,VAR.xml);
}
}
break;
}
case 40: // MPM2I2M
{
if(tt==null){
tt=parseBits(script,si,"Cccr");
if(tt==null) return null;
}
String arg1=tt[1];
Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
{
String arg2=tt[2];
String arg3=tt[3];
CagedAnimal caged=(CagedAnimal)CMClass.getItem("GenCaged");
if(caged!=null)
{
((Item)caged).baseEnvStats().setAbility(1);
((Item)caged).recoverEnvStats();
}
if((caged!=null)&&caged.cageMe((MOB)E)&&(lastKnownLocation!=null))
{
if(arg2.length()>0) ((Item)caged).setName(arg2);
if(arg3.length()>0) ((Item)caged).setDisplayText(arg3);
lastKnownLocation.addItemRefuse((Item)caged,CMProps.getIntVar(CMProps.SYSTEMI_EXPIRE_PLAYER_DROP));
((MOB)E).killMeDead(false);
}
}
else
if(E instanceof CagedAnimal)
{
MOB M=((CagedAnimal)E).unCageMe();
if((M!=null)&&(lastKnownLocation!=null))
{
M.bringToLife(lastKnownLocation,true);
((Item)E).destroy();
}
}
else
logError(scripted,"MPM2I2M","RunTime",arg1+" is not a mob or a caged item.");
break;
}
case 28: // mpdamage
{
if(tt==null){
tt=parseBits(script,si,"Ccccr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]);
if((newTarget!=null)&&(arg2.length()>0))
{
if(newTarget instanceof MOB)
{
MOB deadM=(MOB)newTarget;
MOB killerM=(MOB)newTarget;
if(arg4.equalsIgnoreCase("MEKILL")||arg4.equalsIgnoreCase("ME"))
killerM=monster;
int min=CMath.s_int(arg2.trim());
int max=CMath.s_int(arg3.trim());
if(max<min) max=min;
if(min>0)
{
int dmg=(max==min)?min:CMLib.dice().roll(1,max-min,min);
if((dmg>=deadM.curState().getHitPoints())
&&(!arg4.equalsIgnoreCase("KILL"))
&&(!arg4.equalsIgnoreCase("MEKILL")))
dmg=deadM.curState().getHitPoints()-1;
if(dmg>0)
CMLib.combat().postDamage(killerM,deadM,null,dmg,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,-1,null);
}
}
else
if(newTarget instanceof Item)
{
Item E=(Item)newTarget;
int min=CMath.s_int(arg2.trim());
int max=CMath.s_int(arg3.trim());
if(max<min) max=min;
if(min>0)
{
int dmg=(max==min)?min:CMLib.dice().roll(1,max-min,min);
boolean destroy=false;
if(E.subjectToWearAndTear())
{
if((dmg>=E.usesRemaining())&&(!arg4.equalsIgnoreCase("kill")))
dmg=E.usesRemaining()-1;
if(dmg>0)
E.setUsesRemaining(E.usesRemaining()-dmg);
if(E.usesRemaining()<=0) destroy=true;
}
else
if(arg4.equalsIgnoreCase("kill"))
destroy=true;
if(destroy)
{
if(lastKnownLocation!=null)
lastKnownLocation.showHappens(CMMsg.MSG_OK_VISUAL,E.name()+" is destroyed!");
E.destroy();
}
}
}
}
break;
}
case 78: // mpheal
{
if(tt==null){
tt=parseBits(script,si,"Cccr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if((newTarget!=null)&&(arg2.length()>0))
{
if(newTarget instanceof MOB)
{
MOB healedM=(MOB)newTarget;
MOB healerM=(MOB)newTarget;
int min=CMath.s_int(arg2.trim());
int max=CMath.s_int(arg3.trim());
if(max<min) max=min;
if(min>0)
{
int amt=(max==min)?min:CMLib.dice().roll(1,max-min,min);
if(amt>0)
CMLib.combat().postHealing(healerM,healedM,null,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,amt,null);
}
}
else
if(newTarget instanceof Item)
{
Item E=(Item)newTarget;
int min=CMath.s_int(arg2.trim());
int max=CMath.s_int(arg3.trim());
if(max<min) max=min;
if(min>0)
{
int amt=(max==min)?min:CMLib.dice().roll(1,max-min,min);
if(E.subjectToWearAndTear())
{
E.setUsesRemaining(E.usesRemaining()+amt);
if(E.usesRemaining()>100) E.setUsesRemaining(100);
}
}
}
}
break;
}
case 29: // mptrackto
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
Ability A=CMClass.getAbility("Skill_Track");
if(A!=null)
{
altStatusTickable=A;
A.invoke(monster,CMParms.parse(arg1),null,true,0);
altStatusTickable=null;
}
break;
}
case 53: // mpwalkto
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
Ability A=CMClass.getAbility("Skill_Track");
if(A!=null)
{
altStatusTickable=A;
A.invoke(monster,CMParms.parse(arg1+" LANDONLY"),null,true,0);
altStatusTickable=null;
}
break;
}
case 21: //MPENDQUEST
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
String q=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim());
Quest Q=getQuest(q);
if(Q!=null)
Q.stopQuest();
else
if((tt[1].length()>0)&&(defaultQuestName!=null)&&(defaultQuestName.length()>0))
{
Environmental newTarget=getArgumentMOB(tt[1].trim(),source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(newTarget==null)
logError(scripted,"MPENDQUEST","Unknown","Quest or MOB: "+s);
else
{
for(int i=newTarget.numScripts()-1;i>=0;i--)
{
ScriptingEngine S=newTarget.fetchScript(i);
if((S!=null)
&&(S.defaultQuestName()!=null)
&&(S.defaultQuestName().equalsIgnoreCase(defaultQuestName)))
newTarget.delScript(S);
}
}
}
else
logError(scripted,"MPENDQUEST","Unknown","Quest: "+s);
break;
}
case 69: // MPSTEPQUEST
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
String qName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim());
Quest Q=getQuest(qName);
if(Q!=null) Q.stepQuest();
else
logError(scripted,"MPSTEPQUEST","Unknown","Quest: "+s);
break;
}
case 23: //MPSTARTQUEST
{
if(tt==null){
tt=parseBits(script,si,"Cr");
if(tt==null) return null;
}
String qName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim());
Quest Q=getQuest(qName);
if(Q!=null) Q.startQuest();
else
logError(scripted,"MPSTARTQUEST","Unknown","Quest: "+s);
break;
}
case 64: //MPLOADQUESTOBJ
{
if(tt==null){
tt=parseBits(script,si,"Cccr");
if(tt==null) return null;
}
String questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim());
Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"MPLOADQUESTOBJ","Unknown","Quest: "+questName);
break;
}
Object O=Q.getDesignatedObject(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
if(O==null)
{
logError(scripted,"MPLOADQUESTOBJ","Unknown","Unknown var "+tt[2]+" for Quest: "+questName);
break;
}
String varArg=tt[3];
if((varArg.length()!=2)||(!varArg.startsWith("$")))
{
logError(scripted,"MPLOADQUESTOBJ","Syntax","Invalid argument var: "+varArg+" for "+scripted.Name());
break;
}
char c=varArg.charAt(1);
if(Character.isDigit(c))
tmp[CMath.s_int(Character.toString(c))]=O;
else
switch(c)
{
case 'N':
case 'n': if(O instanceof MOB) source=(MOB)O; break;
case 'I':
case 'i': if(O instanceof Environmental) scripted=(Environmental)O;
if(O instanceof MOB) monster=(MOB)O;
break;
case 'B':
case 'b': if(O instanceof Environmental)
lastLoaded=(Environmental)O;
break;
case 'T':
case 't': if(O instanceof Environmental) target=(Environmental)O; break;
case 'O':
case 'o': if(O instanceof Item) primaryItem=(Item)O; break;
case 'P':
case 'p': if(O instanceof Item) secondaryItem=(Item)O; break;
case 'd':
case 'D': if(O instanceof Room) lastKnownLocation=(Room)O; break;
default:
logError(scripted,"MPLOADQUESTOBJ","Syntax","Invalid argument var: "+varArg+" for "+scripted.Name());
break;
}
break;
}
case 22: //MPQUESTWIN
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
String whoName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
MOB M=null;
if(lastKnownLocation!=null)
M=lastKnownLocation.fetchInhabitant(whoName);
if(M==null) M=CMLib.players().getPlayer(whoName);
if(M!=null) whoName=M.Name();
if(whoName.length()>0)
{
Quest Q=getQuest(tt[2]);
if(Q!=null)
Q.declareWinner(whoName);
else
logError(scripted,"MPQUESTWIN","Unknown","Quest: "+s);
}
break;
}
case 24: // MPCALLFUNC
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
String named=tt[1];
String parms=tt[2].trim();
boolean found=false;
Vector scripts=getScripts();
for(int v=0;v<scripts.size();v++)
{
DVector script2=(DVector)scripts.elementAt(v);
if(script2.size()<1) continue;
String trigger=((String)script2.elementAt(0,1)).toUpperCase().trim();
String[] ttrigger=(String[])script2.elementAt(0,2);
if(getTriggerCode(trigger,ttrigger)==17)
{
String fnamed=CMParms.getCleanBit(trigger,1);
if(fnamed.equalsIgnoreCase(named))
{
found=true;
execute(scripted,
source,
target,
monster,
primaryItem,
secondaryItem,
script2,
varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,parms),
tmp);
break;
}
}
}
if(!found)
logError(scripted,"MPCALLFUNC","Unknown","Function: "+named);
break;
}
case 27: // MPWHILE
{
if(tt==null)
{
Vector V=new Vector();
V.addElement("MPWHILE");
String conditionStr=(s.substring(7).trim());
if(!conditionStr.startsWith("("))
{
logError(scripted,"MPWHILE","Syntax"," NO Starting (: "+s);
break;
}
conditionStr=conditionStr.substring(1).trim();
int x=-1;
int depth=0;
for(int i=0;i<conditionStr.length();i++)
if(conditionStr.charAt(i)=='(')
depth++;
else
if((conditionStr.charAt(i)==')')&&((--depth)<0))
{
x=i;
break;
}
if(x<0)
{
logError(scripted,"MPWHILE","Syntax"," no closing ')': "+s);
break;
}
String DO=conditionStr.substring(x+1).trim();
conditionStr=conditionStr.substring(0,x);
try {
String[] EVAL=parseEval(conditionStr);
V.addElement("(");
Vector V2=CMParms.makeVector(EVAL);
V.addAll(V2);
V.addElement(")");
V.addElement(DO);
tt=CMParms.toStringArray(V);
script.setElementAt(si,2,tt);
} catch(Exception e) {
logError(scripted,"MPWHILE","Syntax",e.getMessage());
break;
}
if(tt==null) return null;
}
int evalEnd=2;
int depth=0;
while((evalEnd<tt.length)&&((!tt[evalEnd].equals(")"))||(depth>0)))
{
if(tt[evalEnd].equals("("))
depth++;
else
if(tt[evalEnd].equals(")"))
depth--;
evalEnd++;
}
if(evalEnd==tt.length)
{
logError(scripted,"MPWHILE","Syntax"," no closing ')': "+s);
break;
}
String[] EVAL=new String[evalEnd-2];
for(int y=2;y<evalEnd;y++)
EVAL[y-2]=tt[y];
String DO=tt[evalEnd+1];
String[] DOT=null;
int doLen=(tt.length-evalEnd)-1;
if(doLen>1)
{
DOT=new String[doLen];
for(int y=0;y<DOT.length;y++)
{
DOT[y]=tt[evalEnd+y+1];
if(y>0) DO+=" "+tt[evalEnd+y+1];
}
}
String[][] EVALO={EVAL};
DVector vscript=new DVector(2);
vscript.addElement("FUNCTION_PROG MPWHILE_"+Math.random(),null);
vscript.addElement(DO,DOT);
long time=System.currentTimeMillis();
while((eval(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,EVALO,0))&&((System.currentTimeMillis()-time)<4000))
execute(scripted,source,target,monster,primaryItem,secondaryItem,vscript,msg,tmp);
if(vscript.elementAt(1,2)!=DOT)
{
int oldDotLen=(DOT==null)?1:DOT.length;
String[] newDOT=(String[])vscript.elementAt(1,2);
String[] newTT=new String[tt.length-oldDotLen+newDOT.length];
int end=0;
for(end=0;end<tt.length-oldDotLen;end++)
newTT[end]=tt[end];
for(int y=0;y<newDOT.length;y++)
newTT[end+y]=newDOT[y];
tt=newTT;
script.setElementAt(si,2,tt);
}
if(EVALO[0]!=EVAL)
{
Vector lazyV=new Vector();
lazyV.addElement("MPWHILE");
lazyV.addElement("(");
String[] newEVAL=EVALO[0];
for(int y=0;y<newEVAL.length;y++)
lazyV.addElement(newEVAL[y]);
for(int i=evalEnd;i<tt.length;i++)
lazyV.addElement(tt[i]);
tt=CMParms.toStringArray(lazyV);
script.setElementAt(si,2,tt);
}
if((System.currentTimeMillis()-time)>=4000)
{
logError(scripted,"MPWHILE","RunTime","4 second limit exceeded: "+s);
break;
}
break;
}
case 26: // MPALARM
{
if(tt==null){
tt=parseBits(script,si,"Ccp");
if(tt==null) return null;
}
String time=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
String parms=tt[2].trim();
if(CMath.s_int(time.trim())<=0)
{
logError(scripted,"MPALARM","Syntax","Bad time "+time);
break;
}
if(parms.length()==0)
{
logError(scripted,"MPALARM","Syntax","No command!");
break;
}
DVector vscript=new DVector(2);
vscript.addElement("FUNCTION_PROG ALARM_"+time+Math.random(),null);
vscript.addElement(parms,null);
prequeResponse(scripted,source,target,monster,primaryItem,secondaryItem,vscript,CMath.s_int(time.trim()),msg);
break;
}
case 37: // mpenable
{
if(tt==null){
tt=parseBits(script,si,"Ccccp");
if(tt==null) return null;
}
Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
String p2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]);
Ability A=null;
if(cast!=null)
{
if(newTarget instanceof MOB) A=((MOB)newTarget).fetchAbility(cast);
if(A==null) A=CMClass.getAbility(cast);
if(A==null)
{
ExpertiseLibrary.ExpertiseDefinition D=CMLib.expertises().findDefinition(cast,false);
if(D==null)
logError(scripted,"MPENABLE","Syntax","Unknown skill/expertise: "+cast);
else
if((newTarget!=null)&&(newTarget instanceof MOB))
((MOB)newTarget).addExpertise(D.ID);
}
}
if((newTarget!=null)
&&(A!=null)
&&(newTarget instanceof MOB))
{
if(!((MOB)newTarget).isMonster())
Log.sysOut("Scripting",newTarget.Name()+" was MPENABLED with "+A.Name());
if(p2.trim().startsWith("++"))
p2=""+(CMath.s_int(p2.trim().substring(2))+A.proficiency());
else
if(p2.trim().startsWith("--"))
p2=""+(A.proficiency()-CMath.s_int(p2.trim().substring(2)));
A.setProficiency(CMath.s_int(p2.trim()));
A.setMiscText(m2);
if(((MOB)newTarget).fetchAbility(A.ID())==null)
((MOB)newTarget).addAbility(A);
}
break;
}
case 38: // mpdisable
{
if(tt==null){
tt=parseBits(script,si,"Ccr");
if(tt==null) return null;
}
Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if((newTarget!=null)&&(newTarget instanceof MOB))
{
Ability A=((MOB)newTarget).findAbility(cast);
if(A!=null)((MOB)newTarget).delAbility(A);
if((!((MOB)newTarget).isMonster())&&(A!=null))
Log.sysOut("Scripting",newTarget.Name()+" was MPDISABLED with "+A.Name());
ExpertiseLibrary.ExpertiseDefinition D=CMLib.expertises().findDefinition(cast,false);
if((newTarget instanceof MOB)&&(D!=null))
((MOB)newTarget).delExpertise(D.ID);
}
break;
}
default:
if(cmd.length()>0)
{
Vector V=CMParms.parse(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s));
if((V.size()>0)&&(monster!=null))
monster.doCommand(V,Command.METAFLAG_MPFORCED);
}
break;
}
}
tickStatus=Tickable.STATUS_END;
return null;
}
protected static final Vector empty=new Vector();
protected Vector getScripts()
{
if(CMSecurity.isDisabled("SCRIPTABLE")||CMSecurity.isDisabled("SCRIPTING"))
return empty;
Vector scripts=null;
if(getScript().length()>100)
scripts=(Vector)Resources.getResource("PARSEDPRG: "+getScript().substring(0,100)+getScript().length()+getScript().hashCode());
else
scripts=(Vector)Resources.getResource("PARSEDPRG: "+getScript());
if(scripts==null)
{
String scr=getScript();
scr=CMStrings.replaceAll(scr,"`","'");
scripts=parseScripts(scr);
if(getScript().length()>100)
Resources.submitResource("PARSEDPRG: "+getScript().substring(0,100)+getScript().length()+getScript().hashCode(),scripts);
else
Resources.submitResource("PARSEDPRG: "+getScript(),scripts);
}
return scripts;
}
protected boolean match(String str, String patt)
{
if(patt.trim().equalsIgnoreCase("ALL"))
return true;
if(patt.length()==0)
return true;
if(str.length()==0)
return false;
if(str.equalsIgnoreCase(patt))
return true;
return false;
}
private Item makeCheapItem(Environmental E)
{
Item product=null;
if(E instanceof Item)
product=(Item)E;
else
{
product=CMClass.getItem("StdItem");
product.setName(E.Name());
product.setDisplayText(E.displayText());
product.setDescription(E.description());
product.setBaseEnvStats((EnvStats)E.baseEnvStats().copyOf());
product.recoverEnvStats();
}
return product;
}
public boolean okMessage(Environmental affecting, CMMsg msg)
{
if((affecting==null)||(msg.source()==null))
return true;
Vector scripts=getScripts();
DVector script=null;
boolean tryIt=false;
String trigger=null;
String[] t=null;
int triggerCode=0;
String str=null;
for(int v=0;v<scripts.size();v++)
{
tryIt=false;
script=(DVector)scripts.elementAt(v);
if(script.size()<1) continue;
trigger=((String)script.elementAt(0,1)).toUpperCase().trim();
t=(String[])script.elementAt(0,2);
triggerCode=getTriggerCode(trigger,t);
switch(triggerCode)
{
case 42: // cnclmsg_prog
if(canTrigger(42))
{
if(t==null) t=parseBits(script,0,"CCT");
String command=t[1];
boolean chk=false;
int x=command.indexOf('=');
if(x>0)
{
chk=true;
for(int i=0;i<x;i++)
switch(command.charAt(i)) {
case 'S': chk=chk&&msg.isSource(command.substring(x+1)); break;
case 'T': chk=chk&&msg.isTarget(command.substring(x+1)); break;
case 'O': chk=chk&&msg.isOthers(command.substring(x+1)); break;
default: chk=false; break;
}
}
else
chk=msg.isSource(command)||msg.isTarget(command)||msg.isOthers(command);
if(chk)
{
str="";
if((msg.source().session()!=null)&&(msg.source().session().previousCMD()!=null))
str=" "+CMParms.combine(msg.source().session().previousCMD(),0).toUpperCase()+" ";
if((t[2].length()==0)||(t[2].equals("ALL")))
tryIt=true;
else
if((t[2].equals("P"))&&(t.length>3))
{
if(match(str.trim(),t[3]))
tryIt=true;
}
else
for(int i=2;i<t.length;i++)
{
if(str.indexOf(" "+t[i]+" ")>=0)
{
str=(t[i].trim()+" "+str.trim()).trim();
tryIt=true;
break;
}
}
}
}
break;
}
if(tryIt)
{
MOB monster=getMakeMOB(affecting);
if(lastKnownLocation==null) lastKnownLocation=msg.source().location();
if((monster==null)||(monster.amDead())||(lastKnownLocation==null)) return true;
Item defaultItem=(affecting instanceof Item)?(Item)affecting:null;
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null) Tool=defaultItem;
String resp=null;
if(msg.target() instanceof MOB)
resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,newObjs());
else
if(msg.target() instanceof Item)
resp=execute(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,str,newObjs());
else
resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,newObjs());
if((resp!=null)&&(resp.equalsIgnoreCase("CANCEL")))
return false;
}
}
return true;
}
protected String standardTriggerCheck(DVector script, String[] t, Environmental E) {
if(E==null) return null;
if(t==null) t=parseBits(script,0,"CT");
String NAME=E.Name().toUpperCase();
if((t[1].length()==0)
||(t[1].equals("ALL"))
||(t[1].equals("P")
&&(t.length>2)
&&((t[2].indexOf(NAME)>=0)
||(E.ID().equalsIgnoreCase(t[2]))
||(t[2].equalsIgnoreCase("ALL")))))
return t[1];
for(int i=1;i<t.length;i++)
{
if(((" "+NAME+" ").indexOf(" "+t[i]+" ")>=0)
||(E.ID().equalsIgnoreCase(t[i]))
||(t[i].equalsIgnoreCase("ALL")))
return t[i];
}
return null;
}
public void executeMsg(Environmental affecting, CMMsg msg)
{
if((affecting==null)||(msg.source()==null))
return;
MOB monster=getMakeMOB(affecting);
if(lastKnownLocation==null) lastKnownLocation=msg.source().location();
if((monster==null)||(monster.amDead())||(lastKnownLocation==null)) return;
Item defaultItem=(affecting instanceof Item)?(Item)affecting:null;
MOB eventMob=monster;
if((defaultItem!=null)&&(defaultItem.owner() instanceof MOB))
eventMob=(MOB)defaultItem.owner();
Vector scripts=getScripts();
if(msg.amITarget(eventMob)
&&(!msg.amISource(monster))
&&(msg.targetMinor()==CMMsg.TYP_DAMAGE)
&&(msg.source()!=monster))
lastToHurtMe=msg.source();
DVector script=null;
String trigger=null;
String[] t=null;
for(int v=0;v<scripts.size();v++)
{
script=(DVector)scripts.elementAt(v);
if(script.size()<1) continue;
trigger=((String)script.elementAt(0,1)).toUpperCase().trim();
t=(String[])script.elementAt(0,2);
int triggerCode=getTriggerCode(trigger,t);
int targetMinorTrigger=-1;
switch(triggerCode)
{
case 1: // greet_prog
if((msg.targetMinor()==CMMsg.TYP_ENTER)
&&(msg.amITarget(lastKnownLocation))
&&(!msg.amISource(eventMob))
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))
&&canTrigger(1)
&&((!(affecting instanceof MOB))||CMLib.flags().canSenseMoving(msg.source(),(MOB)affecting)))
{
if(t==null) t=parseBits(script,0,"CR");
int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null);
return;
}
}
break;
case 2: // all_greet_prog
if((msg.targetMinor()==CMMsg.TYP_ENTER)&&canTrigger(2)
&&(msg.amITarget(lastKnownLocation))
&&(!msg.amISource(eventMob))
&&(canActAtAll(monster)))
{
if(t==null) t=parseBits(script,0,"CR");
int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null);
return;
}
}
break;
case 3: // speech_prog
if(((msg.sourceMinor()==CMMsg.TYP_SPEAK)||(msg.targetMinor()==CMMsg.TYP_SPEAK))&&canTrigger(3)
&&(!msg.amISource(monster))
&&(!CMath.bset(msg.othersMajor(),CMMsg.MASK_CHANNEL))
&&(((msg.othersMessage()!=null)&&((msg.tool()==null)||(!(msg.tool() instanceof Ability))||((((Ability)msg.tool()).classificationCode()&Ability.ALL_ACODES)!=Ability.ACODE_LANGUAGE)))
||((msg.target()==monster)&&(msg.targetMessage()!=null)&&(msg.tool()==null)))
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))))
{
if(t==null) t=parseBits(script,0,"CT");
String str=null;
if(msg.othersMessage()!=null)
str=CMStrings.replaceAll(CMStrings.getSayFromMessage(msg.othersMessage().toUpperCase()),"`","'");
else
str=CMStrings.replaceAll(CMStrings.getSayFromMessage(msg.targetMessage().toUpperCase()),"`","'");
str=(" "+str+" ").toUpperCase();
str=CMStrings.removeColors(str);
str=CMStrings.replaceAll(str,"\n\r"," ");
if((t[1].length()==0)||(t[1].equals("ALL")))
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str);
return;
}
else
if((t[1].equals("P"))&&(t.length>2))
{
if(match(str.trim(),t[2]))
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str);
return;
}
}
else
for(int i=1;i<t.length;i++)
{
int x=str.indexOf(" "+t[i]+" ");
if(x>=0)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str.substring(x).trim());
return;
}
}
}
break;
case 4: // give_prog
if((msg.targetMinor()==CMMsg.TYP_GIVE)
&&canTrigger(4)
&&((msg.amITarget(monster))
||(msg.tool()==affecting)
||(affecting instanceof Room)
||(affecting instanceof Area))
&&(!msg.amISource(monster))
&&(msg.tool() instanceof Item)
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))))
{
String check=standardTriggerCheck(script,t,msg.tool());
if(check!=null)
{
if(lastMsg==msg) break;
lastMsg=msg;
enqueResponse(affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,script,1,check);
return;
}
}
break;
case 40: // llook_prog
if((msg.targetMinor()==CMMsg.TYP_EXAMINE)&&canTrigger(40)
&&(!msg.amISource(monster))
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))))
{
String check=standardTriggerCheck(script,t,msg.target());
if(check!=null)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check);
return;
}
}
break;
case 41: // execmsg_prog
if(canTrigger(41))
{
if(t==null) t=parseBits(script,0,"CCT");
String command=t[1];
boolean chk=false;
int x=command.indexOf('=');
if(x>0)
{
chk=true;
for(int i=0;i<x;i++)
switch(command.charAt(i)) {
case 'S': chk=chk&&msg.isSource(command.substring(x+1)); break;
case 'T': chk=chk&&msg.isTarget(command.substring(x+1)); break;
case 'O': chk=chk&&msg.isOthers(command.substring(x+1)); break;
default: chk=false; break;
}
}
else
chk=msg.isSource(command)||msg.isTarget(command)||msg.isOthers(command);
if(chk)
{
String str="";
if((msg.source().session()!=null)&&(msg.source().session().previousCMD()!=null))
str=" "+CMParms.combine(msg.source().session().previousCMD(),0).toUpperCase()+" ";
boolean doIt=false;
if((t[2].length()==0)||(t[2].equals("ALL")))
doIt=true;
else
if((t[2].equals("P"))&&(t.length>3))
{
if(match(str.trim(),t[3]))
doIt=true;
}
else
for(int i=2;i<t.length;i++)
{
if(str.indexOf(" "+t[i]+" ")>=0)
{
str=(t[i].trim()+" "+str.trim()).trim();
doIt=true;
break;
}
}
if(doIt)
{
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null) Tool=defaultItem;
if(msg.target() instanceof MOB)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str);
else
if(msg.target() instanceof Item)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str);
else
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str);
return;
}
}
}
break;
case 39: // look_prog
if((msg.targetMinor()==CMMsg.TYP_LOOK)&&canTrigger(39)
&&(!msg.amISource(monster))
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))))
{
String check=standardTriggerCheck(script,t,msg.target());
if(check!=null)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,defaultItem,script,1,check);
return;
}
}
break;
case 20: // get_prog
if((msg.targetMinor()==CMMsg.TYP_GET)&&canTrigger(20)
&&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB))
&&(!msg.amISource(monster))
&&(msg.target() instanceof Item)
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))))
{
String check=standardTriggerCheck(script,t,msg.target());
if(check!=null)
{
if(lastMsg==msg) break;
lastMsg=msg;
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check);
return;
}
}
break;
case 22: // drop_prog
if((msg.targetMinor()==CMMsg.TYP_DROP)&&canTrigger(22)
&&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB))
&&(!msg.amISource(monster))
&&(msg.target() instanceof Item)
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))))
{
String check=standardTriggerCheck(script,t,msg.target());
if(check!=null)
{
if(lastMsg==msg) break;
lastMsg=msg;
if(msg.target() instanceof Coins)
execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs());
else
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check);
return;
}
}
break;
case 24: // remove_prog
if((msg.targetMinor()==CMMsg.TYP_REMOVE)&&canTrigger(24)
&&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB))
&&(!msg.amISource(monster))
&&(msg.target() instanceof Item)
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))))
{
String check=standardTriggerCheck(script,t,msg.target());
if(check!=null)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check);
return;
}
}
break;
case 34: // open_prog
if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_OPEN;
case 35: // close_prog
if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_CLOSE;
case 36: // lock_prog
if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_LOCK;
case 37: // unlock_prog
{
if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_UNLOCK;
if((msg.targetMinor()==targetMinorTrigger)&&canTrigger(triggerCode)
&&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB))
&&(!msg.amISource(monster))
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))))
{
Item I=(msg.target() instanceof Item)?(Item)msg.target():defaultItem;
String check=standardTriggerCheck(script,t,msg.target());
if(check!=null)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,I,defaultItem,script,1,check);
return;
}
}
break;
}
case 25: // consume_prog
if(((msg.targetMinor()==CMMsg.TYP_EAT)||(msg.targetMinor()==CMMsg.TYP_DRINK))
&&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB))
&&(!msg.amISource(monster))&&canTrigger(25)
&&(msg.target() instanceof Item)
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))))
{
String check=standardTriggerCheck(script,t,msg.target());
if(check!=null)
{
if((msg.target() == affecting)
&&(affecting instanceof Food))
execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs());
else
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check);
return;
}
}
break;
case 21: // put_prog
if((msg.targetMinor()==CMMsg.TYP_PUT)&&canTrigger(21)
&&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB))
&&(msg.tool() instanceof Item)
&&(!msg.amISource(monster))
&&(msg.target() instanceof Item)
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))))
{
String check=standardTriggerCheck(script,t,msg.target());
if(check!=null)
{
if(lastMsg==msg) break;
lastMsg=msg;
if((msg.tool() instanceof Coins)&&(((Item)msg.target()).owner() instanceof Room))
execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs());
else
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),script,1,check);
return;
}
}
break;
case 27: // buy_prog
if((msg.targetMinor()==CMMsg.TYP_BUY)&&canTrigger(27)
&&((!(affecting instanceof ShopKeeper))
||msg.amITarget(affecting))
&&(!msg.amISource(monster))
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))))
{
String check=standardTriggerCheck(script,t,msg.tool());
if(check!=null)
{
Item product=makeCheapItem(msg.tool());
if((product instanceof Coins)
&&(product.owner() instanceof Room))
execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,check,newObjs());
else
enqueResponse(affecting,msg.source(),monster,monster,product,product,script,1,check);
return;
}
}
break;
case 28: // sell_prog
if((msg.targetMinor()==CMMsg.TYP_SELL)&&canTrigger(28)
&&((msg.amITarget(affecting))||(!(affecting instanceof ShopKeeper)))
&&(!msg.amISource(monster))
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))))
{
String check=standardTriggerCheck(script,t,msg.tool());
if(check!=null)
{
Item product=makeCheapItem(msg.tool());
if((product instanceof Coins)
&&(product.owner() instanceof Room))
execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,newObjs());
else
enqueResponse(affecting,msg.source(),monster,monster,product,product,script,1,check);
return;
}
}
break;
case 23: // wear_prog
if(((msg.targetMinor()==CMMsg.TYP_WEAR)
||(msg.targetMinor()==CMMsg.TYP_HOLD)
||(msg.targetMinor()==CMMsg.TYP_WIELD))
&&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB))
&&(!msg.amISource(monster))&&canTrigger(23)
&&(msg.target() instanceof Item)
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))))
{
String check=standardTriggerCheck(script,t,msg.target());
if(check!=null)
{
enqueResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,check);
return;
}
}
break;
case 19: // bribe_prog
if((msg.targetMinor()==CMMsg.TYP_GIVE)
&&(msg.amITarget(eventMob)||(!(affecting instanceof MOB)))
&&(!msg.amISource(monster))&&canTrigger(19)
&&(msg.tool() instanceof Coins)
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))))
{
if(t==null) t=parseBits(script,0,"CR");
if(t[1].startsWith("ANY")||t[1].startsWith("ALL"))
t[1]=t[1].trim();
else
if(!((Coins)msg.tool()).getCurrency().equals(CMLib.beanCounter().getCurrency(monster)))
break;
double d=0.0;
if(CMath.isDouble(t[1]))
d=CMath.s_double(t[1]);
else
d=(double)CMath.s_int(t[1]);
if((((Coins)msg.tool()).getTotalValue()>=d)
||(t[1].equals("ALL"))
||(t[1].equals("ANY")))
{
enqueResponse(affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,script,1,null);
return;
}
}
break;
case 8: // entry_prog
if((msg.targetMinor()==CMMsg.TYP_ENTER)&&canTrigger(8)
&&(msg.amISource(eventMob)
||(msg.target()==affecting)
||(msg.tool()==affecting)
||(affecting instanceof Item))
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))))
{
if(t==null) t=parseBits(script,0,"CR");
int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
Vector V=(Vector)que.clone();
ScriptableResponse SB=null;
String roomID=null;
if(msg.target()!=null)
roomID=CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(msg.target()));
for(int q=0;q<V.size();q++)
{
SB=(ScriptableResponse)V.elementAt(q);
if((SB.scr==script)&&(SB.s==msg.source()))
{
if(que.removeElement(SB))
execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,newObjs());
break;
}
}
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,roomID);
return;
}
}
break;
case 9: // exit prog
if((msg.targetMinor()==CMMsg.TYP_LEAVE)&&canTrigger(9)
&&(msg.amITarget(lastKnownLocation))
&&(!msg.amISource(eventMob))
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))))
{
if(t==null) t=parseBits(script,0,"CR");
int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
Vector V=(Vector)que.clone();
ScriptableResponse SB=null;
String roomID=null;
if(msg.target()!=null)
roomID=CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(msg.target()));
for(int q=0;q<V.size();q++)
{
SB=(ScriptableResponse)V.elementAt(q);
if((SB.scr==script)&&(SB.s==msg.source()))
{
if(que.removeElement(SB))
execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,newObjs());
break;
}
}
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,roomID);
return;
}
}
break;
case 10: // death prog
if((msg.sourceMinor()==CMMsg.TYP_DEATH)&&canTrigger(10)
&&(msg.amISource(eventMob)||(!(affecting instanceof MOB))))
{
if(t==null) t=parseBits(script,0,"C");
MOB ded=msg.source();
MOB src=lastToHurtMe;
if(msg.tool() instanceof MOB)
src=(MOB)msg.tool();
if((src==null)||(src.location()!=monster.location()))
src=ded;
execute(affecting,src,ded,ded,defaultItem,null,script,null,newObjs());
return;
}
break;
case 44: // kill prog
if((msg.sourceMinor()==CMMsg.TYP_DEATH)&&canTrigger(44)
&&((msg.tool()==affecting)||(!(affecting instanceof MOB))))
{
if(t==null) t=parseBits(script,0,"C");
MOB ded=msg.source();
MOB src=lastToHurtMe;
if(msg.tool() instanceof MOB)
src=(MOB)msg.tool();
if((src==null)||(src.location()!=monster.location()))
src=ded;
execute(affecting,src,ded,ded,defaultItem,null,script,null,newObjs());
return;
}
break;
case 26: // damage prog
if((msg.targetMinor()==CMMsg.TYP_DAMAGE)&&canTrigger(26)
&&(msg.amITarget(eventMob)||(msg.tool()==affecting)))
{
if(t==null) t=parseBits(script,0,"C");
Item I=null;
if(msg.tool() instanceof Item)
I=(Item)msg.tool();
execute(affecting,msg.source(),msg.target(),eventMob,defaultItem,I,script,""+msg.value(),newObjs());
return;
}
break;
case 29: // login_prog
if(!registeredSpecialEvents.contains(Integer.valueOf(CMMsg.TYP_LOGIN)))
{
CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_LOGIN);
registeredSpecialEvents.add(Integer.valueOf(CMMsg.TYP_LOGIN));
}
if((msg.sourceMinor()==CMMsg.TYP_LOGIN)&&canTrigger(29)
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))
&&(!CMLib.flags().isCloaked(msg.source())))
{
if(t==null) t=parseBits(script,0,"CR");
int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null);
return;
}
}
break;
case 32: // level_prog
if(!registeredSpecialEvents.contains(Integer.valueOf(CMMsg.TYP_LEVEL)))
{
CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_LEVEL);
registeredSpecialEvents.add(Integer.valueOf(CMMsg.TYP_LEVEL));
}
if((msg.sourceMinor()==CMMsg.TYP_LEVEL)&&canTrigger(32)
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))
&&(!CMLib.flags().isCloaked(msg.source())))
{
if(t==null) t=parseBits(script,0,"CR");
int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null);
return;
}
}
break;
case 30: // logoff_prog
if((msg.sourceMinor()==CMMsg.TYP_QUIT)&&canTrigger(30)
&&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))
&&(!CMLib.flags().isCloaked(msg.source())))
{
if(t==null) t=parseBits(script,0,"CR");
int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null);
return;
}
}
break;
case 12: // mask_prog
if(!canTrigger(12))
break;
case 18: // act_prog
if((msg.amISource(monster))
||((triggerCode==18)&&(!canTrigger(18))))
break;
case 43: // imask_prog
if((triggerCode!=43)||(msg.amISource(monster)&&canTrigger(43)))
{
if(t==null)
{
t=parseBits(script,0,"CT");
for(int i=0;i<t.length;i++)
t[i]=CMLib.english().stripPunctuation(CMStrings.removeColors(t[i]));
}
boolean doIt=false;
String str=msg.othersMessage();
if(str==null) str=msg.targetMessage();
if(str==null) str=msg.sourceMessage();
if(str==null) break;
str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false);
str=CMLib.english().stripPunctuation(CMStrings.removeColors(str));
str=" "+CMStrings.replaceAll(str,"\n\r"," ").toUpperCase().trim()+" ";
if((t[1].length()==0)||(t[1].equals("ALL")))
doIt=true;
else
if((t[1].equals("P"))&&(t.length>2))
{
if(match(str.trim(),t[2]))
doIt=true;
}
else
for(int i=1;i<t.length;i++)
if(str.indexOf(" "+t[i]+" ")>=0)
{
str=t[i];
doIt=true;
break;
}
if(doIt)
{
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null) Tool=defaultItem;
if(msg.target() instanceof MOB)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str);
else
if(msg.target() instanceof Item)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str);
else
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str);
return;
}
}
break;
case 38: // social prog
if(!msg.amISource(monster)
&&canTrigger(38)
&&(msg.tool() instanceof Social))
{
if(t==null) t=parseBits(script,0,"CR");
if(((Social)msg.tool()).Name().toUpperCase().startsWith(t[1]))
{
Item Tool=defaultItem;
if(msg.target() instanceof MOB)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,msg.tool().Name());
else
if(msg.target() instanceof Item)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,msg.tool().Name());
else
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,msg.tool().Name());
return;
}
}
break;
case 33: // channel prog
if(!registeredSpecialEvents.contains(Integer.valueOf(CMMsg.TYP_CHANNEL)))
{
CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_CHANNEL);
registeredSpecialEvents.add(Integer.valueOf(CMMsg.TYP_CHANNEL));
}
if(!msg.amISource(monster)
&&(CMath.bset(msg.othersMajor(),CMMsg.MASK_CHANNEL))
&&canTrigger(33))
{
if(t==null) t=parseBits(script,0,"CCT");
boolean doIt=false;
String channel=t[1];
int channelInt=msg.othersMinor()-CMMsg.TYP_CHANNEL;
String str=null;
if(channel.equalsIgnoreCase(CMLib.channels().getChannelName(channelInt)))
{
str=msg.sourceMessage();
if(str==null) str=msg.othersMessage();
if(str==null) str=msg.targetMessage();
if(str==null) break;
str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false).toUpperCase().trim();
int dex=str.indexOf("["+channel+"]");
if(dex>0)
str=str.substring(dex+2+channel.length()).trim();
else
{
dex=str.indexOf("'");
int edex=str.lastIndexOf("'");
if(edex>dex) str=str.substring(dex+1,edex);
}
str=" "+CMStrings.removeColors(str)+" ";
str=CMStrings.replaceAll(str,"\n\r"," ");
if((t[2].length()==0)||(t[2].equals("ALL")))
doIt=true;
else
if(t[2].equals("P")&&(t.length>2))
{
if(match(str.trim(),t[3]))
doIt=true;
}
else
for(int i=2;i<t.length;i++)
if(str.indexOf(" "+t[i]+" ")>=0)
{
str=t[i];
doIt=true;
break;
}
}
if(doIt)
{
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null) Tool=defaultItem;
if(msg.target() instanceof MOB)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str);
else
if(msg.target() instanceof Item)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str);
else
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str);
return;
}
}
break;
case 31: // regmask prog
if(!msg.amISource(monster)&&canTrigger(31))
{
boolean doIt=false;
String str=msg.othersMessage();
if(str==null) str=msg.targetMessage();
if(str==null) str=msg.sourceMessage();
if(str==null) break;
str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false);
if(t==null) t=parseBits(script,0,"Cp");
if(CMParms.getCleanBit(t[1],0).equalsIgnoreCase("p"))
doIt=str.trim().equals(t[1].substring(1).trim());
else
{
Pattern P=(Pattern)patterns.get(t[1]);
if(P==null)
{
P=Pattern.compile(t[1], Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
patterns.put(t[1],P);
}
Matcher M=P.matcher(str);
doIt=M.find();
if(doIt) str=str.substring(M.start()).trim();
}
if(doIt)
{
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null) Tool=defaultItem;
if(msg.target() instanceof MOB)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str);
else
if(msg.target() instanceof Item)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str);
else
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str);
return;
}
}
break;
}
}
}
protected int getTriggerCode(String trigger, String[] ttrigger)
{
Integer I=null;
if((ttrigger!=null)&&(ttrigger.length>0))
I=(Integer)progH.get(ttrigger[0]);
else
{
int x=trigger.indexOf(" ");
if(x<0)
I=(Integer)progH.get(trigger.toUpperCase().trim());
else
I=(Integer)progH.get(trigger.substring(0,x).toUpperCase().trim());
}
if(I==null) return 0;
return I.intValue();
}
public MOB getMakeMOB(Tickable ticking)
{
MOB mob=null;
if(ticking instanceof MOB)
{
mob=(MOB)ticking;
if(!mob.amDead())
lastKnownLocation=mob.location();
}
else
if(ticking instanceof Environmental)
{
Room R=CMLib.map().roomLocation((Environmental)ticking);
if(R!=null) lastKnownLocation=R;
if((backupMOB==null)
||(backupMOB.amDestroyed())
||(backupMOB.amDead()))
{
backupMOB=CMClass.getMOB("StdMOB");
if(backupMOB!=null)
{
backupMOB.setName(ticking.name());
backupMOB.setDisplayText(ticking.name()+" is here.");
backupMOB.setDescription("");
backupMOB.setAgeHours(-1);
mob=backupMOB;
if(backupMOB.location()!=lastKnownLocation)
backupMOB.setLocation(lastKnownLocation);
}
}
else
{
backupMOB.setAgeHours(-1);
mob=backupMOB;
if(backupMOB.location()!=lastKnownLocation)
{
backupMOB.setLocation(lastKnownLocation);
backupMOB.setName(ticking.name());
backupMOB.setDisplayText(ticking.name()+" is here.");
}
}
}
return mob;
}
protected boolean canTrigger(int triggerCode)
{
Long L=(Long)noTrigger.get(Integer.valueOf(triggerCode));
if(L==null) return true;
if(System.currentTimeMillis()<L.longValue())
return false;
noTrigger.remove(Integer.valueOf(triggerCode));
return true;
}
public boolean tick(Tickable ticking, int tickID)
{
MOB mob=getMakeMOB(ticking);
Item defaultItem=(ticking instanceof Item)?(Item)ticking:null;
if((mob==null)||(lastKnownLocation==null))
{
altStatusTickable=null;
return true;
}
Environmental affecting=(ticking instanceof Environmental)?((Environmental)ticking):null;
Vector scripts=getScripts();
int triggerCode=-1;
String trigger="";
String[] t=null;
for(int thisScriptIndex=0;thisScriptIndex<scripts.size();thisScriptIndex++)
{
DVector script=(DVector)scripts.elementAt(thisScriptIndex);
if(script.size()<2) continue;
trigger=((String)script.elementAt(0,1)).toUpperCase().trim();
t=(String[])script.elementAt(0,2);
triggerCode=getTriggerCode(trigger,t);
tickStatus=Tickable.STATUS_SCRIPT+triggerCode;
switch(triggerCode)
{
case 5: // rand_Prog
if((!mob.amDead())&&canTrigger(5))
{
if(t==null) t=parseBits(script,0,"CR");
int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs());
}
break;
case 16: // delay_prog
if((!mob.amDead())&&canTrigger(16))
{
int targetTick=-1;
if(delayTargetTimes.containsKey(Integer.valueOf(thisScriptIndex)))
targetTick=((Integer)delayTargetTimes.get(Integer.valueOf(thisScriptIndex))).intValue();
else
{
if(t==null) t=parseBits(script,0,"CCR");
int low=CMath.s_int(t[1]);
int high=CMath.s_int(t[2]);
if(high<low) high=low;
targetTick=CMLib.dice().roll(1,high-low+1,low-1);
delayTargetTimes.put(Integer.valueOf(thisScriptIndex),Integer.valueOf(targetTick));
}
int delayProgCounter=0;
if(delayProgCounters.containsKey(Integer.valueOf(thisScriptIndex)))
delayProgCounter=((Integer)delayProgCounters.get(Integer.valueOf(thisScriptIndex))).intValue();
else
delayProgCounters.put(Integer.valueOf(thisScriptIndex),Integer.valueOf(0));
if(delayProgCounter==targetTick)
{
execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs());
delayProgCounter=-1;
}
delayProgCounters.remove(Integer.valueOf(thisScriptIndex));
delayProgCounters.put(Integer.valueOf(thisScriptIndex),Integer.valueOf(delayProgCounter+1));
}
break;
case 7: // fightProg
if((mob.isInCombat())&&(!mob.amDead())&&canTrigger(7))
{
if(t==null) t=parseBits(script,0,"CR");
int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,newObjs());
}
else
if((ticking instanceof Item)
&&canTrigger(7)
&&(((Item)ticking).owner() instanceof MOB)
&&(((MOB)((Item)ticking).owner()).isInCombat()))
{
if(t==null) t=parseBits(script,0,"CR");
int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
MOB M=(MOB)((Item)ticking).owner();
if(!M.amDead())
execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,newObjs());
}
}
break;
case 11: // hitprcnt
if((mob.isInCombat())&&(!mob.amDead())&&canTrigger(11))
{
if(t==null) t=parseBits(script,0,"CR");
int prcnt=CMath.s_int(t[1]);
int floor=(int)Math.round(CMath.mul(CMath.div(prcnt,100.0),mob.maxState().getHitPoints()));
if(mob.curState().getHitPoints()<=floor)
execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,newObjs());
}
else
if((ticking instanceof Item)
&&canTrigger(11)
&&(((Item)ticking).owner() instanceof MOB)
&&(((MOB)((Item)ticking).owner()).isInCombat()))
{
MOB M=(MOB)((Item)ticking).owner();
if(!M.amDead())
{
if(t==null) t=parseBits(script,0,"CR");
int prcnt=CMath.s_int(t[1]);
int floor=(int)Math.round(CMath.mul(CMath.div(prcnt,100.0),M.maxState().getHitPoints()));
if(M.curState().getHitPoints()<=floor)
execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,newObjs());
}
}
break;
case 6: // once_prog
if(!oncesDone.contains(script)&&canTrigger(6))
{
if(t==null) t=parseBits(script,0,"C");
oncesDone.addElement(script);
execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs());
}
break;
case 14: // time_prog
if((mob.location()!=null)
&&canTrigger(14)
&&(!mob.amDead()))
{
if(t==null) t=parseBits(script,0,"CT");
int lastTimeProgDone=-1;
if(lastTimeProgsDone.containsKey(Integer.valueOf(thisScriptIndex)))
lastTimeProgDone=((Integer)lastTimeProgsDone.get(Integer.valueOf(thisScriptIndex))).intValue();
int time=mob.location().getArea().getTimeObj().getTimeOfDay();
if(lastTimeProgDone!=time)
{
boolean done=false;
for(int i=1;i<t.length;i++)
{
if(time==CMath.s_int(t[i]))
{
done=true;
execute(affecting,mob,mob,mob,defaultItem,null,script,""+time,newObjs());
lastTimeProgsDone.remove(Integer.valueOf(thisScriptIndex));
lastTimeProgsDone.put(Integer.valueOf(thisScriptIndex),Integer.valueOf(time));
break;
}
}
if(!done)
lastTimeProgsDone.remove(Integer.valueOf(thisScriptIndex));
}
}
break;
case 15: // day_prog
if((mob.location()!=null)&&canTrigger(15)
&&(!mob.amDead()))
{
if(t==null) t=parseBits(script,0,"CT");
int lastDayProgDone=-1;
if(lastDayProgsDone.containsKey(Integer.valueOf(thisScriptIndex)))
lastDayProgDone=((Integer)lastDayProgsDone.get(Integer.valueOf(thisScriptIndex))).intValue();
int day=mob.location().getArea().getTimeObj().getDayOfMonth();
if(lastDayProgDone!=day)
{
boolean done=false;
for(int i=1;i<t.length;i++)
{
if(day==CMath.s_int(t[i]))
{
done=true;
execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs());
lastDayProgsDone.remove(Integer.valueOf(thisScriptIndex));
lastDayProgsDone.put(Integer.valueOf(thisScriptIndex),Integer.valueOf(day));
break;
}
}
if(!done)
lastDayProgsDone.remove(Integer.valueOf(thisScriptIndex));
}
}
break;
case 13: // quest time prog
if(!oncesDone.contains(script)&&canTrigger(13))
{
if(t==null) t=parseBits(script,0,"CCC");
Quest Q=getQuest(t[1]);
if((Q!=null)&&(Q.running())&&(!Q.stopping()))
{
int time=CMath.s_int(t[2]);
if(time>=Q.minsRemaining())
{
oncesDone.addElement(script);
execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs());
}
}
}
break;
default:
break;
}
}
tickStatus=Tickable.STATUS_SCRIPT+100;
dequeResponses();
altStatusTickable=null;
return true;
}
public void initializeClass(){};
public int compareTo(CMObject o){ return CMClass.classID(this).compareToIgnoreCase(CMClass.classID(o));}
public void enqueResponse(Environmental host,
MOB source,
Environmental target,
MOB monster,
Item primaryItem,
Item secondaryItem,
DVector script,
int ticks,
String msg)
{
if(noDelay)
execute(host,source,target,monster,primaryItem,secondaryItem,script,msg,newObjs());
else
que.addElement(new ScriptableResponse(host,source,target,monster,primaryItem,secondaryItem,script,ticks,msg));
}
public void prequeResponse(Environmental host,
MOB source,
Environmental target,
MOB monster,
Item primaryItem,
Item secondaryItem,
DVector script,
int ticks,
String msg)
{
que.insertElementAt(new ScriptableResponse(host,source,target,monster,primaryItem,secondaryItem,script,ticks,msg),0);
}
public void dequeResponses()
{
try{
tickStatus=Tickable.STATUS_SCRIPT+100;
for(int q=que.size()-1;q>=0;q--)
{
ScriptableResponse SB=null;
try{SB=(ScriptableResponse)que.elementAt(q);}catch(ArrayIndexOutOfBoundsException x){continue;}
if(SB.checkTimeToExecute())
{
execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,newObjs());
que.removeElement(SB);
}
}
}catch(Exception e){Log.errOut("DefaultScriptingEngine",e);}
}
protected static class JScriptEvent extends ScriptableObject
{
public String getClassName(){ return "JScriptEvent";}
static final long serialVersionUID=43;
Environmental h=null;
MOB s=null;
Environmental t=null;
MOB m=null;
Item pi=null;
Item si=null;
Vector scr;
String message=null;
DefaultScriptingEngine c=null;
public Environmental host(){return h;}
public MOB source(){return s;}
public Environmental target(){return t;}
public MOB monster(){return m;}
public Item item(){return pi;}
public Item item2(){return si;}
public String message(){return message;}
public void setVar(String host, String var, String value)
{
c.setVar(host,var.toUpperCase(),value);
}
public String getVar(String host, String var)
{ return c.getVar(host,var);}
public String toJavaString(Object O){return Context.toString(O);}
public JScriptEvent(DefaultScriptingEngine scrpt,
Environmental host,
MOB source,
Environmental target,
MOB monster,
Item primaryItem,
Item secondaryItem,
String msg)
{
c=scrpt;
h=host;
s=source;
t=target;
m=monster;
pi=primaryItem;
si=secondaryItem;
message=msg;
}
}
}
| {
"content_hash": "243803bd826680e79b570dd30756e55f",
"timestamp": "",
"source": "github",
"line_count": 10112,
"max_line_length": 216,
"avg_line_length": 45.36550632911393,
"alnum_prop": 0.4294539778870636,
"repo_name": "welterde/ewok",
"id": "665a4f9350a9285746e98350056df9b5602eea37",
"size": "459343",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "com/planet_ink/coffee_mud/Common/DefaultScriptingEngine.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Yudansha")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Yudansha")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("72a7bb03-73e1-42d2-b86b-f3f845fddcdf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "a505b0c7625aed8eaaa74d7d9bee4692",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 84,
"avg_line_length": 38.542857142857144,
"alnum_prop": 0.7472201630837657,
"repo_name": "andreaorimoto/hyshhweb",
"id": "ad89f6ded1a6f64a43593be2f35ed5b298059920",
"size": "1352",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Yudansha/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "503429"
},
{
"name": "C#",
"bytes": "63524"
},
{
"name": "CSS",
"bytes": "291251"
},
{
"name": "HTML",
"bytes": "257024"
},
{
"name": "JavaScript",
"bytes": "1743568"
},
{
"name": "Python",
"bytes": "845"
},
{
"name": "Ruby",
"bytes": "738"
},
{
"name": "XSLT",
"bytes": "143425"
}
],
"symlink_target": ""
} |
package com.google.cloud.videointelligence.v1p1beta1.stub.samples;
// [START videointelligence_v1p1beta1_generated_VideoIntelligenceServiceStubSettings_AnnotateVideo_sync]
import com.google.cloud.videointelligence.v1p1beta1.stub.VideoIntelligenceServiceStubSettings;
import java.time.Duration;
public class SyncAnnotateVideo {
public static void main(String[] args) throws Exception {
syncAnnotateVideo();
}
public static void syncAnnotateVideo() throws Exception {
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in
// https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
VideoIntelligenceServiceStubSettings.Builder videoIntelligenceServiceSettingsBuilder =
VideoIntelligenceServiceStubSettings.newBuilder();
videoIntelligenceServiceSettingsBuilder
.annotateVideoSettings()
.setRetrySettings(
videoIntelligenceServiceSettingsBuilder
.annotateVideoSettings()
.getRetrySettings()
.toBuilder()
.setTotalTimeout(Duration.ofSeconds(30))
.build());
VideoIntelligenceServiceStubSettings videoIntelligenceServiceSettings =
videoIntelligenceServiceSettingsBuilder.build();
}
}
// [END videointelligence_v1p1beta1_generated_VideoIntelligenceServiceStubSettings_AnnotateVideo_sync]
| {
"content_hash": "1443228d8f2a9f4161f048ec8096446f",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 104,
"avg_line_length": 45.361111111111114,
"alnum_prop": 0.7587262706674831,
"repo_name": "googleapis/google-cloud-java",
"id": "531098bfe46b71e9991ad893e9fba1af420e6fb0",
"size": "2228",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "java-video-intelligence/samples/snippets/generated/com/google/cloud/videointelligence/v1p1beta1/stub/videointelligenceservicestubsettings/annotatevideo/SyncAnnotateVideo.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2614"
},
{
"name": "HCL",
"bytes": "28592"
},
{
"name": "Java",
"bytes": "826434232"
},
{
"name": "Jinja",
"bytes": "2292"
},
{
"name": "Python",
"bytes": "200408"
},
{
"name": "Shell",
"bytes": "97954"
}
],
"symlink_target": ""
} |
Legacy of the Caste War in The Yucatan
====================================
More than a hundred years after the end of the Caste War Yucatan is still divided.
1.- Run download_padron.sh
1.- Use R to run run_all.R
You'll need to install ssconvert from gnumeric to clean the xls files from the listado nominal
GDF files for loading into gephi are in the gephi directory
| {
"content_hash": "b884a4c0bcf767c037995ed6b78a14b6",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 94,
"avg_line_length": 33.81818181818182,
"alnum_prop": 0.7016129032258065,
"repo_name": "diegovalle/caste-war",
"id": "e79e785b1547bcb1fbf2bae5d9539281c8e196a0",
"size": "372",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "1244"
},
{
"name": "R",
"bytes": "32855"
},
{
"name": "Shell",
"bytes": "582"
}
],
"symlink_target": ""
} |
package com.nilhcem.devoxxfr.core.dagger;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
@Module
public class OkHttpModule {
@Provides @Singleton OkHttpClient provideOkHttpClient(OkHttpClient.Builder builder) {
return builder.build();
}
}
| {
"content_hash": "70b6a190d4725d6a0b099f40b37be7a9",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 89,
"avg_line_length": 21.2,
"alnum_prop": 0.7704402515723271,
"repo_name": "Nilhcem/devoxxfr-2016",
"id": "b4774b8d945ce2e3c576232359f35e06acfd91c0",
"size": "318",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/production/java/com/nilhcem/devoxxfr/core/dagger/OkHttpModule.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "262"
},
{
"name": "IDL",
"bytes": "1968"
},
{
"name": "Java",
"bytes": "213501"
},
{
"name": "JavaScript",
"bytes": "1912"
},
{
"name": "Kotlin",
"bytes": "7783"
},
{
"name": "Prolog",
"bytes": "656"
},
{
"name": "Shell",
"bytes": "795"
}
],
"symlink_target": ""
} |
from testing import unittest, RedconTestBase
from redcon.model import ModelMeta
from redcon.fields import Field
class TestClassToKeyRegex(unittest.TestCase):
def setUp(self):
self.re = ModelMeta.re_cls_to_key
def test_standard_camel_case(self):
name = 'MyAwesomeClass'
expected = ['My', 'Awesome', 'Class']
actual = self.re.findall(name)
self.assertEqual(expected, actual)
def test_starts_caps(self):
name = 'OMGClass'
expected = ['OMG', 'Class']
actual = self.re.findall(name)
self.assertEqual(expected, actual)
def test_ends_caps(self):
name = 'ClassOMG'
expected = ['Class', 'OMG']
actual = self.re.findall(name)
self.assertEqual(expected, actual)
def test_mixed_caps(self):
name = 'WHOWouldDOThis'
expected = ['WHO', 'Would', 'DO', 'This']
actual = self.re.findall(name)
self.assertEqual(expected, actual)
def test_numbers(self):
name = 'MyClass03'
expected = ['My', 'Class', '03']
actual = self.re.findall(name)
self.assertEqual(expected, actual)
def test_numbers_caps(self):
name = 'WUT33Do'
expected = ['WUT', '33', 'Do']
actual = self.re.findall(name)
self.assertEqual(expected, actual)
def test_with_underscore(self):
name = 'Ugly_class'
expected = ['Ugly', 'class']
actual = self.re.findall(name)
self.assertEqual(expected, actual)
class TestModelDefaultSetup(RedconTestBase):
def setUp(self):
super(TestModelDefaultSetup, self).setUp()
class Default(self.redcon.Model):
field1 = self.redcon.fields.Field()
field2 = self.redcon.fields.Field(lookup=True)
self.Default = Default
def test_keyname_set(self):
self.assertEqual('default', self.Default.__keyname__)
def test_countername_set(self):
self.assertEqual('counter.default', self.Default.__countername__)
def test_lookupname_set(self):
self.assertIsNone(self.Default._fields['field1'].lookupname)
self.assertEqual('default:lookup:field2', self.Default._fields['field2'].lookupname)
def test_fields_setup(self):
self.assertTrue(hasattr(self.Default, '_fields'))
self.assertTrue(len(self.Default._fields) == 2)
self.assertTrue(isinstance(self.Default._fields['field1'], Field))
self.assertEqual('field1', self.Default._fields['field1'].name)
self.assertTrue(isinstance(self.Default._fields['field2'], Field))
self.assertEqual('field2', self.Default._fields['field2'].name)
class TestModelCustomSetup(RedconTestBase):
def setUp(self):
super(TestModelCustomSetup, self).setUp()
class Custom(self.redcon.Model):
__keyname__ = 'my_custom_key'
__countername__ = 'my_custom_counter.{keyname}'
__lookupname__ = '{field_name}:myownlookup:{keyname}'
important = self.redcon.fields.Field(lookup=True)
self.Custom = Custom
def test_keyname_set(self):
self.assertEqual('my_custom_key', self.Custom.__keyname__)
def test_countername_set(self):
self.assertEqual('my_custom_counter.my_custom_key', self.Custom.__countername__)
def test_invalid_countername_raises(self):
with self.assertRaises(ValueError) as cm:
class InvalidCustom(self.redcon.Model):
__countername__ = 'invalid_counter'
self.assertEqual(
("invalid __countername__ format 'invalid_counter' for InvalidCustom "
"({keyname} replacement field is required)"),
cm.exception.message
)
def test_lookupname_set(self):
self.assertEqual(
'important:myownlookup:my_custom_key',
self.Custom._fields['important'].lookupname
)
def test_invalid_lookupname_raises(self):
with self.assertRaises(ValueError) as cm:
class InvalidLookup(self.redcon.Model):
__lookupname__ = 'invalid_lookup'
self.assertEqual(
("invalid __lookupname__ format 'invalid_lookup' for InvalidLookup "
"({keyname} and {field_name} replacement fields are required)"),
cm.exception.message,
)
class TestModelSaving(RedconTestBase):
def setUp(self):
super(TestModelSaving, self).setUp()
self.redis.set('counter.with_lookups', 20)
self.redis.set('counter.no_lookups', 40)
class WithLookups(self.redcon.Model):
field1 = self.redcon.fields.Field(lookup=True)
field2 = self.redcon.fields.Field()
field3 = self.redcon.fields.Field(lookup=True)
self.with_lookups = WithLookups(
field1='one',
field2='two',
field3='three'
)
class NoLookups(self.redcon.Model):
field1 = self.redcon.fields.Field()
field2 = self.redcon.fields.Field()
self.no_lookups = NoLookups(
field1=1,
field2=2,
)
def test_multi_save_instantiation(self):
actual = self.redis.hgetall(self.with_lookups._key)
expected = dict(
field1='one',
field2='two',
field3='three',
)
self.assertEqual(expected, actual)
def test_save_instantiation_id(self):
self.assertEqual(21, self.with_lookups.id)
def test_save_after_instantiation(self):
self.with_lookups(
field1=1,
field2=2,
field3=3,
)
expected = dict(
field1='1',
field2='2',
field3='3',
)
actual = self.redis.hgetall(self.with_lookups._key)
self.assertEqual(expected, actual)
def test_save_attempt_non_field(self):
with self.assertRaises(AttributeError) as cm:
self.with_lookups(notafield='hi')
self.assertEqual(
"WithLookups has no field 'notafield'",
cm.exception.message,
)
def test_reverse_lookup_instantiation(self):
field1_expected_lookup = {
'one': '21',
}
field1_lookup = self.redis.hgetall('with_lookups:lookup:field1')
self.assertEqual(field1_expected_lookup, field1_lookup)
field3_expected_lookup = {
'three': '21',
}
field3_lookup = self.redis.hgetall('with_lookups:lookup:field3')
self.assertEqual(field3_expected_lookup, field3_lookup)
def test_no_looksups(self):
expected = dict(
field1='1',
field2='2',
)
actual = self.redis.hgetall(self.no_lookups._key)
self.assertEqual(expected, actual)
| {
"content_hash": "cae6ae8455e303540e823ec708b3dff7",
"timestamp": "",
"source": "github",
"line_count": 211,
"max_line_length": 92,
"avg_line_length": 32.14691943127962,
"alnum_prop": 0.6001769128704113,
"repo_name": "atatsu/redcon",
"id": "bb6a3780d584c060f860998452cc0e84cb0343a4",
"size": "6783",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/model-tests.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "50394"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using YleService;
public class SearchMenu : MonoBehaviour, TableViewDataSource
{
public TableView MainTableView;
public ScrollRect MainScrollRect;
public InputField SearchInputField;
public Button SearchButton;
public YleProgramSearchService SearchService;
[SpaceAttribute(10)]
public GameObject CellPrefab;
// MonoBehaviour
void Start ()
{
MainTableView.DataSource = this;
SearchService.LoadProgramBatchFinished += LoadProgramBatchFinished;
SearchButton.onClick.AddListener(SearchButtonWasSelected);
}
void Update ()
{
if (MainScrollRect.normalizedPosition.y <= 0.0 && !SearchService.IsLoading)
SearchService.LoadProgramBatch();
}
// Events
private void LoadProgramBatchFinished(List<YleProgram> programs, string error)
{
if (programs != null && error == null)
MainTableView.SetupMissingCells();
else
Debug.LogError(error);
}
private void SearchButtonWasSelected()
{
if (!string.IsNullOrEmpty(SearchInputField.text))
{
SearchService.InitializeProgramSearch(SearchInputField.text, 10);
SearchService.LoadProgramBatch();
MainTableView.ReloadData();
}
}
// TableViewDataSource implementation
public int NumberOfElementsInTableView(TableView tableView)
{
return SearchService.Programs.Count;
}
public GameObject TableViewCellForIndex(int index, TableView tableView)
{
GameObject cell = tableView.DequeueCellAtIndex(index);
if (!cell)
cell = Instantiate(CellPrefab);
ProgramPresenter presenter = cell.GetComponent<ProgramPresenter>();
presenter.PresentProgram(SearchService.Programs[index]);
return cell;
}
}
| {
"content_hash": "50c609db19a0904f84d51cd2788412b6",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 83,
"avg_line_length": 29.015151515151516,
"alnum_prop": 0.6783289817232376,
"repo_name": "Rathnadeviprasath1/yle-search-query",
"id": "480c17d99027ab64bc9a20dab8892181078ff324",
"size": "1917",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Assets/Scripts/SearchMenu.cs",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "118649"
},
{
"name": "C#",
"bytes": "322752"
},
{
"name": "GLSL",
"bytes": "24830"
},
{
"name": "JavaScript",
"bytes": "68847"
}
],
"symlink_target": ""
} |
-- |
-- Module : Crypto.Saltine.Core.Hash
-- Copyright : (c) Joseph Abrahamson 2013
-- License : MIT
--
-- Maintainer : me@jspha.com
-- Stability : experimental
-- Portability : non-portable
--
-- Hashing: "Crypto.Saltine.Core.Hash"
--
-- The 'hash' function hashes a message 'ByteString' and returns a
-- hash. Hashes are always of length 'Bytes.hash'. The 'shorthash'
-- function hashes a message 'ByteString' with respect to a secret key
-- and returns a very short hash. Short hashes are always of length
-- 'Bytes.shorthash'.
--
-- The 'hash' function is designed to be usable as a strong component
-- of DSA, RSA-PSS, key derivation, hash-based message-authentication
-- codes, hash-based ciphers, and various other common
-- applications. "Strong" means that the security of these
-- applications, when instantiated with 'hash', is the same as the
-- security of the applications against generic attacks. In
-- particular, the 'hash' function is designed to make finding
-- collisions difficult.
--
-- 'hash' is currently an implementation of SHA-512. 'shorthash' is
-- currently an implementation of SipHash-2-4
-- (<https://131002.net/siphash/>).
--
-- There has been considerable degradation of public confidence in the
-- security conjectures for many hash functions, including
-- SHA-512. However, for the moment, there do not appear to be
-- alternatives that inspire satisfactory levels of confidence. One
-- can hope that NIST's SHA-3 competition will improve the situation.
--
-- Sodium includes an implementation of the Blake2b hash function
-- (<https://blake2.net/>) and is bound here as the 'generichash'
-- function.
--
-- This is version 2010.08.30 of the hash.html web page. Information
-- about SipHash has been added.
module Crypto.Saltine.Core.Hash (
ShorthashKey,
hash,
shorthash, newShorthashKey,
GenerichashKey,
newGenerichashKey,
GenerichashOutLen,
generichashOutLen, generichash
) where
import Crypto.Saltine.Internal.Hash
( c_hash
, c_generichash
, shorthash
, ShorthashKey(..)
, GenerichashKey(..)
, GenerichashOutLen(..)
)
import Crypto.Saltine.Internal.Util as U
import Data.ByteString (ByteString)
import qualified Crypto.Saltine.Internal.Hash as Bytes
import qualified Data.ByteString as S
-- | Computes a cryptographically collision-resistant hash making
-- @hash m == hash m' ==> m == m'@ highly likely even when under
-- attack.
hash :: ByteString
-- ^ Message
-> ByteString
-- ^ Hash
hash m = snd . buildUnsafeByteString Bytes.hash_bytes $ \ph ->
constByteStrings [m] $ \[(pm, _)] -> c_hash ph pm (fromIntegral $ S.length m)
-- | Randomly generates a new key for 'shorthash'.
newShorthashKey :: IO ShorthashKey
newShorthashKey = ShK <$> randomByteString Bytes.shorthash_keybytes
-- | Randomly generates a new key for 'generichash' of the given length.
newGenerichashKey :: Int -> IO (Maybe GenerichashKey)
newGenerichashKey n = if n >= 0 && n <= Bytes.generichash_keybytes_max
then Just . GhK <$> randomByteString n
else return Nothing
-- | Create a validated Generichash output length
generichashOutLen :: Int -> Maybe GenerichashOutLen
generichashOutLen n = if n > 0 && n <= Bytes.generichash_bytes_max
then Just $ GhOL $ fromIntegral n
else Nothing
-- | Computes a generic, keyed hash.
generichash :: GenerichashKey
-> ByteString
-- ^ Message
-> GenerichashOutLen
-- ^ Desired output hash length
-> ByteString
-- ^ Hash
generichash (GhK k) m (GhOL outLen) = snd . buildUnsafeByteString outLen $ \ph ->
constByteStrings [k, m] $ \[(pk, _), (pm, _)] ->
c_generichash ph (fromIntegral outLen) pm (fromIntegral $ S.length m) pk (fromIntegral $ S.length k)
| {
"content_hash": "61b423005670fb729f17a6138c4382c8",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 104,
"avg_line_length": 38.12621359223301,
"alnum_prop": 0.675833969951617,
"repo_name": "tel/saltine",
"id": "1bac29730de780b4f5cd345c8203b0e1985cd1bc",
"size": "3927",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Crypto/Saltine/Core/Hash.hs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Haskell",
"bytes": "240995"
},
{
"name": "Makefile",
"bytes": "236"
}
],
"symlink_target": ""
} |
using System;
using Xamarin.Forms;
using System.Collections.ObjectModel;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Collections.Generic;
namespace tdlr
{
public class TaskListPage : ContentPage
{
public IPlatformParameters platformParams { get; set; }
Image _delete;
Image _edit;
Image _share;
Image _done;
StackLayout _navbar;
ListView _taskList;
Label _vr;
Label _add;
ObservableCollection<Task> _tasks;
Entry _entry;
Image _cancel;
string _userObjectId;
public TaskListPage ()
{
_tasks = new ObservableCollection<Task> ();
#region UI Init
NavigationPage.SetHasNavigationBar (this, false);
this.Title = "tdlr;";
_cancel = new Image {
Aspect = Aspect.AspectFit,
Source = ImageSource.FromFile ("ic_close_white.png"),
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.Center,
IsVisible = false,
Opacity = 0,
};
_delete = new Image {
Aspect = Aspect.AspectFit,
Source = ImageSource.FromFile("ic_delete.png"),
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.Center,
IsVisible = false,
Opacity = 0
};
_edit = new Image {
Aspect = Aspect.AspectFit,
Source = ImageSource.FromFile("ic_mode_edit.png"),
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.Center,
IsVisible = false,
Opacity = 0
};
_share = new Image {
Aspect = Aspect.AspectFit,
Source = ImageSource.FromFile ("ic_share.png"),
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.Center,
IsVisible = false,
Opacity = 0
};
_done = new Image {
Aspect = Aspect.AspectFit,
Source = ImageSource.FromFile ("ic_done_white.png"),
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.Center,
IsVisible = false,
Opacity = 0
};
_vr = new Label {
Text = "|",
TextColor = Color.White,
FontSize = 24,
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.Center,
IsVisible = false,
Opacity = 0
};
_add = new Label {
Text = "+",
TextColor = Color.White,
FontSize = 30,
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.Center,
IsVisible = true,
Opacity = 1
};
_entry = new Entry {
Placeholder = "Enter your task...",
BackgroundColor = Color.Transparent,
TextColor = Color.Black,
IsEnabled = false,
Opacity = 0,
IsVisible = false,
};
_taskList = new ListView {
ItemsSource = _tasks,
IsPullToRefreshEnabled = true,
};
_taskList.ItemTemplate = new DataTemplate (typeof(TaskCell));
Image menu = new Image {
Aspect = Aspect.AspectFit,
Source = ImageSource.FromFile ("ic_menu_white.png"),
HorizontalOptions = LayoutOptions.Start,
VerticalOptions = LayoutOptions.Center,
};
_navbar = new StackLayout {
Orientation = StackOrientation.Horizontal,
HeightRequest = 50,
Padding = new Thickness(10, 0, 20, 0),
Spacing = 5,
BackgroundColor = Color.Black,
Children = {
menu,
new Label {
Text = " tdlr;",
HorizontalOptions = LayoutOptions.StartAndExpand,
VerticalOptions = LayoutOptions.Center,
FontFamily = "Pacifico",
FontSize = 24,
TextColor = Color.FromRgb(240,128,128)
},
_add,
_cancel,
_edit,
_share,
_delete,
_vr,
_done,
}
};
#endregion
#region Event Listeners
_entry.Completed += OnTaskEntered;
_cancel.GestureRecognizers.Add (new TapGestureRecognizer (OnCancelClicked));
_add.GestureRecognizers.Add (new TapGestureRecognizer (OnAddClicked));
_delete.GestureRecognizers.Add (new TapGestureRecognizer (OnDeleteClicked));
_edit.GestureRecognizers.Add (new TapGestureRecognizer (OnEditClicked));
_share.GestureRecognizers.Add (new TapGestureRecognizer (OnShareClicked));
_done.GestureRecognizers.Add (new TapGestureRecognizer (OnDoneClicked));
_taskList.ItemSelected += OnTaskSelected;
menu.GestureRecognizers.Add (new TapGestureRecognizer (OnMenuClicked));
#endregion
#region Main Layout
Content = new StackLayout {
Orientation = StackOrientation.Vertical,
Spacing = 0,
Padding = new Thickness(0,0,0,0),
Children = {
_navbar,
new BoxView {
Color = Color.Gray,
HeightRequest = 1,
BackgroundColor = Color.Black
},
_entry,
new ScrollView {
Content = _taskList
}
}
};
#endregion
}
// When a task is selected or deselected, show the right actions
void OnTaskSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem != null) {
_delete.Opacity = 0;
_edit.Opacity = 0;
_share.Opacity = 0;
_vr.Opacity = 0;
_done.Opacity = 0;
if (((Task)e.SelectedItem).Creator == _userObjectId) {
_delete.IsVisible = true;
_share.IsVisible = true;
_delete.FadeTo (1, 250);
_share.FadeTo (1, 250);
}
_edit.IsVisible = true;
_done.IsVisible = true;
_vr.IsVisible = true;
_add.FadeTo (0, 250);
_add.IsVisible = false;
_edit.FadeTo (1, 250);
_done.FadeTo (1, 250);
_vr.FadeTo (1, 250);
} else {
_delete.FadeTo (0, 250);
_edit.FadeTo (0, 250);
_share.FadeTo (0, 250);
_done.FadeTo (0, 250);
_vr.FadeTo (0, 250);
_add.IsVisible = true;
_delete.IsVisible = false;
_edit.IsVisible = false;
_share.IsVisible = false;
_done.IsVisible = false;
_vr.IsVisible = false;
_add.FadeTo (1, 250);
}
}
// When the user creates a task, try to create & add it to the list
async void OnTaskEntered(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty (_entry.Text)) {
try {
// Create the task
await TaskHelper.CreateTask(_entry.Text);
// Update the UI
_entry.FadeTo(0, 250);
_entry.IsEnabled = false;
_entry.IsVisible = false;
_entry.Text = null;
_cancel.FadeTo (0, 250);
_cancel.IsVisible = false;
_add.IsVisible = true;
_add.FadeTo (1, 250);
// Refresh the list data
OnAppearing();
} catch (Exception ex) {
this.DisplayAlert ("Error creating task", ex.Message, "OK");
}
}
}
// When the user cancels adding a task
async void OnCancelClicked(View image, object sender)
{
_entry.FadeTo(0, 250);
_entry.IsEnabled = false;
_entry.IsVisible = false;
_entry.Text = null;
_cancel.FadeTo (0, 250);
_cancel.IsVisible = false;
_add.IsVisible = true;
_add.FadeTo (1, 250);
}
// When the user deletes a task
async void OnDeleteClicked(View image, object sender)
{
try {
// Delete the task
Task task = ((Task)_taskList.SelectedItem);
await TaskHelper.DeleteTask(task);
// Remove it from the list, and deselect the task
_tasks.Remove(task);
_taskList.SelectedItem = null;
} catch (Exception ex) {
this.DisplayAlert ("Error deleting task", ex.Message, "OK");
}
}
// Unselect the task
async void OnDoneClicked(View image, object sender)
{
_taskList.SelectedItem = null;
}
// Show the add task UI
async void OnAddClicked(View image, object sender)
{
_entry.IsEnabled = true;
_entry.IsVisible = true;
_entry.FadeTo (1, 250);
_entry.Focus ();
_add.FadeTo (0, 250);
_add.IsVisible = false;
_cancel.IsVisible = true;
_cancel.FadeTo (1, 250);
}
// Bring up the options for task status
async void OnEditClicked(View image, object sender)
{
// Show status options
Task task = ((Task)_taskList.SelectedItem);
string oldStatus = task.Status;
var status = await DisplayActionSheet (task.TaskText, "Cancel", null, new string [] {"NotStarted", "InProgress", "Complete", "Blocked"});
if (status.Equals ("Cancel"))
return;
task.Status = status;
try {
// Update the status on the server
await TaskHelper.UpdateTask(task);
} catch (Exception ex) {
task.Status = oldStatus;
DisplayAlert ("Error updating task", ex.Message, "OK");
}
}
// Launch the share list page
async void OnShareClicked(View image, object sender)
{
Navigation.PushAsync (new ShareListPage ((Task)_taskList.SelectedItem));
}
// Logout
async void OnMenuClicked(View image, object sender)
{
App.AuthContext.TokenCache.Clear ();
App.SetADALAuthority ();
OnAppearing ();
}
protected override async void OnAppearing ()
{
_tasks.Clear ();
base.OnAppearing ();
try {
// Make sure the user is signed in and we can get token for calling APIs
AuthenticationResult authResult = await App.AuthContext.AcquireTokenSilentAsync (App.taskApiResourceId, App.clientId);
_userObjectId = authResult.UserInfo.UniqueId;
} catch (Exception ex) {
// Send the user back to the sign in screen, they need to sign in again.
App.AuthContext.TokenCache.Clear ();
Navigation.InsertPageBefore (new WelcomePage (), this);
Navigation.PopAsync ().ConfigureAwait (false);
return;
}
try {
// Update the list of tasks
List<Task> tasks = await TaskHelper.GetUserTasks();
foreach (Task task in tasks) {
_tasks.Add (task);
}
} catch (Exception ex) {
await this.DisplayAlert ("Error getting tasks", ex.Message, "OK");
Navigation.InsertPageBefore (new WelcomePage (), this);
Navigation.PopAsync ().ConfigureAwait (false);
}
}
}
}
| {
"content_hash": "efaa254c85044eee5a24dd1bd4b2fe8d",
"timestamp": "",
"source": "github",
"line_count": 369,
"max_line_length": 141,
"avg_line_length": 25.647696476964768,
"alnum_prop": 0.6482459847844463,
"repo_name": "skwan/cloudroadshow-xamarin",
"id": "0af56d2b89ff39c8d04f4f88236eb9353958f276",
"size": "9466",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tdlr/Views/TaskListPage.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "59335"
}
],
"symlink_target": ""
} |
.class Landroid/widget/VideoView$3;
.super Ljava/lang/Object;
.source "VideoView.java"
# interfaces
.implements Landroid/media/MediaPlayer$OnCompletionListener;
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Landroid/widget/VideoView;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x0
name = null
.end annotation
# instance fields
.field final synthetic this$0:Landroid/widget/VideoView;
# direct methods
.method constructor <init>(Landroid/widget/VideoView;)V
.locals 0
.prologue
.line 588
iput-object p1, p0, Landroid/widget/VideoView$3;->this$0:Landroid/widget/VideoView;
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
return-void
.end method
# virtual methods
.method public onCompletion(Landroid/media/MediaPlayer;)V
.locals 2
.param p1, "mp" # Landroid/media/MediaPlayer;
.prologue
const/4 v1, 0x5
.line 590
iget-object v0, p0, Landroid/widget/VideoView$3;->this$0:Landroid/widget/VideoView;
iput v1, v0, Landroid/widget/VideoView;->mCurrentState:I
.line 591
iget-object v0, p0, Landroid/widget/VideoView$3;->this$0:Landroid/widget/VideoView;
iput v1, v0, Landroid/widget/VideoView;->mTargetState:I
.line 592
iget-object v0, p0, Landroid/widget/VideoView$3;->this$0:Landroid/widget/VideoView;
iget-object v0, v0, Landroid/widget/VideoView;->mMediaController:Landroid/widget/MediaController;
if-eqz v0, :cond_0
.line 593
iget-object v0, p0, Landroid/widget/VideoView$3;->this$0:Landroid/widget/VideoView;
iget-object v0, v0, Landroid/widget/VideoView;->mMediaController:Landroid/widget/MediaController;
invoke-virtual {v0}, Landroid/widget/MediaController;->hide()V
.line 595
:cond_0
iget-object v0, p0, Landroid/widget/VideoView$3;->this$0:Landroid/widget/VideoView;
iget-object v0, v0, Landroid/widget/VideoView;->mOnCompletionListener:Landroid/media/MediaPlayer$OnCompletionListener;
if-eqz v0, :cond_1
.line 596
iget-object v0, p0, Landroid/widget/VideoView$3;->this$0:Landroid/widget/VideoView;
iget-object v0, v0, Landroid/widget/VideoView;->mOnCompletionListener:Landroid/media/MediaPlayer$OnCompletionListener;
iget-object v1, p0, Landroid/widget/VideoView$3;->this$0:Landroid/widget/VideoView;
iget-object v1, v1, Landroid/widget/VideoView;->mMediaPlayer:Landroid/media/MediaPlayer;
invoke-interface {v0, v1}, Landroid/media/MediaPlayer$OnCompletionListener;->onCompletion(Landroid/media/MediaPlayer;)V
.line 598
:cond_1
return-void
.end method
| {
"content_hash": "a067e12176e3b629663bb02499793433",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 123,
"avg_line_length": 28.532608695652176,
"alnum_prop": 0.7367619047619047,
"repo_name": "hexiaoshuai/Flyme_device_ZTE_A1",
"id": "9d0ced06a0e70c371edbc2fae59ef5301bc937d0",
"size": "2625",
"binary": false,
"copies": "1",
"ref": "refs/heads/C880AV1.0.0B06",
"path": "framework.jar.out/smali/android/widget/VideoView$3.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "1500"
},
{
"name": "HTML",
"bytes": "10195"
},
{
"name": "Makefile",
"bytes": "11258"
},
{
"name": "Python",
"bytes": "924"
},
{
"name": "Shell",
"bytes": "2734"
},
{
"name": "Smali",
"bytes": "234274633"
}
],
"symlink_target": ""
} |
package org.elasticsearch.index.mapper.core;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.NumericRangeFilter;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.NumericUtils;
import org.elasticsearch.ElasticSearchIllegalArgumentException;
import org.elasticsearch.common.Explicit;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Numbers;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.analysis.NamedAnalyzer;
import org.elasticsearch.index.analysis.NumericIntegerAnalyzer;
import org.elasticsearch.index.codec.postingsformat.PostingsFormatProvider;
import org.elasticsearch.index.fielddata.IndexFieldDataService;
import org.elasticsearch.index.fielddata.IndexNumericFieldData;
import org.elasticsearch.index.mapper.*;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.search.NumericRangeFieldDataFilter;
import org.elasticsearch.index.similarity.SimilarityProvider;
import java.io.IOException;
import java.util.Map;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeIntegerValue;
import static org.elasticsearch.index.mapper.MapperBuilders.integerField;
import static org.elasticsearch.index.mapper.core.TypeParsers.parseNumberField;
/**
*
*/
public class IntegerFieldMapper extends NumberFieldMapper<Integer> {
public static final String CONTENT_TYPE = "integer";
public static class Defaults extends NumberFieldMapper.Defaults {
public static final FieldType FIELD_TYPE = new FieldType(NumberFieldMapper.Defaults.FIELD_TYPE);
static {
FIELD_TYPE.freeze();
}
public static final Integer NULL_VALUE = null;
}
public static class Builder extends NumberFieldMapper.Builder<Builder, IntegerFieldMapper> {
protected Integer nullValue = Defaults.NULL_VALUE;
public Builder(String name) {
super(name, new FieldType(Defaults.FIELD_TYPE));
builder = this;
}
public Builder nullValue(int nullValue) {
this.nullValue = nullValue;
return this;
}
@Override
public IntegerFieldMapper build(BuilderContext context) {
fieldType.setOmitNorms(fieldType.omitNorms() && boost == 1.0f);
IntegerFieldMapper fieldMapper = new IntegerFieldMapper(buildNames(context),
precisionStep, fuzzyFactor, boost, fieldType,
nullValue, ignoreMalformed(context), provider, similarity);
fieldMapper.includeInAll(includeInAll);
return fieldMapper;
}
}
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
IntegerFieldMapper.Builder builder = integerField(name);
parseNumberField(builder, name, node, parserContext);
for (Map.Entry<String, Object> entry : node.entrySet()) {
String propName = Strings.toUnderscoreCase(entry.getKey());
Object propNode = entry.getValue();
if (propName.equals("null_value")) {
builder.nullValue(nodeIntegerValue(propNode));
}
}
return builder;
}
}
private Integer nullValue;
private String nullValueAsString;
protected IntegerFieldMapper(Names names, int precisionStep, String fuzzyFactor,
float boost, FieldType fieldType,
Integer nullValue, Explicit<Boolean> ignoreMalformed,
PostingsFormatProvider provider, SimilarityProvider similarity) {
super(names, precisionStep, fuzzyFactor, boost, fieldType,
ignoreMalformed, new NamedAnalyzer("_int/" + precisionStep, new NumericIntegerAnalyzer(precisionStep)),
new NamedAnalyzer("_int/max", new NumericIntegerAnalyzer(Integer.MAX_VALUE)), provider, similarity);
this.nullValue = nullValue;
this.nullValueAsString = nullValue == null ? null : nullValue.toString();
}
@Override
public FieldType defaultFieldType() {
return Defaults.FIELD_TYPE;
}
@Override
public org.elasticsearch.index.fielddata.FieldDataType fieldDataType() {
return new org.elasticsearch.index.fielddata.FieldDataType("int");
}
@Override
protected int maxPrecisionStep() {
return 32;
}
@Override
public Integer value(Object value) {
if (value == null) {
return null;
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value instanceof BytesRef) {
return Numbers.bytesToInt((BytesRef) value);
}
return Integer.parseInt(value.toString());
}
@Override
public BytesRef indexedValueForSearch(Object value) {
BytesRef bytesRef = new BytesRef();
NumericUtils.intToPrefixCoded(parseValue(value), precisionStep(), bytesRef);
return bytesRef;
}
private int parseValue(Object value) {
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value instanceof BytesRef) {
return Integer.parseInt(((BytesRef) value).utf8ToString());
}
return Integer.parseInt(value.toString());
}
@Override
public Query fuzzyQuery(String value, String minSim, int prefixLength, int maxExpansions, boolean transpositions) {
int iValue = Integer.parseInt(value);
int iSim;
try {
iSim = Integer.parseInt(minSim);
} catch (NumberFormatException e) {
iSim = (int) Float.parseFloat(minSim);
}
return NumericRangeQuery.newIntRange(names.indexName(), precisionStep,
iValue - iSim,
iValue + iSim,
true, true);
}
@Override
public Query fuzzyQuery(String value, double minSim, int prefixLength, int maxExpansions, boolean transpositions) {
int iValue = Integer.parseInt(value);
int iSim = (int) (minSim * dFuzzyFactor);
return NumericRangeQuery.newIntRange(names.indexName(), precisionStep,
iValue - iSim,
iValue + iSim,
true, true);
}
@Override
public Query termQuery(Object value, @Nullable QueryParseContext context) {
int iValue = parseValue(value);
return NumericRangeQuery.newIntRange(names.indexName(), precisionStep,
iValue, iValue, true, true);
}
@Override
public Filter termFilter(Object value, @Nullable QueryParseContext context) {
int iValue = parseValue(value);
return NumericRangeFilter.newIntRange(names.indexName(), precisionStep,
iValue, iValue, true, true);
}
@Override
public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
return NumericRangeQuery.newIntRange(names.indexName(), precisionStep,
lowerTerm == null ? null : parseValue(lowerTerm),
upperTerm == null ? null : parseValue(upperTerm),
includeLower, includeUpper);
}
@Override
public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
return NumericRangeFilter.newIntRange(names.indexName(), precisionStep,
lowerTerm == null ? null : parseValue(lowerTerm),
upperTerm == null ? null : parseValue(upperTerm),
includeLower, includeUpper);
}
@Override
public Filter rangeFilter(IndexFieldDataService fieldData, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
return NumericRangeFieldDataFilter.newIntRange((IndexNumericFieldData) fieldData.getForField(this),
lowerTerm == null ? null : parseValue(lowerTerm),
upperTerm == null ? null : parseValue(upperTerm),
includeLower, includeUpper);
}
@Override
public Filter nullValueFilter() {
if (nullValue == null) {
return null;
}
return NumericRangeFilter.newIntRange(names.indexName(), precisionStep,
nullValue,
nullValue,
true, true);
}
@Override
protected boolean customBoost() {
return true;
}
@Override
protected Field innerParseCreateField(ParseContext context) throws IOException {
int value;
float boost = this.boost;
if (context.externalValueSet()) {
Object externalValue = context.externalValue();
if (externalValue == null) {
if (nullValue == null) {
return null;
}
value = nullValue;
} else if (externalValue instanceof String) {
String sExternalValue = (String) externalValue;
if (sExternalValue.length() == 0) {
if (nullValue == null) {
return null;
}
value = nullValue;
} else {
value = Integer.parseInt(sExternalValue);
}
} else {
value = ((Number) externalValue).intValue();
}
if (context.includeInAll(includeInAll, this)) {
context.allEntries().addText(names.fullName(), Integer.toString(value), boost);
}
} else {
XContentParser parser = context.parser();
if (parser.currentToken() == XContentParser.Token.VALUE_NULL ||
(parser.currentToken() == XContentParser.Token.VALUE_STRING && parser.textLength() == 0)) {
if (nullValue == null) {
return null;
}
value = nullValue;
if (nullValueAsString != null && (context.includeInAll(includeInAll, this))) {
context.allEntries().addText(names.fullName(), nullValueAsString, boost);
}
} else if (parser.currentToken() == XContentParser.Token.START_OBJECT) {
XContentParser.Token token;
String currentFieldName = null;
Integer objValue = nullValue;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else {
if ("value".equals(currentFieldName) || "_value".equals(currentFieldName)) {
if (parser.currentToken() != XContentParser.Token.VALUE_NULL) {
objValue = parser.intValue();
}
} else if ("boost".equals(currentFieldName) || "_boost".equals(currentFieldName)) {
boost = parser.floatValue();
} else {
throw new ElasticSearchIllegalArgumentException("unknown property [" + currentFieldName + "]");
}
}
}
if (objValue == null) {
// no value
return null;
}
value = objValue;
} else {
value = parser.intValue();
if (context.includeInAll(includeInAll, this)) {
context.allEntries().addText(names.fullName(), parser.text(), boost);
}
}
}
CustomIntegerNumericField field = new CustomIntegerNumericField(this, value, fieldType);
field.setBoost(boost);
return field;
}
@Override
protected String contentType() {
return CONTENT_TYPE;
}
@Override
public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException {
super.merge(mergeWith, mergeContext);
if (!this.getClass().equals(mergeWith.getClass())) {
return;
}
if (!mergeContext.mergeFlags().simulate()) {
this.nullValue = ((IntegerFieldMapper) mergeWith).nullValue;
this.nullValueAsString = ((IntegerFieldMapper) mergeWith).nullValueAsString;
}
}
@Override
protected void doXContentBody(XContentBuilder builder) throws IOException {
super.doXContentBody(builder);
if (precisionStep != Defaults.PRECISION_STEP) {
builder.field("precision_step", precisionStep);
}
if (fuzzyFactor != Defaults.FUZZY_FACTOR) {
builder.field("fuzzy_factor", fuzzyFactor);
}
if (nullValue != null) {
builder.field("null_value", nullValue);
}
if (includeInAll != null) {
builder.field("include_in_all", includeInAll);
}
}
public static class CustomIntegerNumericField extends CustomNumericField {
private final int number;
private final NumberFieldMapper mapper;
public CustomIntegerNumericField(NumberFieldMapper mapper, int number, FieldType fieldType) {
super(mapper, mapper.fieldType().stored() ? number : null, fieldType);
this.mapper = mapper;
this.number = number;
}
@Override
public TokenStream tokenStream(Analyzer analyzer) throws IOException {
if (fieldType().indexed()) {
return mapper.popCachedStream().setIntValue(number);
}
return null;
}
@Override
public String numericAsString() {
return Integer.toString(number);
}
}
}
| {
"content_hash": "34d9302a82116cedf6384d129eb31a73",
"timestamp": "",
"source": "github",
"line_count": 371,
"max_line_length": 181,
"avg_line_length": 39.05390835579515,
"alnum_prop": 0.6183311477672717,
"repo_name": "synhershko/elasticsearch",
"id": "aaa045c06483d27fe33a916cee171dba5fbe3b3c",
"size": "15294",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/elasticsearch/index/mapper/core/IntegerFieldMapper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "14603640"
},
{
"name": "Shell",
"bytes": "12355"
}
],
"symlink_target": ""
} |
<?php
/*
* GENERATED CODE WARNING
* This file was generated from the file
* https://github.com/google/googleapis/blob/master/google/devtools/clouderrorreporting/v1beta1/error_stats_service.proto
* and updates to that file get reflected here through a refresh process.
*/
namespace Google\Cloud\Errorreporting\V1beta1;
use Google\GAX\AgentHeaderDescriptor;
use Google\GAX\ApiCallable;
use Google\GAX\CallSettings;
use Google\GAX\GrpcConstants;
use Google\GAX\GrpcCredentialsHelper;
use Google\GAX\PageStreamingDescriptor;
use Google\GAX\PathTemplate;
use google\devtools\clouderrorreporting\v1beta1\DeleteEventsRequest;
use google\devtools\clouderrorreporting\v1beta1\ErrorGroupOrder;
use google\devtools\clouderrorreporting\v1beta1\ErrorStatsServiceClient;
use google\devtools\clouderrorreporting\v1beta1\ListEventsRequest;
use google\devtools\clouderrorreporting\v1beta1\ListGroupStatsRequest;
use google\devtools\clouderrorreporting\v1beta1\QueryTimeRange;
use google\devtools\clouderrorreporting\v1beta1\ServiceContextFilter;
use google\devtools\clouderrorreporting\v1beta1\TimedCountAlignment;
use google\protobuf\Duration;
use google\protobuf\Timestamp;
/**
* Service Description: An API for retrieving and managing error statistics as well as data for
* individual events.
*
* This class provides the ability to make remote calls to the backing service through method
* calls that map to API methods. Sample code to get started:
*
* ```
* try {
* $errorStatsServiceApi = new ErrorStatsServiceApi();
* $formattedProjectName = ErrorStatsServiceApi::formatProjectName("[PROJECT]");
* $timeRange = new QueryTimeRange();
* foreach ($errorStatsServiceApi->listGroupStats($formattedProjectName, $timeRange) as $element) {
* // doThingsWith(element);
* }
* } finally {
* if (isset($errorStatsServiceApi)) {
* $errorStatsServiceApi->close();
* }
* }
* ```
*
* Many parameters require resource names to be formatted in a particular way. To assist
* with these names, this class includes a format method for each type of name, and additionally
* a parse method to extract the individual identifiers contained within names that are
* returned.
*/
class ErrorStatsServiceApi
{
/**
* The default address of the service.
*/
const SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com';
/**
* The default port of the service.
*/
const DEFAULT_SERVICE_PORT = 443;
/**
* The default timeout for non-retrying methods.
*/
const DEFAULT_TIMEOUT_MILLIS = 30000;
const _GAX_VERSION = '0.1.0';
const _CODEGEN_NAME = 'GAPIC';
const _CODEGEN_VERSION = '0.0.0';
private static $projectNameTemplate;
private $grpcCredentialsHelper;
private $errorStatsServiceStub;
private $scopes;
private $defaultCallSettings;
private $descriptors;
/**
* Formats a string containing the fully-qualified path to represent
* a project resource.
*/
public static function formatProjectName($project)
{
return self::getProjectNameTemplate()->render([
'project' => $project,
]);
}
/**
* Parses the project from the given fully-qualified path which
* represents a project resource.
*/
public static function parseProjectFromProjectName($projectName)
{
return self::getProjectNameTemplate()->match($projectName)['project'];
}
private static function getProjectNameTemplate()
{
if (self::$projectNameTemplate == null) {
self::$projectNameTemplate = new PathTemplate('projects/{project}');
}
return self::$projectNameTemplate;
}
private static function getPageStreamingDescriptors()
{
$listGroupStatsPageStreamingDescriptor =
new PageStreamingDescriptor([
'requestPageTokenField' => 'page_token',
'requestPageSizeField' => 'page_size',
'responsePageTokenField' => 'next_page_token',
'resourceField' => 'error_group_stats',
]);
$listEventsPageStreamingDescriptor =
new PageStreamingDescriptor([
'requestPageTokenField' => 'page_token',
'requestPageSizeField' => 'page_size',
'responsePageTokenField' => 'next_page_token',
'resourceField' => 'error_events',
]);
$pageStreamingDescriptors = [
'listGroupStats' => $listGroupStatsPageStreamingDescriptor,
'listEvents' => $listEventsPageStreamingDescriptor,
];
return $pageStreamingDescriptors;
}
// TODO(garrettjones): add channel (when supported in gRPC)
/**
* Constructor.
*
* @param array $options {
* Optional. Options for configuring the service API wrapper.
*
* @type string $serviceAddress The domain name of the API remote host.
* Default 'clouderrorreporting.googleapis.com'.
* @type mixed $port The port on which to connect to the remote host. Default 443.
* @type Grpc\ChannelCredentials $sslCreds
* A `ChannelCredentials` for use with an SSL-enabled channel.
* Default: a credentials object returned from
* Grpc\ChannelCredentials::createSsl()
* @type array $scopes A string array of scopes to use when acquiring credentials.
* Default the scopes for the Stackdriver Error Reporting API.
* @type array $retryingOverride
* An associative array of string => RetryOptions, where the keys
* are method names (e.g. 'createFoo'), that overrides default retrying
* settings. A value of null indicates that the method in question should
* not retry.
* @type int $timeoutMillis The timeout in milliseconds to use for calls
* that don't use retries. For calls that use retries,
* set the timeout in RetryOptions.
* Default: 30000 (30 seconds)
* @type string $appName The codename of the calling service. Default 'gax'.
* @type string $appVersion The version of the calling service.
* Default: the current version of GAX.
* @type Google\Auth\CredentialsLoader $credentialsLoader
* A CredentialsLoader object created using the
* Google\Auth library.
* }
*/
public function __construct($options = [])
{
$defaultScopes = [
'https://www.googleapis.com/auth/cloud-platform',
];
$defaultOptions = [
'serviceAddress' => self::SERVICE_ADDRESS,
'port' => self::DEFAULT_SERVICE_PORT,
'scopes' => $defaultScopes,
'retryingOverride' => null,
'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS,
'appName' => 'gax',
'appVersion' => self::_GAX_VERSION,
'credentialsLoader' => null,
];
$options = array_merge($defaultOptions, $options);
$headerDescriptor = new AgentHeaderDescriptor([
'clientName' => $options['appName'],
'clientVersion' => $options['appVersion'],
'codeGenName' => self::_CODEGEN_NAME,
'codeGenVersion' => self::_CODEGEN_VERSION,
'gaxVersion' => self::_GAX_VERSION,
'phpVersion' => phpversion(),
]);
$defaultDescriptors = ['headerDescriptor' => $headerDescriptor];
$this->descriptors = [
'listGroupStats' => $defaultDescriptors,
'listEvents' => $defaultDescriptors,
'deleteEvents' => $defaultDescriptors,
];
$pageStreamingDescriptors = self::getPageStreamingDescriptors();
foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) {
$this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor;
}
// TODO load the client config in a more package-friendly way
// https://github.com/googleapis/toolkit/issues/332
$clientConfigJsonString = file_get_contents(__DIR__.'/resources/error_stats_service_client_config.json');
$clientConfig = json_decode($clientConfigJsonString, true);
$this->defaultCallSettings =
CallSettings::load(
'google.devtools.clouderrorreporting.v1beta1.ErrorStatsService',
$clientConfig,
$options['retryingOverride'],
GrpcConstants::getStatusCodeNames(),
$options['timeoutMillis']
);
$this->scopes = $options['scopes'];
$createStubOptions = [];
if (!empty($options['sslCreds'])) {
$createStubOptions['sslCreds'] = $options['sslCreds'];
}
$grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions);
$this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions);
$createErrorStatsServiceStubFunction = function ($hostname, $opts) {
return new ErrorStatsServiceClient($hostname, $opts);
};
$this->errorStatsServiceStub = $this->grpcCredentialsHelper->createStub(
$createErrorStatsServiceStubFunction,
$options['serviceAddress'],
$options['port'],
$createStubOptions
);
}
/**
* Lists the specified groups.
*
* Sample code:
* ```
* try {
* $errorStatsServiceApi = new ErrorStatsServiceApi();
* $formattedProjectName = ErrorStatsServiceApi::formatProjectName("[PROJECT]");
* $timeRange = new QueryTimeRange();
* foreach ($errorStatsServiceApi->listGroupStats($formattedProjectName, $timeRange) as $element) {
* // doThingsWith(element);
* }
* } finally {
* if (isset($errorStatsServiceApi)) {
* $errorStatsServiceApi->close();
* }
* }
* ```
*
* @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written
* as <code>projects/</code> plus the
* <a href="https://support.google.com/cloud/answer/6158840">Google Cloud
* Platform project ID</a>.
*
* Example: <code>projects/my-project-123</code>.
* @param QueryTimeRange $timeRange [Required] List data for the given time range.
* Only <code>ErrorGroupStats</code> with a non-zero count in the given time
* range are returned, unless the request contains an explicit group_id list.
* If a group_id list is given, also <code>ErrorGroupStats</code> with zero
* occurrences are returned.
* @param array $optionalArgs {
* Optional.
*
* @type string[] $groupId
* [Optional] List all <code>ErrorGroupStats</code> with these IDs.
* @type ServiceContextFilter $serviceFilter
* [Optional] List only <code>ErrorGroupStats</code> which belong to a service
* context that matches the filter.
* Data for all service contexts is returned if this field is not specified.
* @type Duration $timedCountDuration
* [Optional] The preferred duration for a single returned `TimedCount`.
* If not set, no timed counts are returned.
* @type TimedCountAlignment $alignment
* [Optional] The alignment of the timed counts to be returned.
* Default is `ALIGNMENT_EQUAL_AT_END`.
* @type Timestamp $alignmentTime
* [Optional] Time where the timed counts shall be aligned if rounded
* alignment is chosen. Default is 00:00 UTC.
* @type ErrorGroupOrder $order
* [Optional] The sort order in which the results are returned.
* Default is `COUNT_DESC`.
* @type int $pageSize
* The maximum number of resources contained in the underlying API
* response. The API may return fewer values in a page, even if
* there are additional values to be retrieved.
* @type string $pageToken
* A page token is used to specify a page of values to be returned.
* If no page token is specified (the default), the first page
* of values will be returned. Any page token used here must have
* been generated by a previous call to the API.
* @type Google\GAX\RetrySettings $retrySettings
* Retry settings to use for this call. If present, then
* $timeoutMillis is ignored.
* @type int $timeoutMillis
* Timeout to use for this call. Only used if $retrySettings
* is not set.
* }
*
* @return Google\GAX\PagedListResponse
*
* @throws Google\GAX\ApiException if the remote call fails
*/
public function listGroupStats($projectName, $timeRange, $optionalArgs = [])
{
$request = new ListGroupStatsRequest();
$request->setProjectName($projectName);
$request->setTimeRange($timeRange);
if (isset($optionalArgs['groupId'])) {
foreach ($optionalArgs['groupId'] as $elem) {
$request->addGroupId($elem);
}
}
if (isset($optionalArgs['serviceFilter'])) {
$request->setServiceFilter($optionalArgs['serviceFilter']);
}
if (isset($optionalArgs['timedCountDuration'])) {
$request->setTimedCountDuration($optionalArgs['timedCountDuration']);
}
if (isset($optionalArgs['alignment'])) {
$request->setAlignment($optionalArgs['alignment']);
}
if (isset($optionalArgs['alignmentTime'])) {
$request->setAlignmentTime($optionalArgs['alignmentTime']);
}
if (isset($optionalArgs['order'])) {
$request->setOrder($optionalArgs['order']);
}
if (isset($optionalArgs['pageSize'])) {
$request->setPageSize($optionalArgs['pageSize']);
}
if (isset($optionalArgs['pageToken'])) {
$request->setPageToken($optionalArgs['pageToken']);
}
$mergedSettings = $this->defaultCallSettings['listGroupStats']->merge(
new CallSettings($optionalArgs)
);
$callable = ApiCallable::createApiCall(
$this->errorStatsServiceStub,
'ListGroupStats',
$mergedSettings,
$this->descriptors['listGroupStats']
);
return $callable(
$request,
[],
['call_credentials_callback' => $this->createCredentialsCallback()]);
}
/**
* Lists the specified events.
*
* Sample code:
* ```
* try {
* $errorStatsServiceApi = new ErrorStatsServiceApi();
* $formattedProjectName = ErrorStatsServiceApi::formatProjectName("[PROJECT]");
* $groupId = "";
* foreach ($errorStatsServiceApi->listEvents($formattedProjectName, $groupId) as $element) {
* // doThingsWith(element);
* }
* } finally {
* if (isset($errorStatsServiceApi)) {
* $errorStatsServiceApi->close();
* }
* }
* ```
*
* @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written
* as `projects/` plus the
* [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840).
* Example: `projects/my-project-123`.
* @param string $groupId [Required] The group for which events shall be returned.
* @param array $optionalArgs {
* Optional.
*
* @type ServiceContextFilter $serviceFilter
* [Optional] List only ErrorGroups which belong to a service context that
* matches the filter.
* Data for all service contexts is returned if this field is not specified.
* @type QueryTimeRange $timeRange
* [Optional] List only data for the given time range.
* @type int $pageSize
* The maximum number of resources contained in the underlying API
* response. The API may return fewer values in a page, even if
* there are additional values to be retrieved.
* @type string $pageToken
* A page token is used to specify a page of values to be returned.
* If no page token is specified (the default), the first page
* of values will be returned. Any page token used here must have
* been generated by a previous call to the API.
* @type Google\GAX\RetrySettings $retrySettings
* Retry settings to use for this call. If present, then
* $timeoutMillis is ignored.
* @type int $timeoutMillis
* Timeout to use for this call. Only used if $retrySettings
* is not set.
* }
*
* @return Google\GAX\PagedListResponse
*
* @throws Google\GAX\ApiException if the remote call fails
*/
public function listEvents($projectName, $groupId, $optionalArgs = [])
{
$request = new ListEventsRequest();
$request->setProjectName($projectName);
$request->setGroupId($groupId);
if (isset($optionalArgs['serviceFilter'])) {
$request->setServiceFilter($optionalArgs['serviceFilter']);
}
if (isset($optionalArgs['timeRange'])) {
$request->setTimeRange($optionalArgs['timeRange']);
}
if (isset($optionalArgs['pageSize'])) {
$request->setPageSize($optionalArgs['pageSize']);
}
if (isset($optionalArgs['pageToken'])) {
$request->setPageToken($optionalArgs['pageToken']);
}
$mergedSettings = $this->defaultCallSettings['listEvents']->merge(
new CallSettings($optionalArgs)
);
$callable = ApiCallable::createApiCall(
$this->errorStatsServiceStub,
'ListEvents',
$mergedSettings,
$this->descriptors['listEvents']
);
return $callable(
$request,
[],
['call_credentials_callback' => $this->createCredentialsCallback()]);
}
/**
* Deletes all error events of a given project.
*
* Sample code:
* ```
* try {
* $errorStatsServiceApi = new ErrorStatsServiceApi();
* $formattedProjectName = ErrorStatsServiceApi::formatProjectName("[PROJECT]");
* $response = $errorStatsServiceApi->deleteEvents($formattedProjectName);
* } finally {
* if (isset($errorStatsServiceApi)) {
* $errorStatsServiceApi->close();
* }
* }
* ```
*
* @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written
* as `projects/` plus the
* [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840).
* Example: `projects/my-project-123`.
* @param array $optionalArgs {
* Optional.
*
* @type Google\GAX\RetrySettings $retrySettings
* Retry settings to use for this call. If present, then
* $timeoutMillis is ignored.
* @type int $timeoutMillis
* Timeout to use for this call. Only used if $retrySettings
* is not set.
* }
*
* @return google\devtools\clouderrorreporting\v1beta1\DeleteEventsResponse
*
* @throws Google\GAX\ApiException if the remote call fails
*/
public function deleteEvents($projectName, $optionalArgs = [])
{
$request = new DeleteEventsRequest();
$request->setProjectName($projectName);
$mergedSettings = $this->defaultCallSettings['deleteEvents']->merge(
new CallSettings($optionalArgs)
);
$callable = ApiCallable::createApiCall(
$this->errorStatsServiceStub,
'DeleteEvents',
$mergedSettings,
$this->descriptors['deleteEvents']
);
return $callable(
$request,
[],
['call_credentials_callback' => $this->createCredentialsCallback()]);
}
/**
* Initiates an orderly shutdown in which preexisting calls continue but new
* calls are immediately cancelled.
*/
public function close()
{
$this->errorStatsServiceStub->close();
}
private function createCredentialsCallback()
{
return $this->grpcCredentialsHelper->createCallCredentialsCallback();
}
}
| {
"content_hash": "30b78729588c94dc066527143dcd6bdf",
"timestamp": "",
"source": "github",
"line_count": 521,
"max_line_length": 121,
"avg_line_length": 41.16698656429942,
"alnum_prop": 0.594414397612831,
"repo_name": "geigerj/api-client-staging",
"id": "ac61f58809ad5fffe2c37ac35cb82c9edeee81b1",
"size": "22053",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "generated/php/google-devtools-clouderrorreporting-v1beta1/src/Errorreporting/V1beta1/ErrorStatsServiceApi.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Go",
"bytes": "184253"
},
{
"name": "Java",
"bytes": "839668"
},
{
"name": "JavaScript",
"bytes": "289666"
},
{
"name": "PHP",
"bytes": "311136"
},
{
"name": "Python",
"bytes": "514799"
},
{
"name": "Ruby",
"bytes": "450035"
}
],
"symlink_target": ""
} |
<p class="description">Gerencie rapidamente o leiaute, o alinhamento e o dimensionamento de colunas de grade, navegação, componentes e muito mais com um conjunto completo de utilitários flexbox responsivos.</p>
Se você é **novo ou não está familiarizado com o flexbox**, nós recomendamos você a ler este [guia do Flexbox CSS-Tricks](https://css-tricks.com/snippets/css/a-guide-to-flexbox/).
## Propriedades para o pai
### display
{{"demo": "pages/system/flexbox/Display.js", "defaultCodeOpen": false, "bg": true}}
```jsx
<Box sx={{ display: 'flex' }}>…
```
### flex-direction
{{"demo": "pages/system/flexbox/FlexDirection.js", "defaultCodeOpen": false, "bg": true}}
```jsx
<Box flexDirection="row">…
<Box flexDirection="row">…
<Box sx={{ flexDirection: 'row' }}>…
<Box flexDirection="row">…
<Box flexDirection="row">…
<Box sx={{ flexDirection: 'row-reverse' }}>…
<Box flexDirection="row">…
<Box flexDirection="row">…
<Box sx={{ flexDirection: 'row-reverse' }}>…
```
### flex-wrap
{{"demo": "pages/system/flexbox/FlexWrap.js", "defaultCodeOpen": false, "bg": true}}
```jsx
<Box sx={{ flexWrap: 'nowrap' }}>…
<Box sx={{ flexWrap: 'nowrap' }}>…
<Box flexWrap="nowrap">…
<Box flexWrap="nowrap">…
<Box sx={{ flexWrap: 'wrap' }}>…
```
### justify-content
{{"demo": "pages/system/flexbox/JustifyContent.js", "defaultCodeOpen": false, "bg": true}}
```jsx
<Box sx={{ justifyContent: 'flex-start' }}>…
<Box justifyContent="flex-end">…
<Box justifyContent="center">…
<Box justifyContent="flex-end">…
<Box justifyContent="center">…
<Box sx={{ justifyContent: 'flex-end' }}>…
<Box sx={{ justifyContent: 'flex-start' }}>…
<Box justifyContent="flex-end">…
<Box justifyContent="center">…
<Box justifyContent="flex-end">…
<Box justifyContent="center">…
<Box sx={{ justifyContent: 'flex-end' }}>…
<Box sx={{ justifyContent: 'center' }}>…
<Box justifyContent="flex-end">…
<Box justifyContent="center">…
<Box justifyContent="flex-end">…
<Box justifyContent="center">…
```
### align-items
{{"demo": "pages/system/flexbox/AlignItems.js", "defaultCodeOpen": false, "bg": true}}
```jsx
<Box sx={{ alignItems: 'flex-start' }}>…
<Box alignItems="flex-end">…
<Box alignItems="flex-start">…
<Box alignItems="flex-end">…
<Box alignItems="center">…
<Box sx={{ alignItems: 'flex-end' }}>…
<Box sx={{ alignItems: 'flex-start' }}>…
<Box alignItems="flex-end">…
<Box alignItems="flex-start">…
<Box alignItems="flex-end">…
<Box alignItems="center">…
<Box sx={{ alignItems: 'flex-end' }}>…
<Box alignItems="flex-start">…
<Box alignItems="flex-end">…
<Box sx={{ alignItems: 'center' }}>…
```
### align-content
{{"demo": "pages/system/flexbox/AlignContent.js", "defaultCodeOpen": false, "bg": true}}
```jsx
<Box sx={{ alignContent: 'flex-start' }}>…
<Box alignContent="flex-end">…
<Box alignContent="flex-end">…
<Box sx={{ alignContent: 'flex-end' }}>…
<Box sx={{ alignContent: 'flex-end' }}>…
```
## Propriedades para os Filhos
### order
{{"demo": "pages/system/flexbox/Order.js", "defaultCodeOpen": false, "bg": true}}
```jsx
<Box sx={{ order: 2 }}>Item 1</Box>
<Box sx={{ order: 3 }}>Item 2</Box>
<Box sx={{ order: 1 }}>Item 3</Box>
```
### flex-grow
{{"demo": "pages/system/flexbox/FlexGrow.js", "defaultCodeOpen": false, "bg": true}}
```jsx
<Box sx={{ flexGrow: 1 }}>Item 1</Box>
<Box>Item 2</Box>
<Box>Item 3</Box>
```
### flex-shrink
{{"demo": "pages/system/flexbox/FlexShrink.js", "defaultCodeOpen": false, "bg": true}}
```jsx
<Box sx={{ width: '100%' }}>Item 1</Box>
<Box sx={{ flexShrink: 1 }}>Item 2</Box>
<Box sx={{ flexShrink: 0 }}>Item 3</Box>
```
### align-self
{{"demo": "pages/system/flexbox/AlignSelf.js", "defaultCodeOpen": false, "bg": true}}
```jsx
<Box>Item 1</Box>
<Box sx={{ alignSelf: 'flex-end' }}>Item 2</Box>
<Box>Item 3</Box>
```
## API
```js
import { flexbox } from '@material-ui/system';
```
| Nome da importação | Propriedade | Propriedade CSS | Chave do tema |
|:------------------ |:---------------- |:----------------- |:------------- |
| `flexDirection` | `flexDirection` | `flex-direction` | none |
| `flexWrap` | `flexWrap` | `flex-wrap` | none |
| `justifyContent` | `justifyContent` | `justify-content` | none |
| `alignItems` | `alignItems` | `align-items` | none |
| `alignContent` | `alignContent` | `align-content` | none |
| `order` | `order` | `order` | none |
| `flex` | `flex` | `flex` | none |
| `flexGrow` | `flexGrow` | `flex-grow` | none |
| `flexShrink` | `flexShrink` | `flex-shrink` | none |
| `alignSelf` | `alignSelf` | `align-self` | none |
| {
"content_hash": "f66467dc9258f3272a55072fca745ac6",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 210,
"avg_line_length": 29.73125,
"alnum_prop": 0.5991170906033214,
"repo_name": "callemall/material-ui",
"id": "cecba72e46622c71bdbd8ad180e9864bfa849be1",
"size": "4883",
"binary": false,
"copies": "1",
"ref": "refs/heads/next",
"path": "docs/src/pages/system/flexbox/flexbox-pt.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "302"
},
{
"name": "JavaScript",
"bytes": "1758519"
},
{
"name": "Shell",
"bytes": "144"
},
{
"name": "TypeScript",
"bytes": "27469"
}
],
"symlink_target": ""
} |
'use strict';
/**
* Module dependencies
*/
var blogsPolicy = require('../policies/blogs.server.policy'),
blogs = require('../controllers/blogs.server.controller'),
comments = require('../controllers/comments.server.controller');
module.exports = function(app) {
// Blogs Routes
app.route('/api/blogs').all(blogsPolicy.isAllowed)
.get(blogs.list)
.post(blogs.create);
app.route('/api/blogs/:blogId').all(blogsPolicy.isAllowed)
.get(blogs.read)
.put(blogs.update)
.delete(blogs.delete);
// Finish by binding the Blog middleware
app.param('blogId', blogs.blogByID);
app.route('/api/addcomment')
.post(comments.add);
app.route('/api/acomment')
.post(comments.acomment);
app.route('/api/rcomment')
.post(comments.rcomment);
};
| {
"content_hash": "35ba8c4687465fecda9e93fbc8a069cf",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 66,
"avg_line_length": 23.87878787878788,
"alnum_prop": 0.6713197969543148,
"repo_name": "AmirMustafa/Blog-Application",
"id": "715c5660b47b4addcc9c8cf3440fee47e3337c76",
"size": "788",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/blogs/server/routes/blogs.server.routes.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1528"
},
{
"name": "HTML",
"bytes": "48032"
},
{
"name": "JavaScript",
"bytes": "334257"
},
{
"name": "Shell",
"bytes": "685"
}
],
"symlink_target": ""
} |
module AuditScopable
extend ActiveSupport::Concern
included do
scope :created_n_days_ago,
->(n) { where("current_date - created_at::date = ?", n) }
scope :updated_n_days_ago,
->(n) { where("current_date - updated_at::date = ?", n) }
scope :xchanged_n_days_ago,
(lambda do |n|
where(["current_date - created_at::date = ? or
current_date - updated_at::date = ?", n, n])
end)
scope :created_in_the_last_n_days,
->(n) { where("current_date - created_at::date < ?", n) }
scope :updated_in_the_last_n_days,
->(n) { where("current_date - updated_at::date < ?", n) }
scope :changed_in_the_last_n_days,
(lambda do |n|
where(["current_date - created_at::date < ? or
current_date - updated_at::date < ?", n, n])
end)
end
def fresh?
created_at > 1.hour.ago
end
def self.created_in_the_last(amount = 1, time_unit = "hour")
where("created_at > now() - interval '#{amount} #{time_unit}'")
end
end
| {
"content_hash": "a4b1a851113b2ecb900fc2955f6930e9",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 68,
"avg_line_length": 34.74193548387097,
"alnum_prop": 0.5329619312906221,
"repo_name": "bio-org-au/nsl-editor",
"id": "60a8430b560281eea2ca4821d73826a9eb75d1fd",
"size": "1123",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/concerns/audit_scopable.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "53964"
},
{
"name": "CoffeeScript",
"bytes": "32497"
},
{
"name": "Dockerfile",
"bytes": "658"
},
{
"name": "HTML",
"bytes": "724160"
},
{
"name": "JavaScript",
"bytes": "82408"
},
{
"name": "PLpgSQL",
"bytes": "181444"
},
{
"name": "Ruby",
"bytes": "2827413"
},
{
"name": "SQLPL",
"bytes": "169"
},
{
"name": "Shell",
"bytes": "1496"
},
{
"name": "TSQL",
"bytes": "16000"
}
],
"symlink_target": ""
} |
#ifndef ASVECTOR_HEADER_FILE_INCLUDED
#define ASVECTOR_HEADER_FILE_INCLUDED
#ifdef __cplusplus
extern "C" {
#endif
typedef struct ASVector
{
void *memory ;
size_t allocated, used ;
size_t unit ;
}ASVector;
#define DECL_VECTOR(t,v) ASVector v = {NULL,0,0,sizeof(t)}
#define DECL_VECTOR_RAW(v) ASVector v = {NULL,0,0,1}
#define VECTOR_HEAD(t,v) ((t*)((v).memory))
#define PVECTOR_HEAD(t,v) ((t*)((v)->memory))
#define VECTOR_HEAD_RAW(v) ((v).memory)
#define VECTOR_TAIL(t,v) (((t*)((v).memory)) + ((v).used))
#define PVECTOR_TAIL(t,v) (((t*)((v)->memory)) + ((v)->used))
#define VECTOR_TAIL_RAW(v) (((v).memory) + ((v).used*(v).unit))
#define VECTOR_USED(v) ((v).used)
#define VECTOR_UNIT(v) ((v).unit)
#define PVECTOR_USED(v) ((v)->used)
#define PVECTOR_UNIT(v) ((v)->unit)
ASVector *create_asvector( size_t unit );
void destroy_asvector( ASVector **v );
/* return memory starting address : */
void *alloc_vector( ASVector *v, size_t new_size );
void *realloc_vector( ASVector *v, size_t new_size );
/* If append_vector is used with data == NULL it will only allocate
additional space, but will not copy any data.
Returns self : */
ASVector *append_vector( ASVector *v, void * data, size_t size );
/* returns index on success, -1 on failure */
int vector_insert_elem( ASVector *v, void *data, size_t size, void *sibling, int before );
int vector_relocate_elem (ASVector *v, unsigned int index, unsigned int new_index);
inline size_t vector_find_data (ASVector *v, void *data );
int vector_find_elem( ASVector *v, void *data );
/* returns 1 on success, 0 on failure */
int vector_remove_elem( ASVector *v, void *data );
int vector_remove_index( ASVector *v, size_t index );
void
print_vector( stream_func func, void* stream, ASVector *v, char *name, void (*print_func)( stream_func func, void* stream, void *data ) );
/* returns nothing : */
void flush_vector( ASVector *v ); /* reset used to 0 */
void free_vector( ASVector *v ); /* free all memory used, except for object itself */
#ifdef __cplusplus
}
#endif
#endif /* #ifndef ASVECTOR_HEADER_FILE_INCLUDED */
| {
"content_hash": "e60977a4290da5d6fa301a4e78a784bd",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 138,
"avg_line_length": 35.483333333333334,
"alnum_prop": 0.6632221700328793,
"repo_name": "born2late/afterstep-devel",
"id": "242bbb8a2c4aec99ac5b81832a15eadcd6e87216",
"size": "2129",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "libAfterBase/asvector.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "8783905"
},
{
"name": "C++",
"bytes": "39829"
},
{
"name": "CSS",
"bytes": "2853"
},
{
"name": "Groff",
"bytes": "91779"
},
{
"name": "Logos",
"bytes": "19847"
},
{
"name": "Makefile",
"bytes": "103769"
},
{
"name": "Mask",
"bytes": "2535"
},
{
"name": "Objective-C",
"bytes": "7817"
},
{
"name": "Perl",
"bytes": "14704"
},
{
"name": "Perl6",
"bytes": "507"
},
{
"name": "Shell",
"bytes": "125314"
},
{
"name": "XS",
"bytes": "13098"
}
],
"symlink_target": ""
} |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* InventoryStatus.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v202208;
public class InventoryStatus implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected InventoryStatus(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _ACTIVE = "ACTIVE";
public static final java.lang.String _INACTIVE = "INACTIVE";
public static final java.lang.String _ARCHIVED = "ARCHIVED";
public static final InventoryStatus ACTIVE = new InventoryStatus(_ACTIVE);
public static final InventoryStatus INACTIVE = new InventoryStatus(_INACTIVE);
public static final InventoryStatus ARCHIVED = new InventoryStatus(_ARCHIVED);
public java.lang.String getValue() { return _value_;}
public static InventoryStatus fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
InventoryStatus enumeration = (InventoryStatus)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static InventoryStatus fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(InventoryStatus.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202208", "InventoryStatus"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
| {
"content_hash": "cc5c156faf81aa0ee4fa1e5ba19a1713",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 131,
"avg_line_length": 40.45348837209303,
"alnum_prop": 0.6935901121011785,
"repo_name": "googleads/googleads-java-lib",
"id": "7d6fd4fe546bad88e1972d8b483e3f40fd334ba3",
"size": "3479",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202208/InventoryStatus.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "81068791"
}
],
"symlink_target": ""
} |
define([
'underscore',
'knockback',
'contrail-view',
'contrail-list-model',
'monitor/infrastructure/controlnode/ui/js/models/ControlNodeRoutesModel'
//Remove all query references once it is moved to core
], function (_, Knockback, ContrailView, ContrailListModel, ControlNodeRoutesModel) {
var routingInstancesDropdownList = [{text:'All',value:'All'}],
backwardRouteStack = [], forwardRouteStack = [], filteredPrefix = '',
routInstance = '', showRouteStack;
var ControlNodeRoutesFormView = ContrailView.extend({
render: function (options) {
var self = this, viewConfig = self.attributes.viewConfig,
hostname = viewConfig['hostname'],
prefix = 'controlroutes',
routesTmpl = contrail.getTemplate4Id(
ctwc.TMPL_FORM_RESULT),
controlNodeRoutesModel = new ControlNodeRoutesModel(),
widgetConfig = contrail.checkIfExist(viewConfig.widgetConfig) ?
viewConfig.widgetConfig : null,
routesFormId = "#" + prefix + "-form";
monitorInfraUtils.appendHostNameInWidgetTitleForUnderlayPage(viewConfig);
self.model = controlNodeRoutesModel;
self.$el.append(routesTmpl({prefix: prefix}));
var remoteAjaxConfig = {
remote: {
ajaxConfig: {
url: contrail.format(monitorInfraConstants.
monitorInfraUrls['CONTROLNODE_ROUTE_INST_LIST'],
hostname),
type: "GET",
},
dataParser: parseRoutingInstanceResp
},
cacheConfig: {
}
};
var routingInstanceListModel = new ContrailListModel(remoteAjaxConfig);
routingInstanceListModel.onDataUpdate.subscribe(function(){
self.model.routingInstanceOptionList(routingInstanceListModel.getItems());
})
self.renderView4Config($(self.$el).find(routesFormId),
this.model,
self.getViewConfig(options,viewConfig,routingInstanceListModel),
null,
null,
null,
function () {
self.model.showErrorAttr(prefix + '-container',
false);
Knockback.applyBindings(self.model,
document.getElementById(prefix + '-container'));
kbValidation.bind(self);
self.renderQueryResult(viewConfig);
$("#run_query").on('click', function() {
self.renderQueryResult(viewConfig);
});
}
);
if (widgetConfig !== null) {
self.renderView4Config($(self.$el).find(routesFormId),
self.model, widgetConfig, null, null, null);
}
},
renderQueryResult: function(viewConfig) {
var self = this,
prefix = 'controlroutes',
hostname = viewConfig['hostname'],
queryResultId = "#" + prefix + "-results",
responseViewConfig = {
elementId: ctwl.CONTROLNODE_ROUTES_RESULT_VIEW,
view: "ControlRoutesResultView",
viewPathPrefix: ctwl.CONTROLNODE_VIEWPATH_PREFIX,
app: cowc.APP_CONTRAIL_CONTROLLER,
viewConfig: viewConfig
};
//Making the Routes call here as the result also needs to be update
//prefix value in this form
var routesQueryString = self.model.getControlRoutesQueryString();
if(routesQueryString.prefix !== undefined){
filteredPrefix = routesQueryString.prefix;
}else{
filteredPrefix = '';
}
if(routesQueryString.routingInst !== undefined){
routInstance = routesQueryString.routingInst;
}else{
routInstance = '';
}
var routesRemoteConfig = {
url: monitorInfraConstants.
monitorInfraUrls['CONTROLNODE_ROUTES'] +
'?ip=' + hostname +
'&' + $.param(routesQueryString),
type: 'GET'
};
var listModelConfig = {
remote : {
ajaxConfig : routesRemoteConfig,
dataParser : function (response) {
var selValues = {};
showRouteStack = undefined;
backwardRouteStack = []; forwardRouteStack = [];
var parsedData = monitorInfraParsers.
parseRoutes(response,routesQueryString);
if(getValueByJsonPath(response[0],'ShowRouteResp;tables;list','') !== ''){
backwardRoutes(response);
forwardRoutes(response);
}
var prefixList = [];
$.each(parsedData,function(i,d){
prefixList.push({text:d.dispPrefix,value:d.dispPrefix});
});
self.model.prefixOptionList(prefixList);
return parsedData;
}
},
cacheConfig : {
// ucid: ctwc.CACHE_CONFIGNODE
}
};
var backwardRoutes = function(model){
var routingTable, showRoute, routingInstance, prefix;
var showRouteTable = getValueByJsonPath(model[0],'ShowRouteResp;tables;list;ShowRouteTable',{});
if(showRouteTable.constructor().length === undefined){
routingTable = showRouteTable.routing_table_name;
routingInstance = showRouteTable.routing_instance;
showRoute = showRouteTable.routes.list.ShowRoute;
}else{
routingTable = showRouteTable[0].routing_table_name;
routingInstance = showRouteTable[0].routing_instance;
showRoute = showRouteTable[0].routes.list.ShowRoute
}
if(showRoute.constructor().length === undefined){
prefix = showRoute.prefix;
}else{
prefix = showRoute[0].prefix;
}
if(showRouteStack === undefined){
showRouteStack = showRouteTable;
backwardRouteStack.push({
limit: routesQueryString.limit,
startRoutingTable: routingTable,
startRoutingInstance: routingInstance,
startPrefix: prefix,
prefix: filteredPrefix,
routingInst: routInstance
});
}else{
if(!_.isEqual(showRouteStack, showRouteTable)){
showRouteStack = showRouteTable;
backwardRouteStack.push({
limit: routesQueryString.limit,
startRoutingTable: routingTable,
startRoutingInstance: routingInstance,
startPrefix: prefix,
prefix: filteredPrefix,
routingInst: routInstance
});
}
}
};
var forwardRoutes = function(model){
var routingTable, showRoute, routingInstance, prefix;
var showRouteTable = getValueByJsonPath(model[0],'ShowRouteResp;tables;list;ShowRouteTable',{});
if(showRouteTable.constructor().length === undefined){
routingTable = showRouteTable.routing_table_name;
routingInstance = showRouteTable.routing_instance;
showRoute = showRouteTable.routes.list.ShowRoute;
}else{
routingTable = showRouteTable[showRouteTable.length - 1].routing_table_name;
routingInstance = showRouteTable[showRouteTable.length - 1].routing_instance;
showRoute = showRouteTable[showRouteTable.length - 1].routes.list.ShowRoute;
}
if(showRoute.constructor().length === undefined){
prefix = showRoute.prefix;
}else{
prefix = showRoute[showRoute.length - 1].prefix;
}
forwardRouteStack.push({
limit: routesQueryString.limit,
startRoutingTable: routingTable,
startRoutingInstance: routingInstance,
startPrefix: prefix,
prefix: filteredPrefix,
routingInst:routInstance
});
};
var model = new ContrailListModel(listModelConfig);
self.renderView4Config($(self.$el).find(queryResultId),
model, responseViewConfig,null,null,null,function() {
monitorInfraUtils.bindPaginationListeners({
gridSel: $('#' + ctwl.CONTROLNODE_ROUTES_RESULTS),
model: self.model,
obj:viewConfig,
parseFn: function(response) {
backwardRoutes(response);
forwardRoutes(response);
var parsedData = monitorInfraParsers.
parseRoutes(response, routesQueryString);
return parsedData;
},
getUrlFn: function(step) {
var urlparm;
if(step === 'forward' && forwardRouteStack.length !== 0){
urlParm = forwardRouteStack.pop();
return monitorInfraConstants.
monitorInfraUrls['CONTROLNODE_ROUTES'] +
'?ip=' + hostname +
'&' + $.param(urlParm);
}
if(step === 'backward' && backwardRouteStack.length !== 1){
backwardRouteStack.splice(backwardRouteStack.length - 1, 1);
urlParm = backwardRouteStack.pop();
forwardRouteStack.pop();
if(urlParm !== undefined){
return monitorInfraConstants.
monitorInfraUrls['CONTROLNODE_ROUTES'] +
'?ip=' + hostname +
'&' + $.param(urlParm);
}
}
}
});
});
},
getViewConfig: function (options,viewConfig,routingInstanceListModel) {
var self = this;
var hostname = viewConfig['hostname'];
var addressFamilyList = ["All","enet","ermvpn","evpn",
"inet","inetvpn","inet6","l3vpn","rtarget"];
var routeLimits = [10, 50, 100, 200];
$.each(routeLimits,function(idx,obj){
routeLimits[idx] = {'value':obj,'text':obj+' Routes'};
});
routeLimits = [{'text':'All','value':'All'}].concat(routeLimits);
var protocols = ['All','XMPP','BGP','ServiceChain','Static'];
return {
view: "SectionView",
viewConfig: {
rows: [
{
columns: [
{
elementId: 'routing_instance',
view: "FormDropdownView",
viewConfig: {
path: 'routing_instance',
dataBindValue: 'routing_instance',
class: "col-xs-6",
dataBindOptionList: 'routingInstanceOptionList',
elementConfig: {
defaultValueId: 0,
dropdownAutoWidth : false,
dataTextField:'text',
dataValueField:'value'
}
}
},
{
elementId: 'prefix',
view: "FormComboboxView",
viewConfig: {
label:'Prefix',
path: 'prefix',
class: "col-xs-2",
dataBindValue: 'prefix',
dataBindOptionList: 'prefixOptionList',
elementConfig: {
dataTextField: "text",
dataValueField: "value",
placeholder: 'Prefix'
}
}
},
{
elementId: 'routes_limit',
view: "FormDropdownView",
viewConfig: {
path: 'routes_limit',
label: 'Limit',
dataBindValue: 'routes_limit',
class: "col-xs-2",
elementConfig: {
dataTextField: "text",
dataValueField: "value",
data: routeLimits
}
}
}
]
},
/*{
columns: [
{
elementId: 'peer_source',
view: "FormDropdownView",
viewConfig: {
path: 'peer_source',
dataBindValue: 'peer_source',
class: "col-xs-2",
elementConfig: {
dataSource: {
type: 'remote',
url: contrail.format(
monitorInfraConstants.
monitorInfraUrls['CONTROLNODE_PEER_LIST'],
hostname),
parse:function(response){
var ret = ['All']
if(!(response instanceof Array)){
response = [response];
}
ret = ['All'].concat(response);
return ret;
}
}
}
}
},
{
elementId: 'address_family',
view: "FormDropdownView",
viewConfig: {
path: 'address_family',
dataBindValue: 'address_family',
class: "col-xs-2",
elementConfig: {
data: addressFamilyList
}
}
},
{
elementId: 'protocol',
view: "FormDropdownView",
viewConfig: {
path: 'protocol',
dataBindValue: 'protocol',
class: "col-xs-2",
elementConfig: {
data: protocols
}
}
}
]
},*/
{
columns: [
{
elementId: 'run_query',
view: "FormButtonView",
viewConfig: {
label: "Search",
class: 'display-inline-block margin-0-10-0-0',
elementConfig: {
btnClass: 'btn-primary'
}
}
},
{
elementId: 'reset_query',
view: "FormButtonView",
viewConfig: {
label: "Reset",
class: 'display-inline-block margin-0-10-0-0',
elementConfig: {
onClick: "reset"
}
}
}
]
}
]
}
};
}
});
function parseRoutingInstanceResp (response){
routingInstancesDropdownList = [{text:'All',value:'All'}]
if(response != null && response['ShowRoutingInstanceSummaryResp'] != null &&
response['ShowRoutingInstanceSummaryResp']['instances'] != null &&
response['ShowRoutingInstanceSummaryResp']['instances']['list'] != null &&
response['ShowRoutingInstanceSummaryResp']['instances']['list']['ShowRoutingInstance'] != null){
var routingInstances = response['ShowRoutingInstanceSummaryResp']['instances']['list']['ShowRoutingInstance'];
var routingInstancesLength = routingInstances.length;
for(var i = 0; i < routingInstancesLength; i++) {
routingInstancesDropdownList.push({text:routingInstances[i]['name'],value:routingInstances[i]['name']});
}
}
return routingInstancesDropdownList;
}
return ControlNodeRoutesFormView;
});
| {
"content_hash": "213f5688deb0213dd9e5fccf135a2aeb",
"timestamp": "",
"source": "github",
"line_count": 403,
"max_line_length": 122,
"avg_line_length": 51.11414392059553,
"alnum_prop": 0.3822515656099811,
"repo_name": "biswajit-mandal/contrail-web-controller",
"id": "16e9a0fad794b4172e9c65f55f01ca417b1e40d5",
"size": "20671",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "webroot/monitor/infrastructure/controlnode/ui/js/views/ControlNodeRoutesFormView.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "51691"
},
{
"name": "HTML",
"bytes": "10498"
},
{
"name": "JavaScript",
"bytes": "11736517"
},
{
"name": "Shell",
"bytes": "1700"
}
],
"symlink_target": ""
} |
<?php
/**
* DO NOT EDIT!
* This file was automatically generated via bin/generate-validator-spec.php.
*/
namespace AmpProject\Validator\Spec\Error;
use AmpProject\Validator\Spec\Error;
use AmpProject\Validator\Spec\SpecRule;
/**
* Error class InvalidAttrValue.
*
* @package ampproject/amp-toolbox.
*
* @property-read string $format
* @property-read int $specificity
*/
final class InvalidAttrValue extends Error
{
/**
* Code of the error.
*
* @var string
*/
const CODE = 'INVALID_ATTR_VALUE';
/**
* Array of spec data.
*
* @var array{format: string, specificity?: int}
*/
const SPEC = [
SpecRule::FORMAT => 'The attribute \'%1\' in tag \'%2\' is set to the invalid value \'%3\'.',
SpecRule::SPECIFICITY => 26,
];
}
| {
"content_hash": "7840380afb5156e649873e2a21c38c0a",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 101,
"avg_line_length": 20.666666666666668,
"alnum_prop": 0.6215880893300249,
"repo_name": "ampproject/amp-toolbox-php",
"id": "5ee097314513d9d76dd005e1e596af1a87401951",
"size": "806",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/Validator/Spec/Error/InvalidAttrValue.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "1530243"
},
{
"name": "Shell",
"bytes": "653"
}
],
"symlink_target": ""
} |
<query xmlns="http://labkey.org/data/xml/query">
<metadata>
<tables xmlns="http://labkey.org/data/xml">
<table tableName="demographicsAssignments" tableDbType="NOT_IN_DB">
<columns>
<column columnName="Id">
<isKeyField>true</isKeyField>
<isHidden>true</isHidden>
<fk>
<fkDbSchema>study</fkDbSchema>
<fkTable>animal</fkTable>
<fkColumnName>id</fkColumnName>
</fk>
</column>
<column columnName="projects">
<columnTitle>Active Projects</columnTitle>
<displayWidth>110</displayWidth>
<!--<url>/query/executeQuery.view?schemaName=study&-->
<!--query.queryName=Assignment&-->
<!--query.Id~eq=${Id}&-->
<!--query.enddate~isblank&-->
<!--</url>-->
</column>
<column columnName="Availability">
<columnTitle>Availability</columnTitle>
<!--<url>/query/executeQuery.view?schemaName=study&-->
<!--query.queryName=Assignment&-->
<!--query.Id~eq=${Id}&-->
<!--query.project~eq=20070202-->
<!--</url>-->
</column>
</columns>
<titleColumn>projects</titleColumn>
</table>
</tables>
</metadata>
</query>
| {
"content_hash": "785f79e5021450e94b9b181d292e6f9e",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 82,
"avg_line_length": 48.16216216216216,
"alnum_prop": 0.40235690235690236,
"repo_name": "WNPRC-EHR-Services/wnprc-modules",
"id": "7d482da0c899bb64b1596997fe19e6c20305250b",
"size": "1782",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "WNPRC_EHR/resources/queries/study/demographicsAssignments.query.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "82228"
},
{
"name": "Dockerfile",
"bytes": "10292"
},
{
"name": "HTML",
"bytes": "365171"
},
{
"name": "Java",
"bytes": "2064544"
},
{
"name": "JavaScript",
"bytes": "2319537"
},
{
"name": "Perl",
"bytes": "186990"
},
{
"name": "R",
"bytes": "22703"
},
{
"name": "SCSS",
"bytes": "2816"
},
{
"name": "Shell",
"bytes": "18316"
},
{
"name": "TSQL",
"bytes": "332"
},
{
"name": "Twig",
"bytes": "925"
},
{
"name": "TypeScript",
"bytes": "324237"
}
],
"symlink_target": ""
} |
package com.king.photo.util;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;
public class NoScrollGridView extends GridView {
public NoScrollGridView(Context context) {
super(context);
}
public NoScrollGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
| {
"content_hash": "e5f536ec26819bd3da40c2ceec250699",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 72,
"avg_line_length": 26.714285714285715,
"alnum_prop": 0.7825311942959001,
"repo_name": "androidWeq/ItHome",
"id": "678b2a38e8524591cc46876229859cc8c5f813b0",
"size": "561",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/king/photo/util/NoScrollGridView.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "574066"
}
],
"symlink_target": ""
} |
#import "CPTPlot.h"
#import "CPTExceptions.h"
#import "CPTFill.h"
#import "CPTGraph.h"
#import "CPTLegend.h"
#import "CPTLineStyle.h"
#import "CPTMutableNumericData+TypeConversion.h"
#import "CPTMutablePlotRange.h"
#import "CPTPathExtensions.h"
#import "CPTPlotArea.h"
#import "CPTPlotAreaFrame.h"
#import "CPTPlotSpace.h"
#import "CPTPlotSpaceAnnotation.h"
#import "CPTShadow.h"
#import "CPTTextLayer.h"
#import "CPTUtilities.h"
#import "NSCoderExtensions.h"
#import <tgmath.h>
/** @defgroup plotAnimation Plots
* @brief Plot properties that can be animated using Core Animation.
* @if MacOnly
* @since Custom layer property animation is supported on macOS 10.6 and later.
* @endif
* @ingroup animation
**/
/** @defgroup plotAnimationAllPlots All Plots
* @brief Plot properties that can be animated using Core Animation for all plot types.
* @ingroup plotAnimation
**/
/** @if MacOnly
* @defgroup plotBindings Plot Binding Identifiers
* @brief Binding identifiers for all plots.
* @endif
**/
/** @if MacOnly
* @defgroup plotBindingsAllPlots Bindings For All Plots
* @brief Binding identifiers for all plots.
* @ingroup plotBindings
* @endif
**/
CPTPlotBinding const CPTPlotBindingDataLabels = @"dataLabels"; ///< Plot data labels.
/// @cond
@interface CPTPlot()
@property (nonatomic, readwrite, assign) BOOL dataNeedsReloading;
@property (nonatomic, readwrite, strong, nonnull) NSMutableDictionary *cachedData;
@property (nonatomic, readwrite, assign) BOOL needsRelabel;
@property (nonatomic, readwrite, assign) NSRange labelIndexRange;
@property (nonatomic, readwrite, strong, nullable) CPTMutableAnnotationArray *labelAnnotations;
@property (nonatomic, readwrite, copy, nullable) CPTLayerArray *dataLabels;
@property (nonatomic, readwrite, assign) NSUInteger pointingDeviceDownLabelIndex;
@property (nonatomic, readwrite, assign) NSUInteger cachedDataCount;
@property (nonatomic, readwrite, assign) BOOL inTitleUpdate;
@property (nonatomic, readonly, assign) NSUInteger numberOfRecords;
-(nonnull CPTMutableNumericData *)numericDataForNumbers:(nonnull id)numbers;
-(void)setCachedDataType:(CPTNumericDataType)newDataType;
-(void)updateContentAnchorForLabel:(nonnull CPTPlotSpaceAnnotation *)label;
@end
/// @endcond
#pragma mark -
/** @brief An abstract plot class.
*
* Each data series on the graph is represented by a plot. Data is provided by
* a datasource that conforms to the CPTPlotDataSource protocol.
* @if MacOnly
* Plots also support data binding on macOS.
* @endif
*
* A Core Plot plot will request its data from the datasource when it is first displayed.
* You can force it to load new data in several ways:
* - Call @link CPTGraph::reloadData -reloadData @endlink on the graph to reload all plots.
* - Call @link CPTPlot::reloadData -reloadData @endlink on the plot to reload all of the data for only that plot.
* - Call @link CPTPlot::reloadDataInIndexRange: -reloadDataInIndexRange: @endlink on the plot to reload a range
* of data indices without changing the total number of data points.
* - Call @link CPTPlot::insertDataAtIndex:numberOfRecords: -insertDataAtIndex:numberOfRecords: @endlink
* to insert new data at the given index. Any data at higher indices will be moved to make room.
* Only the new data will be requested from the datasource.
*
* You can also remove data from the plot without reloading anything by using the
* @link CPTPlot::deleteDataInIndexRange: -deleteDataInIndexRange: @endlink method.
*
* @see See @ref plotAnimation "Plots" for a list of animatable properties supported by each plot type.
* @if MacOnly
* @see See @ref plotBindings "Plot Bindings" for a list of binding identifiers supported by each plot type.
* @endif
**/
@implementation CPTPlot
@dynamic dataLabels;
/** @property nullable id<CPTPlotDataSource> dataSource
* @brief The data source for the plot.
**/
@synthesize dataSource;
/** @property nullable NSString *title
* @brief The title of the plot displayed in the legend.
*
* Assigning a new value to this property also sets the value of the @ref attributedTitle property to @nil.
**/
@synthesize title;
/** @property nullable NSAttributedString *attributedTitle
* @brief The styled title of the plot displayed in the legend.
*
* Assigning a new value to this property also sets the value of the @ref title property to the
* same string without formatting information.
**/
@synthesize attributedTitle;
/** @property nullable CPTPlotSpace *plotSpace
* @brief The plot space for the plot.
**/
@synthesize plotSpace;
/** @property nullable CPTPlotArea *plotArea
* @brief The plot area for the plot.
**/
@dynamic plotArea;
/** @property BOOL dataNeedsReloading
* @brief If @YES, the plot data will be reloaded from the data source before the layer content is drawn.
**/
@synthesize dataNeedsReloading;
@synthesize cachedData;
/** @property NSUInteger cachedDataCount
* @brief The number of data points stored in the cache.
**/
@synthesize cachedDataCount;
/** @property BOOL doublePrecisionCache
* @brief If @YES, the cache holds data of type @double, otherwise it holds @ref NSDecimal.
**/
@dynamic doublePrecisionCache;
/** @property CPTPlotCachePrecision cachePrecision
* @brief The numeric precision used to cache the plot data and perform all plot calculations. Defaults to #CPTPlotCachePrecisionAuto.
**/
@synthesize cachePrecision;
/** @property CPTNumericDataType doubleDataType
* @brief The CPTNumericDataType used to cache plot data as @double.
**/
@dynamic doubleDataType;
/** @property CPTNumericDataType decimalDataType
* @brief The CPTNumericDataType used to cache plot data as @ref NSDecimal.
**/
@dynamic decimalDataType;
/** @property BOOL needsRelabel
* @brief If @YES, the plot needs to be relabeled before the layer content is drawn.
**/
@synthesize needsRelabel;
/** @property BOOL adjustLabelAnchors
* @brief If @YES, data labels anchor points are adjusted automatically when the labels are positioned. If @NO, data labels anchor points do not change.
**/
@synthesize adjustLabelAnchors;
/** @property BOOL showLabels
* @brief Set to @NO to override all other label settings and hide the data labels. Defaults to @YES.
**/
@synthesize showLabels;
/** @property CGFloat labelOffset
* @brief The distance that labels should be offset from their anchor points. The direction of the offset is defined by subclasses.
* @ingroup plotAnimationAllPlots
**/
@synthesize labelOffset;
/** @property CGFloat labelRotation
* @brief The rotation of the data labels in radians.
* Set this property to @num{π/2} to have labels read up the screen, for example.
* @ingroup plotAnimationAllPlots
**/
@synthesize labelRotation;
/** @property NSUInteger labelField
* @brief The plot field identifier of the data field used to generate automatic labels.
**/
@synthesize labelField;
/** @property nullable CPTTextStyle *labelTextStyle
* @brief The text style used to draw the data labels.
* Set this property to @nil to hide the data labels.
**/
@synthesize labelTextStyle;
/** @property nullable NSFormatter *labelFormatter
* @brief The number formatter used to format the data labels.
* Set this property to @nil to hide the data labels.
* If you need a non-numerical label, such as a date, you can use a formatter than turns
* the numerical plot coordinate into a string (e.g., @quote{Jan 10, 2010}).
* The CPTCalendarFormatter and CPTTimeFormatter classes are useful for this purpose.
**/
@synthesize labelFormatter;
/** @property nullable CPTShadow *labelShadow
* @brief The shadow applied to each data label.
**/
@synthesize labelShadow;
@synthesize labelIndexRange;
@synthesize labelAnnotations;
/** @property BOOL alignsPointsToPixels
* @brief If @YES (the default), all plot points will be aligned to device pixels when drawing.
**/
@synthesize alignsPointsToPixels;
/** @property BOOL drawLegendSwatchDecoration
* @brief If @YES (the default), additional plot-specific decorations, symbols, and/or colors will be drawn on top of the legend swatch rectangle.
**/
@synthesize drawLegendSwatchDecoration;
@synthesize inTitleUpdate;
/** @internal
* @property NSUInteger pointingDeviceDownLabelIndex
* @brief The index that was selected on the pointing device down event.
**/
@synthesize pointingDeviceDownLabelIndex;
@dynamic numberOfRecords;
#pragma mark -
#pragma mark Init/Dealloc
/// @cond
#if TARGET_OS_SIMULATOR || TARGET_OS_IPHONE
#else
+(void)initialize
{
if ( self == [CPTPlot class] ) {
[self exposeBinding:CPTPlotBindingDataLabels];
}
}
#endif
/// @endcond
/// @name Initialization
/// @{
/** @brief Initializes a newly allocated CPTPlot object with the provided frame rectangle.
*
* This is the designated initializer. The initialized layer will have the following properties:
* - @ref cachedDataCount = @num{0}
* - @ref cachePrecision = #CPTPlotCachePrecisionAuto
* - @ref dataSource = @nil
* - @ref title = @nil
* - @ref attributedTitle = @nil
* - @ref plotSpace = @nil
* - @ref dataNeedsReloading = @NO
* - @ref needsRelabel = @YES
* - @ref adjustLabelAnchors = @YES
* - @ref showLabels = @YES
* - @ref labelOffset = @num{0.0}
* - @ref labelRotation = @num{0.0}
* - @ref labelField = @num{0}
* - @ref labelTextStyle = @nil
* - @ref labelFormatter = @nil
* - @ref labelShadow = @nil
* - @ref alignsPointsToPixels = @YES
* - @ref drawLegendSwatchDecoration = @YES
* - @ref masksToBounds = @YES
* - @ref needsDisplayOnBoundsChange = @YES
*
* @param newFrame The frame rectangle.
* @return The initialized CPTPlot object.
**/
-(nonnull instancetype)initWithFrame:(CGRect)newFrame
{
if ((self = [super initWithFrame:newFrame])) {
cachedData = [[NSMutableDictionary alloc] initWithCapacity:5];
cachedDataCount = 0;
cachePrecision = CPTPlotCachePrecisionAuto;
dataSource = nil;
title = nil;
attributedTitle = nil;
plotSpace = nil;
dataNeedsReloading = NO;
needsRelabel = YES;
adjustLabelAnchors = YES;
showLabels = YES;
labelOffset = CPTFloat(0.0);
labelRotation = CPTFloat(0.0);
labelField = 0;
labelTextStyle = nil;
labelFormatter = nil;
labelShadow = nil;
labelIndexRange = NSMakeRange(0, 0);
labelAnnotations = nil;
alignsPointsToPixels = YES;
inTitleUpdate = NO;
pointingDeviceDownLabelIndex = NSNotFound;
drawLegendSwatchDecoration = YES;
self.masksToBounds = YES;
self.needsDisplayOnBoundsChange = YES;
}
return self;
}
/// @}
/// @cond
-(nonnull instancetype)initWithLayer:(nonnull id)layer
{
if ((self = [super initWithLayer:layer])) {
CPTPlot *theLayer = (CPTPlot *)layer;
cachedData = theLayer->cachedData;
cachedDataCount = theLayer->cachedDataCount;
cachePrecision = theLayer->cachePrecision;
dataSource = theLayer->dataSource;
title = theLayer->title;
attributedTitle = theLayer->attributedTitle;
plotSpace = theLayer->plotSpace;
dataNeedsReloading = theLayer->dataNeedsReloading;
needsRelabel = theLayer->needsRelabel;
adjustLabelAnchors = theLayer->adjustLabelAnchors;
showLabels = theLayer->showLabels;
labelOffset = theLayer->labelOffset;
labelRotation = theLayer->labelRotation;
labelField = theLayer->labelField;
labelTextStyle = theLayer->labelTextStyle;
labelFormatter = theLayer->labelFormatter;
labelShadow = theLayer->labelShadow;
labelIndexRange = theLayer->labelIndexRange;
labelAnnotations = theLayer->labelAnnotations;
alignsPointsToPixels = theLayer->alignsPointsToPixels;
inTitleUpdate = theLayer->inTitleUpdate;
drawLegendSwatchDecoration = theLayer->drawLegendSwatchDecoration;
pointingDeviceDownLabelIndex = NSNotFound;
}
return self;
}
/// @endcond
#pragma mark -
#pragma mark NSCoding Methods
/// @cond
-(void)encodeWithCoder:(nonnull NSCoder *)coder
{
[super encodeWithCoder:coder];
id<CPTPlotDataSource> theDataSource = self.dataSource;
if ( [theDataSource conformsToProtocol:@protocol(NSCoding)] ) {
[coder encodeConditionalObject:theDataSource forKey:@"CPTPlot.dataSource"];
}
[coder encodeObject:self.title forKey:@"CPTPlot.title"];
[coder encodeObject:self.attributedTitle forKey:@"CPTPlot.attributedTitle"];
[coder encodeObject:self.plotSpace forKey:@"CPTPlot.plotSpace"];
[coder encodeInteger:self.cachePrecision forKey:@"CPTPlot.cachePrecision"];
[coder encodeBool:self.needsRelabel forKey:@"CPTPlot.needsRelabel"];
[coder encodeBool:self.adjustLabelAnchors forKey:@"CPTPlot.adjustLabelAnchors"];
[coder encodeBool:self.showLabels forKey:@"CPTPlot.showLabels"];
[coder encodeCGFloat:self.labelOffset forKey:@"CPTPlot.labelOffset"];
[coder encodeCGFloat:self.labelRotation forKey:@"CPTPlot.labelRotation"];
[coder encodeInteger:(NSInteger)self.labelField forKey:@"CPTPlot.labelField"];
[coder encodeObject:self.labelTextStyle forKey:@"CPTPlot.labelTextStyle"];
[coder encodeObject:self.labelFormatter forKey:@"CPTPlot.labelFormatter"];
[coder encodeObject:self.labelShadow forKey:@"CPTPlot.labelShadow"];
[coder encodeObject:[NSValue valueWithRange:self.labelIndexRange] forKey:@"CPTPlot.labelIndexRange"];
[coder encodeObject:self.labelAnnotations forKey:@"CPTPlot.labelAnnotations"];
[coder encodeBool:self.alignsPointsToPixels forKey:@"CPTPlot.alignsPointsToPixels"];
[coder encodeBool:self.drawLegendSwatchDecoration forKey:@"CPTPlot.drawLegendSwatchDecoration"];
// No need to archive these properties:
// dataNeedsReloading
// cachedData
// cachedDataCount
// inTitleUpdate
// pointingDeviceDownLabelIndex
}
-(nullable instancetype)initWithCoder:(nonnull NSCoder *)coder
{
if ((self = [super initWithCoder:coder])) {
dataSource = [coder decodeObjectOfClass:[NSObject class]
forKey:@"CPTPlot.dataSource"];
title = [[coder decodeObjectOfClass:[NSString class]
forKey:@"CPTPlot.title"] copy];
attributedTitle = [[coder decodeObjectOfClass:[NSAttributedString class]
forKey:@"CPTPlot.attributedTitle"] copy];
plotSpace = [coder decodeObjectOfClass:[CPTPlotSpace class]
forKey:@"CPTPlot.plotSpace"];
cachePrecision = (CPTPlotCachePrecision)[coder decodeIntegerForKey:@"CPTPlot.cachePrecision"];
needsRelabel = [coder decodeBoolForKey:@"CPTPlot.needsRelabel"];
adjustLabelAnchors = [coder decodeBoolForKey:@"CPTPlot.adjustLabelAnchors"];
showLabels = [coder decodeBoolForKey:@"CPTPlot.showLabels"];
labelOffset = [coder decodeCGFloatForKey:@"CPTPlot.labelOffset"];
labelRotation = [coder decodeCGFloatForKey:@"CPTPlot.labelRotation"];
labelField = (NSUInteger)[coder decodeIntegerForKey:@"CPTPlot.labelField"];
labelTextStyle = [[coder decodeObjectOfClass:[CPTTextStyle class]
forKey:@"CPTPlot.labelTextStyle"] copy];
labelFormatter = [coder decodeObjectOfClass:[NSFormatter class]
forKey:@"CPTPlot.labelFormatter"];
labelShadow = [coder decodeObjectOfClass:[CPTShadow class]
forKey:@"CPTPlot.labelShadow"];
labelIndexRange = [[coder decodeObjectOfClass:[NSValue class]
forKey:@"CPTPlot.labelIndexRange"] rangeValue];
labelAnnotations = [[coder decodeObjectOfClasses:[NSSet setWithArray:@[[NSArray class], [CPTAnnotation class]]]
forKey:@"CPTPlot.labelAnnotations"] mutableCopy];
alignsPointsToPixels = [coder decodeBoolForKey:@"CPTPlot.alignsPointsToPixels"];
drawLegendSwatchDecoration = [coder decodeBoolForKey:@"CPTPlot.drawLegendSwatchDecoration"];
// support old archives
if ( [coder containsValueForKey:@"CPTPlot.identifier"] ) {
self.identifier = [coder decodeObjectOfClass:[NSObject class]
forKey:@"CPTPlot.identifier"];
}
// init other properties
cachedData = [[NSMutableDictionary alloc] initWithCapacity:5];
cachedDataCount = 0;
dataNeedsReloading = YES;
inTitleUpdate = NO;
pointingDeviceDownLabelIndex = NSNotFound;
}
return self;
}
/// @endcond
#pragma mark -
#pragma mark NSSecureCoding Methods
/// @cond
+(BOOL)supportsSecureCoding
{
return YES;
}
/// @endcond
#pragma mark -
#pragma mark Bindings
#if TARGET_OS_SIMULATOR || TARGET_OS_IPHONE
#else
/// @cond
-(nullable Class)valueClassForBinding:(nonnull NSString *__unused)binding
{
return [NSArray class];
}
/// @endcond
#endif
#pragma mark -
#pragma mark Drawing
/// @cond
-(void)drawInContext:(nonnull CGContextRef)context
{
[self reloadDataIfNeeded];
[super drawInContext:context];
id<CPTPlotDelegate> theDelegate = (id<CPTPlotDelegate>)self.delegate;
if ( [theDelegate respondsToSelector:@selector(didFinishDrawing:)] ) {
[theDelegate didFinishDrawing:self];
}
}
/// @endcond
#pragma mark -
#pragma mark Animation
/// @cond
+(BOOL)needsDisplayForKey:(nonnull NSString *)aKey
{
static NSSet<NSString *> *keys = nil;
static dispatch_once_t onceToken = 0;
dispatch_once(&onceToken, ^{
keys = [NSSet setWithArray:@[@"labelOffset",
@"labelRotation"]];
});
if ( [keys containsObject:aKey] ) {
return YES;
}
else {
return [super needsDisplayForKey:aKey];
}
}
/// @endcond
#pragma mark -
#pragma mark Layout
/// @cond
-(void)layoutSublayers
{
[self relabel];
[super layoutSublayers];
}
/// @endcond
#pragma mark -
#pragma mark Data Source
/// @cond
-(NSUInteger)numberOfRecords
{
id<CPTPlotDataSource> theDataSource = self.dataSource;
return [theDataSource numberOfRecordsForPlot:self];
}
/// @endcond
/**
* @brief Marks the receiver as needing the data source reloaded before the content is next drawn.
**/
-(void)setDataNeedsReloading
{
self.dataNeedsReloading = YES;
}
/**
* @brief Reload all plot data, labels, and plot-specific information from the data source immediately.
**/
-(void)reloadData
{
[self.cachedData removeAllObjects];
self.cachedDataCount = 0;
[self reloadDataInIndexRange:NSMakeRange(0, self.numberOfRecords)];
}
/**
* @brief Reload plot data from the data source only if the data cache is out of date.
**/
-(void)reloadDataIfNeeded
{
if ( self.dataNeedsReloading ) {
[self reloadData];
}
}
/** @brief Reload plot data, labels, and plot-specific information in the given index range from the data source immediately.
* @param indexRange The index range to load.
**/
-(void)reloadDataInIndexRange:(NSRange)indexRange
{
NSParameterAssert(NSMaxRange(indexRange) <= self.numberOfRecords);
self.dataNeedsReloading = NO;
[self reloadPlotDataInIndexRange:indexRange];
// Data labels
[self reloadDataLabelsInIndexRange:indexRange];
}
/** @brief Insert records into the plot data cache at the given index.
* @param idx The starting index of the new records.
* @param numberOfRecords The number of records to insert.
**/
-(void)insertDataAtIndex:(NSUInteger)idx numberOfRecords:(NSUInteger)numberOfRecords
{
NSParameterAssert(idx <= self.cachedDataCount);
Class numericClass = [CPTNumericData class];
for ( id data in self.cachedData.allValues ) {
if ( [data isKindOfClass:numericClass] ) {
CPTMutableNumericData *numericData = (CPTMutableNumericData *)data;
size_t sampleSize = numericData.sampleBytes;
size_t length = sampleSize * numberOfRecords;
[(NSMutableData *) numericData.data increaseLengthBy:length];
int8_t *start = [numericData mutableSamplePointer:idx];
size_t bytesToMove = numericData.data.length - (idx + numberOfRecords) * sampleSize;
if ( bytesToMove > 0 ) {
memmove(start + length, start, bytesToMove);
}
}
else {
NSMutableArray *array = (NSMutableArray *)data;
NSNull *nullObject = [NSNull null];
NSUInteger lastIndex = idx + numberOfRecords - 1;
for ( NSUInteger i = idx; i <= lastIndex; i++ ) {
[array insertObject:nullObject atIndex:i];
}
}
}
CPTMutableAnnotationArray *labelArray = self.labelAnnotations;
if ( labelArray ) {
id nullObject = [NSNull null];
NSUInteger lastIndex = idx + numberOfRecords - 1;
for ( NSUInteger i = idx; i <= lastIndex; i++ ) {
[labelArray insertObject:nullObject atIndex:i];
}
}
self.cachedDataCount += numberOfRecords;
[self reloadDataInIndexRange:NSMakeRange(idx, numberOfRecords)];
}
/** @brief Delete records in the given index range from the plot data cache.
* @param indexRange The index range of the data records to remove.
**/
-(void)deleteDataInIndexRange:(NSRange)indexRange
{
NSParameterAssert(NSMaxRange(indexRange) <= self.cachedDataCount);
Class numericClass = [CPTNumericData class];
for ( id data in self.cachedData.allValues ) {
if ( [data isKindOfClass:numericClass] ) {
CPTMutableNumericData *numericData = (CPTMutableNumericData *)data;
size_t sampleSize = numericData.sampleBytes;
int8_t *start = [numericData mutableSamplePointer:indexRange.location];
size_t length = sampleSize * indexRange.length;
size_t bytesToMove = numericData.data.length - (indexRange.location + indexRange.length) * sampleSize;
if ( bytesToMove > 0 ) {
memmove(start, start + length, bytesToMove);
}
NSMutableData *dataBuffer = (NSMutableData *)numericData.data;
dataBuffer.length -= length;
}
else {
[(NSMutableArray *) data removeObjectsInRange:indexRange];
}
}
CPTMutableAnnotationArray *labelArray = self.labelAnnotations;
NSUInteger maxIndex = NSMaxRange(indexRange);
Class annotationClass = [CPTAnnotation class];
for ( NSUInteger i = indexRange.location; i < maxIndex; i++ ) {
CPTAnnotation *annotation = labelArray[i];
if ( [annotation isKindOfClass:annotationClass] ) {
[self removeAnnotation:annotation];
}
}
[labelArray removeObjectsInRange:indexRange];
self.cachedDataCount -= indexRange.length;
[self setNeedsDisplay];
}
/**
* @brief Reload all plot data from the data source immediately.
**/
-(void)reloadPlotData
{
NSMutableDictionary<NSNumber *, id> *dataCache = self.cachedData;
for ( NSNumber *fieldID in self.fieldIdentifiers ) {
[dataCache removeObjectForKey:fieldID];
}
[self reloadPlotDataInIndexRange:NSMakeRange(0, self.cachedDataCount)];
}
/** @brief Reload plot data in the given index range from the data source immediately.
* @param indexRange The index range to load.
**/
-(void)reloadPlotDataInIndexRange:(NSRange __unused)indexRange
{
// do nothing--implementation provided by subclasses
}
/**
* @brief Reload all data labels from the data source immediately.
**/
-(void)reloadDataLabels
{
[self.cachedData removeObjectForKey:CPTPlotBindingDataLabels];
[self reloadDataLabelsInIndexRange:NSMakeRange(0, self.cachedDataCount)];
}
/** @brief Reload data labels in the given index range from the data source immediately.
* @param indexRange The index range to load.
**/
-(void)reloadDataLabelsInIndexRange:(NSRange)indexRange
{
id<CPTPlotDataSource> theDataSource = (id<CPTPlotDataSource>)self.dataSource;
if ( [theDataSource respondsToSelector:@selector(dataLabelsForPlot:recordIndexRange:)] ) {
[self cacheArray:[theDataSource dataLabelsForPlot:self recordIndexRange:indexRange]
forKey:CPTPlotBindingDataLabels
atRecordIndex:indexRange.location];
}
else if ( [theDataSource respondsToSelector:@selector(dataLabelForPlot:recordIndex:)] ) {
id nilObject = [CPTPlot nilData];
CPTMutableLayerArray *array = [[NSMutableArray alloc] initWithCapacity:indexRange.length];
NSUInteger maxIndex = NSMaxRange(indexRange);
for ( NSUInteger idx = indexRange.location; idx < maxIndex; idx++ ) {
CPTLayer *labelLayer = [theDataSource dataLabelForPlot:self recordIndex:idx];
if ( labelLayer ) {
[array addObject:labelLayer];
}
else {
[array addObject:nilObject];
}
}
[self cacheArray:array
forKey:CPTPlotBindingDataLabels
atRecordIndex:indexRange.location];
}
[self relabelIndexRange:indexRange];
}
/**
* @brief A unique marker object used in collections to indicate that the datasource returned @nil.
**/
+(nonnull id)nilData
{
static id nilObject = nil;
static dispatch_once_t onceToken = 0;
dispatch_once(&onceToken, ^{
nilObject = [[NSObject alloc] init];
});
return nilObject;
}
/** @brief Gets a range of plot data for the given plot and field.
* @param fieldEnum The field index.
* @param indexRange The range of the data indexes of interest.
* @return An array of data points.
**/
-(nullable id)numbersFromDataSourceForField:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange
{
id numbers; // can be CPTNumericData, NSArray, or NSData
id<CPTPlotDataSource> theDataSource = self.dataSource;
if ( theDataSource ) {
if ( [theDataSource respondsToSelector:@selector(dataForPlot:field:recordIndexRange:)] ) {
numbers = [theDataSource dataForPlot:self field:fieldEnum recordIndexRange:indexRange];
}
else if ( [theDataSource respondsToSelector:@selector(doublesForPlot:field:recordIndexRange:)] ) {
numbers = [NSMutableData dataWithLength:sizeof(double) * indexRange.length];
double *fieldValues = [numbers mutableBytes];
double *doubleValues = [theDataSource doublesForPlot:self field:fieldEnum recordIndexRange:indexRange];
memcpy(fieldValues, doubleValues, sizeof(double) * indexRange.length);
}
else if ( [theDataSource respondsToSelector:@selector(numbersForPlot:field:recordIndexRange:)] ) {
NSArray *numberArray = [theDataSource numbersForPlot:self field:fieldEnum recordIndexRange:indexRange];
if ( numberArray ) {
numbers = [NSArray arrayWithArray:numberArray];
}
else {
numbers = nil;
}
}
else if ( [theDataSource respondsToSelector:@selector(doubleForPlot:field:recordIndex:)] ) {
NSUInteger recordIndex;
NSMutableData *fieldData = [NSMutableData dataWithLength:sizeof(double) * indexRange.length];
double *fieldValues = fieldData.mutableBytes;
for ( recordIndex = indexRange.location; recordIndex < indexRange.location + indexRange.length; ++recordIndex ) {
double number = [theDataSource doubleForPlot:self field:fieldEnum recordIndex:recordIndex];
*fieldValues++ = number;
}
numbers = fieldData;
}
else {
BOOL respondsToSingleValueSelector = [theDataSource respondsToSelector:@selector(numberForPlot:field:recordIndex:)];
NSNull *nullObject = [NSNull null];
NSUInteger recordIndex;
NSMutableArray *fieldValues = [NSMutableArray arrayWithCapacity:indexRange.length];
for ( recordIndex = indexRange.location; recordIndex < indexRange.location + indexRange.length; recordIndex++ ) {
if ( respondsToSingleValueSelector ) {
id number = [theDataSource numberForPlot:self field:fieldEnum recordIndex:recordIndex];
if ( number ) {
[fieldValues addObject:number];
}
else {
[fieldValues addObject:nullObject];
}
}
else {
[fieldValues addObject:[NSDecimalNumber zero]];
}
}
numbers = fieldValues;
}
}
else {
numbers = @[];
}
return numbers;
}
/** @brief Gets a range of plot data for the given plot.
* @param indexRange The range of the data indexes of interest.
* @return Returns @YES if the datasource implements the
* @link CPTPlotDataSource::dataForPlot:recordIndexRange: -dataForPlot:recordIndexRange: @endlink
* method and it returns valid data.
**/
-(BOOL)loadNumbersForAllFieldsFromDataSourceInRecordIndexRange:(NSRange)indexRange
{
BOOL hasData = NO;
id<CPTPlotDataSource> theDataSource = self.dataSource;
if ( [theDataSource respondsToSelector:@selector(dataForPlot:recordIndexRange:)] ) {
CPTNumericData *data = [theDataSource dataForPlot:self recordIndexRange:indexRange];
if ( [data isKindOfClass:[CPTNumericData class]] ) {
const NSUInteger sampleCount = data.numberOfSamples;
CPTNumericDataType dataType = data.dataType;
if ((sampleCount > 0) && (data.numberOfDimensions == 2)) {
CPTNumberArray *theShape = data.shape;
const NSUInteger rowCount = theShape[0].unsignedIntegerValue;
const NSUInteger fieldCount = theShape[1].unsignedIntegerValue;
if ( fieldCount > 0 ) {
// convert data type if needed
switch ( self.cachePrecision ) {
case CPTPlotCachePrecisionAuto:
if ( self.doublePrecisionCache ) {
if ( !CPTDataTypeEqualToDataType(dataType, self.doubleDataType)) {
CPTMutableNumericData *mutableData = [data mutableCopy];
mutableData.dataType = self.doubleDataType;
data = mutableData;
}
}
else {
if ( !CPTDataTypeEqualToDataType(dataType, self.decimalDataType)) {
CPTMutableNumericData *mutableData = [data mutableCopy];
mutableData.dataType = self.decimalDataType;
data = mutableData;
}
}
break;
case CPTPlotCachePrecisionDecimal:
if ( !CPTDataTypeEqualToDataType(dataType, self.decimalDataType)) {
CPTMutableNumericData *mutableData = [data mutableCopy];
mutableData.dataType = self.decimalDataType;
data = mutableData;
}
break;
case CPTPlotCachePrecisionDouble:
if ( !CPTDataTypeEqualToDataType(dataType, self.doubleDataType)) {
CPTMutableNumericData *mutableData = [data mutableCopy];
mutableData.dataType = self.doubleDataType;
data = mutableData;
}
break;
}
// add the data to the cache
const NSUInteger bufferLength = rowCount * dataType.sampleBytes;
switch ( data.dataOrder ) {
case CPTDataOrderRowsFirst:
{
const void *sourceEnd = (const int8_t *)(data.bytes) + data.length;
for ( NSUInteger fieldNum = 0; fieldNum < fieldCount; fieldNum++ ) {
NSMutableData *tempData = [[NSMutableData alloc] initWithLength:bufferLength];
if ( CPTDataTypeEqualToDataType(dataType, self.doubleDataType)) {
const double *sourceData = [data samplePointerAtIndex:0, fieldNum];
double *destData = tempData.mutableBytes;
while ( sourceData < (const double *)sourceEnd ) {
*destData++ = *sourceData;
sourceData += fieldCount;
}
}
else {
const NSDecimal *sourceData = [data samplePointerAtIndex:0, fieldNum];
NSDecimal *destData = tempData.mutableBytes;
while ( sourceData < (const NSDecimal *)sourceEnd ) {
*destData++ = *sourceData;
sourceData += fieldCount;
}
}
CPTMutableNumericData *tempNumericData = [[CPTMutableNumericData alloc] initWithData:tempData
dataType:dataType
shape:nil];
[self cacheNumbers:tempNumericData forField:fieldNum atRecordIndex:indexRange.location];
}
hasData = YES;
}
break;
case CPTDataOrderColumnsFirst:
for ( NSUInteger fieldNum = 0; fieldNum < fieldCount; fieldNum++ ) {
const void *samples = [data samplePointerAtIndex:0, fieldNum];
NSData *tempData = [[NSData alloc] initWithBytes:samples
length:bufferLength];
CPTMutableNumericData *tempNumericData = [[CPTMutableNumericData alloc] initWithData:tempData
dataType:dataType
shape:nil];
[self cacheNumbers:tempNumericData forField:fieldNum atRecordIndex:indexRange.location];
}
hasData = YES;
break;
}
}
}
}
}
return hasData;
}
#pragma mark -
#pragma mark Data Caching
-(NSUInteger)cachedDataCount
{
[self reloadDataIfNeeded];
return cachedDataCount;
}
/** @brief Copies an array of numbers to the cache.
* @param numbers An array of numbers to cache. Can be a CPTNumericData, NSArray, or NSData (NSData is assumed to be a c-style array of type @double).
* @param fieldEnum The field enumerator identifying the field.
**/
-(void)cacheNumbers:(nullable id)numbers forField:(NSUInteger)fieldEnum
{
NSNumber *cacheKey = @(fieldEnum);
CPTCoordinate coordinate = [self coordinateForFieldIdentifier:fieldEnum];
CPTPlotSpace *thePlotSpace = self.plotSpace;
if ( numbers ) {
switch ( [thePlotSpace scaleTypeForCoordinate:coordinate] ) {
case CPTScaleTypeLinear:
case CPTScaleTypeLog:
case CPTScaleTypeLogModulus:
{
id theNumbers = numbers;
CPTMutableNumericData *mutableNumbers = [self numericDataForNumbers:theNumbers];
NSUInteger sampleCount = mutableNumbers.numberOfSamples;
if ( sampleCount > 0 ) {
(self.cachedData)[cacheKey] = mutableNumbers;
}
else {
[self.cachedData removeObjectForKey:cacheKey];
}
self.cachedDataCount = sampleCount;
switch ( self.cachePrecision ) {
case CPTPlotCachePrecisionAuto:
[self setCachedDataType:mutableNumbers.dataType];
break;
case CPTPlotCachePrecisionDouble:
[self setCachedDataType:self.doubleDataType];
break;
case CPTPlotCachePrecisionDecimal:
[self setCachedDataType:self.decimalDataType];
break;
}
}
break;
case CPTScaleTypeCategory:
{
CPTStringArray *samples = (CPTStringArray *)numbers;
if ( [samples isKindOfClass:[NSArray class]] ) {
[thePlotSpace setCategories:samples forCoordinate:coordinate];
NSUInteger sampleCount = samples.count;
if ( sampleCount > 0 ) {
CPTMutableNumberArray *indices = [[NSMutableArray alloc] initWithCapacity:sampleCount];
for ( NSString *category in samples ) {
[indices addObject:@([thePlotSpace indexOfCategory:category forCoordinate:coordinate])];
}
CPTNumericDataType dataType = (self.cachePrecision == CPTPlotCachePrecisionDecimal ? self.decimalDataType : self.doubleDataType);
CPTMutableNumericData *mutableNumbers = [[CPTMutableNumericData alloc] initWithArray:indices
dataType:dataType
shape:nil];
(self.cachedData)[cacheKey] = mutableNumbers;
self.cachedDataCount = sampleCount;
}
else {
[self.cachedData removeObjectForKey:cacheKey];
}
}
else {
[self.cachedData removeObjectForKey:cacheKey];
}
}
break;
default:
break;
}
}
else {
[self.cachedData removeObjectForKey:cacheKey];
self.cachedDataCount = 0;
}
self.needsRelabel = YES;
[self setNeedsDisplay];
}
/** @brief Copies an array of numbers to replace a part of the cache.
* @param numbers An array of numbers to cache. Can be a CPTNumericData, NSArray, or NSData (NSData is assumed to be a c-style array of type @double).
* @param fieldEnum The field enumerator identifying the field.
* @param idx The index of the first data point to replace.
**/
-(void)cacheNumbers:(nullable id)numbers forField:(NSUInteger)fieldEnum atRecordIndex:(NSUInteger)idx
{
if ( numbers ) {
NSNumber *cacheKey = @(fieldEnum);
NSUInteger sampleCount = 0;
CPTCoordinate coordinate = [self coordinateForFieldIdentifier:fieldEnum];
CPTPlotSpace *thePlotSpace = self.plotSpace;
CPTMutableNumericData *mutableNumbers = nil;
switch ( [thePlotSpace scaleTypeForCoordinate:coordinate] ) {
case CPTScaleTypeLinear:
case CPTScaleTypeLog:
case CPTScaleTypeLogModulus:
{
id theNumbers = numbers;
mutableNumbers = [self numericDataForNumbers:theNumbers];
sampleCount = mutableNumbers.numberOfSamples;
if ( sampleCount > 0 ) {
// Ensure the new data is the same type as the cache
switch ( self.cachePrecision ) {
case CPTPlotCachePrecisionAuto:
[self setCachedDataType:mutableNumbers.dataType];
break;
case CPTPlotCachePrecisionDouble:
{
CPTNumericDataType newType = self.doubleDataType;
[self setCachedDataType:newType];
mutableNumbers.dataType = newType;
}
break;
case CPTPlotCachePrecisionDecimal:
{
CPTNumericDataType newType = self.decimalDataType;
[self setCachedDataType:newType];
mutableNumbers.dataType = newType;
}
break;
}
}
}
break;
case CPTScaleTypeCategory:
{
CPTStringArray *samples = (CPTStringArray *)numbers;
if ( [samples isKindOfClass:[NSArray class]] ) {
sampleCount = samples.count;
if ( sampleCount > 0 ) {
CPTMutableNumberArray *indices = [[NSMutableArray alloc] initWithCapacity:sampleCount];
for ( NSString *category in samples ) {
[thePlotSpace addCategory:category forCoordinate:coordinate];
[indices addObject:@([thePlotSpace indexOfCategory:category forCoordinate:coordinate])];
}
CPTNumericDataType dataType = (self.cachePrecision == CPTPlotCachePrecisionDecimal ? self.decimalDataType : self.doubleDataType);
mutableNumbers = [[CPTMutableNumericData alloc] initWithArray:indices
dataType:dataType
shape:nil];
}
}
}
break;
default:
[self.cachedData removeObjectForKey:cacheKey];
break;
}
if ( mutableNumbers && (sampleCount > 0)) {
// Ensure the data cache exists and is the right size
CPTMutableNumericData *cachedNumbers = (self.cachedData)[cacheKey];
if ( !cachedNumbers ) {
cachedNumbers = [CPTMutableNumericData numericDataWithData:[NSData data]
dataType:mutableNumbers.dataType
shape:nil];
(self.cachedData)[cacheKey] = cachedNumbers;
}
id<CPTPlotDataSource> theDataSource = self.dataSource;
NSUInteger numberOfRecords = [theDataSource numberOfRecordsForPlot:self];
cachedNumbers.shape = @[@(numberOfRecords)];
// Update the cache
self.cachedDataCount = numberOfRecords;
NSUInteger startByte = idx * cachedNumbers.sampleBytes;
void *cachePtr = (int8_t *)(cachedNumbers.mutableBytes) + startByte;
size_t numberOfBytes = MIN(mutableNumbers.data.length, cachedNumbers.data.length - startByte);
memcpy(cachePtr, mutableNumbers.bytes, numberOfBytes);
[self relabelIndexRange:NSMakeRange(idx, sampleCount)];
}
[self setNeedsDisplay];
}
}
/// @cond
-(nonnull CPTMutableNumericData *)numericDataForNumbers:(nonnull id)numbers
{
CPTMutableNumericData *mutableNumbers = nil;
CPTNumericDataType loadedDataType;
if ( [numbers isKindOfClass:[CPTNumericData class]] ) {
mutableNumbers = [numbers mutableCopy];
// ensure the numeric data is in a supported format; default to double if not already NSDecimal
if ( !CPTDataTypeEqualToDataType(mutableNumbers.dataType, self.decimalDataType) &&
!CPTDataTypeEqualToDataType(mutableNumbers.dataType, self.doubleDataType)) {
mutableNumbers.dataType = self.doubleDataType;
}
}
else if ( [numbers isKindOfClass:[NSData class]] ) {
loadedDataType = self.doubleDataType;
mutableNumbers = [[CPTMutableNumericData alloc] initWithData:numbers dataType:loadedDataType shape:nil];
}
else if ( [numbers isKindOfClass:[NSArray class]] ) {
if (((CPTNumberArray *)numbers).count == 0 ) {
loadedDataType = self.doubleDataType;
}
else if ( [((NSArray<NSNumber *> *)numbers)[0] isKindOfClass:[NSDecimalNumber class]] ) {
loadedDataType = self.decimalDataType;
}
else {
loadedDataType = self.doubleDataType;
}
mutableNumbers = [[CPTMutableNumericData alloc] initWithArray:numbers dataType:loadedDataType shape:nil];
}
else {
[NSException raise:CPTException format:@"Unsupported number array format"];
}
return mutableNumbers;
}
/// @endcond
-(BOOL)doublePrecisionCache
{
BOOL result = NO;
switch ( self.cachePrecision ) {
case CPTPlotCachePrecisionAuto:
{
NSMutableDictionary<NSString *, CPTNumericData *> *dataCache = self.cachedData;
Class numberClass = [NSNumber class];
for ( id key in dataCache.allKeys ) {
if ( [key isKindOfClass:numberClass] ) {
result = CPTDataTypeEqualToDataType(((CPTMutableNumericData *)dataCache[key]).dataType, self.doubleDataType);
break;
}
}
}
break;
case CPTPlotCachePrecisionDouble:
result = YES;
break;
default:
// not double precision
break;
}
return result;
}
/** @brief Retrieves an array of numbers from the cache.
* @param fieldEnum The field enumerator identifying the field.
* @return The array of cached numbers.
**/
-(nullable CPTMutableNumericData *)cachedNumbersForField:(NSUInteger)fieldEnum
{
return (self.cachedData)[@(fieldEnum)];
}
/** @brief Retrieves a single number from the cache.
* @param fieldEnum The field enumerator identifying the field.
* @param idx The index of the desired data value.
* @return The cached number.
**/
-(nullable NSNumber *)cachedNumberForField:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx
{
CPTMutableNumericData *numbers = [self cachedNumbersForField:fieldEnum];
return [numbers sampleValue:idx];
}
/** @brief Retrieves a single number from the cache.
* @param fieldEnum The field enumerator identifying the field.
* @param idx The index of the desired data value.
* @return The cached number or @NAN if no data is cached for the requested field.
**/
-(double)cachedDoubleForField:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx
{
CPTMutableNumericData *numbers = [self cachedNumbersForField:fieldEnum];
if ( numbers ) {
switch ( numbers.dataTypeFormat ) {
case CPTFloatingPointDataType:
{
const double *doubleNumber = (const double *)[numbers samplePointer:idx];
if ( doubleNumber ) {
return *doubleNumber;
}
}
break;
case CPTDecimalDataType:
{
const NSDecimal *decimalNumber = (const NSDecimal *)[numbers samplePointer:idx];
if ( decimalNumber ) {
return CPTDecimalDoubleValue(*decimalNumber);
}
}
break;
default:
[NSException raise:CPTException format:@"Unsupported data type format"];
break;
}
}
return (double)NAN;
}
/** @brief Retrieves a single number from the cache.
* @param fieldEnum The field enumerator identifying the field.
* @param idx The index of the desired data value.
* @return The cached number or @NAN if no data is cached for the requested field.
**/
-(NSDecimal)cachedDecimalForField:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx
{
CPTMutableNumericData *numbers = [self cachedNumbersForField:fieldEnum];
if ( numbers ) {
switch ( numbers.dataTypeFormat ) {
case CPTFloatingPointDataType:
{
const double *doubleNumber = (const double *)[numbers samplePointer:idx];
if ( doubleNumber ) {
return CPTDecimalFromDouble(*doubleNumber);
}
}
break;
case CPTDecimalDataType:
{
const NSDecimal *decimalNumber = (const NSDecimal *)[numbers samplePointer:idx];
if ( decimalNumber ) {
return *decimalNumber;
}
}
break;
default:
[NSException raise:CPTException format:@"Unsupported data type format"];
break;
}
}
return CPTDecimalNaN();
}
/// @cond
-(void)setCachedDataType:(CPTNumericDataType)newDataType
{
Class numberClass = [NSNumber class];
NSMutableDictionary<NSString *, CPTMutableNumericData *> *dataDictionary = self.cachedData;
for ( id key in dataDictionary.allKeys ) {
if ( [key isKindOfClass:numberClass] ) {
CPTMutableNumericData *numericData = dataDictionary[key];
numericData.dataType = newDataType;
}
}
}
/// @endcond
-(CPTNumericDataType)doubleDataType
{
static CPTNumericDataType dataType;
static dispatch_once_t onceToken = 0;
dispatch_once(&onceToken, ^{
dataType = CPTDataType(CPTFloatingPointDataType, sizeof(double), CFByteOrderGetCurrent());
});
return dataType;
}
-(CPTNumericDataType)decimalDataType
{
static CPTNumericDataType dataType;
static dispatch_once_t onceToken = 0;
dispatch_once(&onceToken, ^{
dataType = CPTDataType(CPTDecimalDataType, sizeof(NSDecimal), CFByteOrderGetCurrent());
});
return dataType;
}
/** @brief Retrieves an array of values from the cache.
* @param key The key identifying the field.
* @return The array of cached values.
**/
-(nullable NSArray *)cachedArrayForKey:(nonnull NSString *)key
{
return (self.cachedData)[key];
}
/** @brief Retrieves a single value from the cache.
* @param key The key identifying the field.
* @param idx The index of the desired data value.
* @return The cached value or @nil if no data is cached for the requested key.
**/
-(nullable id)cachedValueForKey:(nonnull NSString *)key recordIndex:(NSUInteger)idx
{
return [self cachedArrayForKey:key][idx];
}
/** @brief Copies an array of arbitrary values to the cache.
* @param array An array of arbitrary values to cache.
* @param key The key identifying the field.
**/
-(void)cacheArray:(nullable NSArray *)array forKey:(nonnull NSString *)key
{
if ( array ) {
NSUInteger sampleCount = array.count;
if ( sampleCount > 0 ) {
(self.cachedData)[key] = array;
}
else {
[self.cachedData removeObjectForKey:key];
}
self.cachedDataCount = sampleCount;
}
else {
[self.cachedData removeObjectForKey:key];
self.cachedDataCount = 0;
}
}
/** @brief Copies an array of arbitrary values to replace a part of the cache.
* @param array An array of arbitrary values to cache.
* @param key The key identifying the field.
* @param idx The index of the first data point to replace.
**/
-(void)cacheArray:(nullable NSArray *)array forKey:(nonnull NSString *)key atRecordIndex:(NSUInteger)idx
{
NSUInteger sampleCount = array.count;
if ( sampleCount > 0 ) {
// Ensure the data cache exists and is the right size
id<CPTPlotDataSource> theDataSource = self.dataSource;
NSUInteger numberOfRecords = [theDataSource numberOfRecordsForPlot:self];
NSMutableArray *cachedValues = (self.cachedData)[key];
if ( !cachedValues ) {
cachedValues = [NSMutableArray arrayWithCapacity:numberOfRecords];
NSNull *nullObject = [NSNull null];
for ( NSUInteger i = 0; i < numberOfRecords; i++ ) {
[cachedValues addObject:nullObject];
}
(self.cachedData)[key] = cachedValues;
}
// Update the cache
self.cachedDataCount = numberOfRecords;
NSArray *dataArray = array;
[cachedValues replaceObjectsInRange:NSMakeRange(idx, sampleCount) withObjectsFromArray:dataArray];
}
}
#pragma mark -
#pragma mark Data Ranges
/** @brief Determines the smallest plot range that fully encloses the data for a particular field.
* @param fieldEnum The field enumerator identifying the field.
* @return The plot range enclosing the data.
**/
-(nullable CPTPlotRange *)plotRangeForField:(NSUInteger)fieldEnum
{
if ( self.dataNeedsReloading ) {
[self reloadData];
}
CPTMutableNumericData *numbers = [self cachedNumbersForField:fieldEnum];
CPTPlotRange *range = nil;
NSUInteger numberOfSamples = numbers.numberOfSamples;
if ( numberOfSamples > 0 ) {
if ( self.doublePrecisionCache ) {
double min = (double)INFINITY;
double max = -(double)INFINITY;
const double *doubles = (const double *)numbers.bytes;
const double *lastSample = doubles + numberOfSamples;
while ( doubles < lastSample ) {
double value = *doubles++;
if ( !isnan(value)) {
if ( value < min ) {
min = value;
}
if ( value > max ) {
max = value;
}
}
}
if ( max >= min ) {
range = [CPTPlotRange plotRangeWithLocation:@(min) length:@(max - min)];
}
}
else {
NSDecimal min = [NSDecimalNumber maximumDecimalNumber].decimalValue;
NSDecimal max = [NSDecimalNumber minimumDecimalNumber].decimalValue;
const NSDecimal *decimals = (const NSDecimal *)numbers.bytes;
const NSDecimal *lastSample = decimals + numberOfSamples;
while ( decimals < lastSample ) {
NSDecimal value = *decimals++;
if ( !NSDecimalIsNotANumber(&value)) {
if ( CPTDecimalLessThan(value, min)) {
min = value;
}
if ( CPTDecimalGreaterThan(value, max)) {
max = value;
}
}
}
if ( CPTDecimalGreaterThanOrEqualTo(max, min)) {
range = [CPTPlotRange plotRangeWithLocationDecimal:min lengthDecimal:CPTDecimalSubtract(max, min)];
}
}
}
return range;
}
/** @brief Determines the smallest plot range that fully encloses the data for a particular coordinate.
* @param coord The coordinate identifier.
* @return The plot range enclosing the data.
**/
-(nullable CPTPlotRange *)plotRangeForCoordinate:(CPTCoordinate)coord
{
CPTNumberArray *fields = [self fieldIdentifiersForCoordinate:coord];
if ( fields.count == 0 ) {
return nil;
}
CPTMutablePlotRange *unionRange = nil;
for ( NSNumber *field in fields ) {
CPTPlotRange *currentRange = [self plotRangeForField:field.unsignedIntegerValue];
if ( !unionRange ) {
unionRange = [currentRange mutableCopy];
}
else {
[unionRange unionPlotRange:[self plotRangeForField:field.unsignedIntegerValue]];
}
}
return unionRange;
}
/** @brief Determines the smallest plot range that fully encloses the entire plot for a particular field.
* @param fieldEnum The field enumerator identifying the field.
* @return The plot range enclosing the data.
**/
-(nullable CPTPlotRange *)plotRangeEnclosingField:(NSUInteger)fieldEnum
{
return [self plotRangeForField:fieldEnum];
}
/** @brief Determines the smallest plot range that fully encloses the entire plot for a particular coordinate.
* @param coord The coordinate identifier.
* @return The plot range enclosing the data.
**/
-(nullable CPTPlotRange *)plotRangeEnclosingCoordinate:(CPTCoordinate)coord
{
CPTNumberArray *fields = [self fieldIdentifiersForCoordinate:coord];
if ( fields.count == 0 ) {
return nil;
}
CPTMutablePlotRange *unionRange = nil;
for ( NSNumber *field in fields ) {
CPTPlotRange *currentRange = [self plotRangeEnclosingField:field.unsignedIntegerValue];
if ( !unionRange ) {
unionRange = [currentRange mutableCopy];
}
else {
[unionRange unionPlotRange:[self plotRangeEnclosingField:field.unsignedIntegerValue]];
}
}
return unionRange;
}
#pragma mark -
#pragma mark Data Labels
/**
* @brief Marks the receiver as needing to update all data labels before the content is next drawn.
* @see @link CPTPlot::relabelIndexRange: -relabelIndexRange: @endlink
**/
-(void)setNeedsRelabel
{
self.labelIndexRange = NSMakeRange(0, self.cachedDataCount);
self.needsRelabel = YES;
}
/**
* @brief Updates the data labels in the labelIndexRange.
**/
-(void)relabel
{
if ( !self.needsRelabel ) {
return;
}
self.needsRelabel = NO;
id nullObject = [NSNull null];
Class nullClass = [NSNull class];
Class annotationClass = [CPTAnnotation class];
CPTTextStyle *dataLabelTextStyle = self.labelTextStyle;
NSFormatter *dataLabelFormatter = self.labelFormatter;
BOOL plotProvidesLabels = dataLabelTextStyle && dataLabelFormatter;
BOOL hasCachedLabels = NO;
CPTMutableLayerArray *cachedLabels = (CPTMutableLayerArray *)[self cachedArrayForKey:CPTPlotBindingDataLabels];
for ( CPTLayer *label in cachedLabels ) {
if ( ![label isKindOfClass:nullClass] ) {
hasCachedLabels = YES;
break;
}
}
if ( !self.showLabels || (!hasCachedLabels && !plotProvidesLabels)) {
for ( CPTAnnotation *annotation in self.labelAnnotations ) {
if ( [annotation isKindOfClass:annotationClass] ) {
[self removeAnnotation:annotation];
}
}
self.labelAnnotations = nil;
return;
}
CPTDictionary *textAttributes = dataLabelTextStyle.attributes;
BOOL hasAttributedFormatter = ([dataLabelFormatter attributedStringForObjectValue:[NSDecimalNumber zero]
withDefaultAttributes:textAttributes] != nil);
NSUInteger sampleCount = self.cachedDataCount;
NSRange indexRange = self.labelIndexRange;
NSUInteger maxIndex = NSMaxRange(indexRange);
if ( !self.labelAnnotations ) {
self.labelAnnotations = [NSMutableArray arrayWithCapacity:sampleCount];
}
CPTPlotSpace *thePlotSpace = self.plotSpace;
CGFloat theRotation = self.labelRotation;
CPTMutableAnnotationArray *labelArray = self.labelAnnotations;
NSUInteger oldLabelCount = labelArray.count;
id nilObject = [CPTPlot nilData];
CPTMutableNumericData *labelFieldDataCache = [self cachedNumbersForField:self.labelField];
CPTShadow *theShadow = self.labelShadow;
for ( NSUInteger i = indexRange.location; i < maxIndex; i++ ) {
NSNumber *dataValue = [labelFieldDataCache sampleValue:i];
CPTLayer *newLabelLayer;
if ( isnan([dataValue doubleValue])) {
newLabelLayer = nil;
}
else {
newLabelLayer = [self cachedValueForKey:CPTPlotBindingDataLabels recordIndex:i];
if (((newLabelLayer == nil) || (newLabelLayer == nilObject)) && plotProvidesLabels ) {
if ( hasAttributedFormatter ) {
NSAttributedString *labelString = [dataLabelFormatter attributedStringForObjectValue:dataValue withDefaultAttributes:textAttributes];
newLabelLayer = [[CPTTextLayer alloc] initWithAttributedText:labelString];
}
else {
NSString *labelString = [dataLabelFormatter stringForObjectValue:dataValue];
newLabelLayer = [[CPTTextLayer alloc] initWithText:labelString style:dataLabelTextStyle];
}
}
if ( [newLabelLayer isKindOfClass:nullClass] || (newLabelLayer == nilObject)) {
newLabelLayer = nil;
}
}
newLabelLayer.shadow = theShadow;
CPTPlotSpaceAnnotation *labelAnnotation;
if ( i < oldLabelCount ) {
labelAnnotation = labelArray[i];
if ( newLabelLayer ) {
if ( [labelAnnotation isKindOfClass:nullClass] ) {
labelAnnotation = [[CPTPlotSpaceAnnotation alloc] initWithPlotSpace:thePlotSpace anchorPlotPoint:nil];
labelArray[i] = labelAnnotation;
[self addAnnotation:labelAnnotation];
}
}
else {
if ( [labelAnnotation isKindOfClass:annotationClass] ) {
labelArray[i] = nullObject;
[self removeAnnotation:labelAnnotation];
}
}
}
else {
if ( newLabelLayer ) {
labelAnnotation = [[CPTPlotSpaceAnnotation alloc] initWithPlotSpace:thePlotSpace anchorPlotPoint:nil];
[labelArray addObject:labelAnnotation];
[self addAnnotation:labelAnnotation];
}
else {
[labelArray addObject:nullObject];
}
}
if ( newLabelLayer ) {
labelAnnotation.contentLayer = newLabelLayer;
labelAnnotation.rotation = theRotation;
[self positionLabelAnnotation:labelAnnotation forIndex:i];
[self updateContentAnchorForLabel:labelAnnotation];
}
}
// remove labels that are no longer needed
while ( labelArray.count > sampleCount ) {
CPTAnnotation *oldAnnotation = labelArray[labelArray.count - 1];
if ( [oldAnnotation isKindOfClass:annotationClass] ) {
[self removeAnnotation:oldAnnotation];
}
[labelArray removeLastObject];
}
}
/** @brief Marks the receiver as needing to update a range of data labels before the content is next drawn.
* @param indexRange The index range needing update.
* @see setNeedsRelabel()
**/
-(void)relabelIndexRange:(NSRange)indexRange
{
self.labelIndexRange = indexRange;
self.needsRelabel = YES;
}
/// @cond
-(void)updateContentAnchorForLabel:(nonnull CPTPlotSpaceAnnotation *)label
{
if ( label && self.adjustLabelAnchors ) {
CGPoint displacement = label.displacement;
if ( CGPointEqualToPoint(displacement, CGPointZero)) {
displacement.y = CPTFloat(1.0); // put the label above the data point if zero displacement
}
CGFloat angle = CPTFloat(M_PI) + atan2(displacement.y, displacement.x) - label.rotation;
CGFloat newAnchorX = cos(angle);
CGFloat newAnchorY = sin(angle);
if ( ABS(newAnchorX) <= ABS(newAnchorY)) {
newAnchorX /= ABS(newAnchorY);
newAnchorY = signbit(newAnchorY) ? CPTFloat(-1.0) : CPTFloat(1.0);
}
else {
newAnchorY /= ABS(newAnchorX);
newAnchorX = signbit(newAnchorX) ? CPTFloat(-1.0) : CPTFloat(1.0);
}
label.contentAnchorPoint = CPTPointMake((newAnchorX + CPTFloat(1.0)) / CPTFloat(2.0), (newAnchorY + CPTFloat(1.0)) / CPTFloat(2.0));
}
}
/// @endcond
/**
* @brief Repositions all existing label annotations.
**/
-(void)repositionAllLabelAnnotations
{
CPTAnnotationArray *annotations = self.labelAnnotations;
NSUInteger labelCount = annotations.count;
Class annotationClass = [CPTAnnotation class];
for ( NSUInteger i = 0; i < labelCount; i++ ) {
CPTPlotSpaceAnnotation *annotation = annotations[i];
if ( [annotation isKindOfClass:annotationClass] ) {
[self positionLabelAnnotation:annotation forIndex:i];
[self updateContentAnchorForLabel:annotation];
}
}
}
#pragma mark -
#pragma mark Legends
/** @brief The number of legend entries provided by this plot.
* @return The number of legend entries.
**/
-(NSUInteger)numberOfLegendEntries
{
return 1;
}
/** @brief The title text of a legend entry.
* @param idx The index of the desired title.
* @return The title of the legend entry at the requested index.
**/
-(nullable NSString *)titleForLegendEntryAtIndex:(NSUInteger __unused)idx
{
NSString *legendTitle = self.title;
if ( !legendTitle ) {
id myIdentifier = self.identifier;
if ( [myIdentifier isKindOfClass:[NSString class]] ) {
legendTitle = (NSString *)myIdentifier;
}
}
return legendTitle;
}
/** @brief The styled title text of a legend entry.
* @param idx The index of the desired title.
* @return The styled title of the legend entry at the requested index.
**/
-(nullable NSAttributedString *)attributedTitleForLegendEntryAtIndex:(NSUInteger __unused)idx
{
NSAttributedString *legendTitle = self.attributedTitle;
if ( !legendTitle ) {
id myIdentifier = self.identifier;
if ( [myIdentifier isKindOfClass:[NSAttributedString class]] ) {
legendTitle = (NSAttributedString *)myIdentifier;
}
}
return legendTitle;
}
/** @brief Draws the legend swatch of a legend entry.
* Subclasses should call @super to draw the background fill and border.
* @param legend The legend being drawn.
* @param idx The index of the desired swatch.
* @param rect The bounding rectangle where the swatch should be drawn.
* @param context The graphics context to draw into.
**/
-(void)drawSwatchForLegend:(nonnull CPTLegend *)legend atIndex:(NSUInteger)idx inRect:(CGRect)rect inContext:(nonnull CGContextRef)context
{
id<CPTLegendDelegate> theDelegate = (id<CPTLegendDelegate>)self.delegate;
CPTFill *theFill = nil;
if ( [theDelegate respondsToSelector:@selector(legend:fillForSwatchAtIndex:forPlot:)] ) {
theFill = [theDelegate legend:legend fillForSwatchAtIndex:idx forPlot:self];
}
if ( !theFill ) {
theFill = legend.swatchFill;
}
CPTLineStyle *theLineStyle = nil;
if ( [theDelegate respondsToSelector:@selector(legend:lineStyleForSwatchAtIndex:forPlot:)] ) {
theLineStyle = [theDelegate legend:legend lineStyleForSwatchAtIndex:idx forPlot:self];
}
if ( !theLineStyle ) {
theLineStyle = legend.swatchBorderLineStyle;
}
if ( theFill || theLineStyle ) {
CGFloat radius = legend.swatchCornerRadius;
if ( theFill ) {
CGContextBeginPath(context);
CPTAddRoundedRectPath(context, CPTAlignIntegralRectToUserSpace(context, rect), radius);
[theFill fillPathInContext:context];
}
if ( theLineStyle ) {
[theLineStyle setLineStyleInContext:context];
CGContextBeginPath(context);
CPTAddRoundedRectPath(context, CPTAlignBorderedRectToUserSpace(context, rect, theLineStyle), radius);
[theLineStyle strokePathInContext:context];
}
}
}
#pragma mark -
#pragma mark Responder Chain and User interaction
/// @name User Interaction
/// @{
/**
* @brief Informs the receiver that the user has
* @if MacOnly pressed the mouse button. @endif
* @if iOSOnly started touching the screen. @endif
*
*
* If this plot has a delegate that responds to the
* @link CPTPlotDelegate::plot:dataLabelTouchDownAtRecordIndex: -plot:dataLabelTouchDownAtRecordIndex: @endlink or
* @link CPTPlotDelegate::plot:dataLabelTouchDownAtRecordIndex:withEvent: -plot:dataLabelTouchDownAtRecordIndex:withEvent: @endlink
* methods, the data labels are searched to find the index of the one containing the @par{interactionPoint}.
* The delegate method will be called and this method returns @YES if the @par{interactionPoint} is within a label.
* This method returns @NO if the @par{interactionPoint} is too far away from all of the data labels.
*
* @param event The OS event.
* @param interactionPoint The coordinates of the interaction.
* @return Whether the event was handled or not.
**/
-(BOOL)pointingDeviceDownEvent:(nonnull CPTNativeEvent *)event atPoint:(CGPoint)interactionPoint
{
self.pointingDeviceDownLabelIndex = NSNotFound;
CPTGraph *theGraph = self.graph;
if ( !theGraph || self.hidden ) {
return NO;
}
id<CPTPlotDelegate> theDelegate = (id<CPTPlotDelegate>)self.delegate;
if ( [theDelegate respondsToSelector:@selector(plot:dataLabelTouchDownAtRecordIndex:)] ||
[theDelegate respondsToSelector:@selector(plot:dataLabelTouchDownAtRecordIndex:withEvent:)] ||
[theDelegate respondsToSelector:@selector(plot:dataLabelWasSelectedAtRecordIndex:)] ||
[theDelegate respondsToSelector:@selector(plot:dataLabelWasSelectedAtRecordIndex:withEvent:)] ) {
// Inform delegate if a label was hit
CPTMutableAnnotationArray *labelArray = self.labelAnnotations;
NSUInteger labelCount = labelArray.count;
Class annotationClass = [CPTAnnotation class];
for ( NSUInteger idx = 0; idx < labelCount; idx++ ) {
CPTPlotSpaceAnnotation *annotation = labelArray[idx];
if ( [annotation isKindOfClass:annotationClass] ) {
CPTLayer *labelLayer = annotation.contentLayer;
if ( labelLayer && !labelLayer.hidden ) {
CGPoint labelPoint = [theGraph convertPoint:interactionPoint toLayer:labelLayer];
if ( CGRectContainsPoint(labelLayer.bounds, labelPoint)) {
self.pointingDeviceDownLabelIndex = idx;
BOOL handled = NO;
if ( [theDelegate respondsToSelector:@selector(plot:dataLabelTouchDownAtRecordIndex:)] ) {
handled = YES;
[theDelegate plot:self dataLabelTouchDownAtRecordIndex:idx];
}
if ( [theDelegate respondsToSelector:@selector(plot:dataLabelTouchDownAtRecordIndex:withEvent:)] ) {
handled = YES;
[theDelegate plot:self dataLabelTouchDownAtRecordIndex:idx withEvent:event];
}
if ( handled ) {
return YES;
}
}
}
}
}
}
return [super pointingDeviceDownEvent:event atPoint:interactionPoint];
}
/**
* @brief Informs the receiver that the user has
* @if MacOnly pressed the mouse button. @endif
* @if iOSOnly ended touching the screen. @endif
*
*
* If this plot has a delegate that responds to the
* @link CPTPlotDelegate::plot:dataLabelTouchUpAtRecordIndex: -plot:dataLabelTouchUpAtRecordIndex: @endlink or
* @link CPTPlotDelegate::plot:dataLabelTouchUpAtRecordIndex:withEvent: -plot:dataLabelTouchUpAtRecordIndex:withEvent: @endlink
* methods, the data labels are searched to find the index of the one containing the @par{interactionPoint}.
* The delegate method will be called and this method returns @YES if the @par{interactionPoint} is within a label.
* This method returns @NO if the @par{interactionPoint} is too far away from all of the data labels.
*
* If the data label being released is the same as the one that was pressed (see
* @link CPTPlot::pointingDeviceDownEvent:atPoint: -pointingDeviceDownEvent:atPoint: @endlink), if the delegate responds to the
* @link CPTPlotDelegate::plot:dataLabelWasSelectedAtRecordIndex: -plot:dataLabelWasSelectedAtRecordIndex: @endlink and/or
* @link CPTPlotDelegate::plot:dataLabelWasSelectedAtRecordIndex:withEvent: -plot:dataLabelWasSelectedAtRecordIndex:withEvent: @endlink
* methods, these will be called.
*
* @param event The OS event.
* @param interactionPoint The coordinates of the interaction.
* @return Whether the event was handled or not.
**/
-(BOOL)pointingDeviceUpEvent:(nonnull CPTNativeEvent *)event atPoint:(CGPoint)interactionPoint
{
NSUInteger selectedDownIndex = self.pointingDeviceDownLabelIndex;
self.pointingDeviceDownLabelIndex = NSNotFound;
CPTGraph *theGraph = self.graph;
if ( !theGraph || self.hidden ) {
return NO;
}
id<CPTPlotDelegate> theDelegate = (id<CPTPlotDelegate>)self.delegate;
if ( [theDelegate respondsToSelector:@selector(plot:dataLabelTouchUpAtRecordIndex:)] ||
[theDelegate respondsToSelector:@selector(plot:dataLabelTouchUpAtRecordIndex:withEvent:)] ||
[theDelegate respondsToSelector:@selector(plot:dataLabelWasSelectedAtRecordIndex:)] ||
[theDelegate respondsToSelector:@selector(plot:dataLabelWasSelectedAtRecordIndex:withEvent:)] ) {
// Inform delegate if a label was hit
CPTMutableAnnotationArray *labelArray = self.labelAnnotations;
NSUInteger labelCount = labelArray.count;
Class annotationClass = [CPTAnnotation class];
for ( NSUInteger idx = 0; idx < labelCount; idx++ ) {
CPTPlotSpaceAnnotation *annotation = labelArray[idx];
if ( [annotation isKindOfClass:annotationClass] ) {
CPTLayer *labelLayer = annotation.contentLayer;
if ( labelLayer && !labelLayer.hidden ) {
CGPoint labelPoint = [theGraph convertPoint:interactionPoint toLayer:labelLayer];
if ( CGRectContainsPoint(labelLayer.bounds, labelPoint)) {
BOOL handled = NO;
if ( [theDelegate respondsToSelector:@selector(plot:dataLabelTouchUpAtRecordIndex:)] ) {
handled = YES;
[theDelegate plot:self dataLabelTouchUpAtRecordIndex:idx];
}
if ( [theDelegate respondsToSelector:@selector(plot:dataLabelTouchUpAtRecordIndex:withEvent:)] ) {
handled = YES;
[theDelegate plot:self dataLabelTouchUpAtRecordIndex:idx withEvent:event];
}
if ( idx == selectedDownIndex ) {
if ( [theDelegate respondsToSelector:@selector(plot:dataLabelWasSelectedAtRecordIndex:)] ) {
handled = YES;
[theDelegate plot:self dataLabelWasSelectedAtRecordIndex:idx];
}
if ( [theDelegate respondsToSelector:@selector(plot:dataLabelWasSelectedAtRecordIndex:withEvent:)] ) {
handled = YES;
[theDelegate plot:self dataLabelWasSelectedAtRecordIndex:idx withEvent:event];
}
}
if ( handled ) {
return YES;
}
}
}
}
}
}
return [super pointingDeviceUpEvent:event atPoint:interactionPoint];
}
/// @}
#pragma mark -
#pragma mark Accessors
/// @cond
-(nullable CPTLayerArray *)dataLabels
{
return [self cachedArrayForKey:CPTPlotBindingDataLabels];
}
-(void)setDataLabels:(nullable CPTLayerArray *)newDataLabels
{
[self cacheArray:newDataLabels forKey:CPTPlotBindingDataLabels];
[self setNeedsRelabel];
}
-(void)setTitle:(nullable NSString *)newTitle
{
if ( newTitle != title ) {
title = [newTitle copy];
if ( !self.inTitleUpdate ) {
self.inTitleUpdate = YES;
self.attributedTitle = nil;
self.inTitleUpdate = NO;
[[NSNotificationCenter defaultCenter] postNotificationName:CPTLegendNeedsLayoutForPlotNotification object:self];
}
}
}
-(void)setAttributedTitle:(nullable NSAttributedString *)newTitle
{
if ( newTitle != attributedTitle ) {
attributedTitle = [newTitle copy];
if ( !self.inTitleUpdate ) {
self.inTitleUpdate = YES;
self.title = attributedTitle.string;
self.inTitleUpdate = NO;
[[NSNotificationCenter defaultCenter] postNotificationName:CPTLegendNeedsLayoutForPlotNotification object:self];
}
}
}
-(void)setDataSource:(nullable id<CPTPlotDataSource>)newSource
{
if ( newSource != dataSource ) {
dataSource = newSource;
[self setDataNeedsReloading];
}
}
-(void)setDataNeedsReloading:(BOOL)newDataNeedsReloading
{
if ( newDataNeedsReloading != dataNeedsReloading ) {
dataNeedsReloading = newDataNeedsReloading;
if ( dataNeedsReloading ) {
[self setNeedsDisplay];
}
}
}
-(nullable CPTPlotArea *)plotArea
{
CPTGraph *theGraph = self.graph;
return theGraph.plotAreaFrame.plotArea;
}
-(void)setNeedsRelabel:(BOOL)newNeedsRelabel
{
if ( newNeedsRelabel != needsRelabel ) {
needsRelabel = newNeedsRelabel;
if ( needsRelabel ) {
[self setNeedsLayout];
}
}
}
-(void)setShowLabels:(BOOL)newShowLabels
{
if ( newShowLabels != showLabels ) {
showLabels = newShowLabels;
if ( showLabels ) {
[self setNeedsLayout];
}
[self setNeedsRelabel];
}
}
-(void)setLabelTextStyle:(nullable CPTTextStyle *)newStyle
{
if ( newStyle != labelTextStyle ) {
labelTextStyle = [newStyle copy];
if ( labelTextStyle && !self.labelFormatter ) {
NSNumberFormatter *newFormatter = [[NSNumberFormatter alloc] init];
newFormatter.minimumIntegerDigits = 1;
newFormatter.maximumFractionDigits = 1;
newFormatter.minimumFractionDigits = 1;
self.labelFormatter = newFormatter;
}
self.needsRelabel = YES;
}
}
-(void)setLabelOffset:(CGFloat)newOffset
{
if ( newOffset != labelOffset ) {
labelOffset = newOffset;
[self repositionAllLabelAnnotations];
}
}
-(void)setLabelRotation:(CGFloat)newRotation
{
if ( newRotation != labelRotation ) {
labelRotation = newRotation;
Class annotationClass = [CPTAnnotation class];
for ( CPTPlotSpaceAnnotation *label in self.labelAnnotations ) {
if ( [label isKindOfClass:annotationClass] ) {
label.rotation = labelRotation;
[self updateContentAnchorForLabel:label];
}
}
}
}
-(void)setLabelFormatter:(nullable NSFormatter *)newTickLabelFormatter
{
if ( newTickLabelFormatter != labelFormatter ) {
labelFormatter = newTickLabelFormatter;
self.needsRelabel = YES;
}
}
-(void)setLabelShadow:(nullable CPTShadow *)newLabelShadow
{
if ( newLabelShadow != labelShadow ) {
labelShadow = newLabelShadow;
Class annotationClass = [CPTAnnotation class];
for ( CPTAnnotation *label in self.labelAnnotations ) {
if ( [label isKindOfClass:annotationClass] ) {
label.contentLayer.shadow = labelShadow;
}
}
}
}
-(void)setCachePrecision:(CPTPlotCachePrecision)newPrecision
{
if ( newPrecision != cachePrecision ) {
cachePrecision = newPrecision;
switch ( cachePrecision ) {
case CPTPlotCachePrecisionAuto:
// don't change data already in the cache
break;
case CPTPlotCachePrecisionDouble:
[self setCachedDataType:self.doubleDataType];
break;
case CPTPlotCachePrecisionDecimal:
[self setCachedDataType:self.decimalDataType];
break;
}
}
}
-(void)setAlignsPointsToPixels:(BOOL)newAlignsPointsToPixels
{
if ( newAlignsPointsToPixels != alignsPointsToPixels ) {
alignsPointsToPixels = newAlignsPointsToPixels;
[self setNeedsDisplay];
}
}
-(void)setHidden:(BOOL)newHidden
{
if ( newHidden != self.hidden ) {
super.hidden = newHidden;
[self setNeedsRelabel];
}
}
/// @endcond
@end
#pragma mark -
@implementation CPTPlot(AbstractMethods)
#pragma mark -
#pragma mark Fields
/** @brief Number of fields in a plot data record.
* @return The number of fields.
**/
-(NSUInteger)numberOfFields
{
return 0;
}
/** @brief Identifiers (enum values) identifying the fields.
* @return Array of NSNumber objects for the various field identifiers.
**/
-(nonnull CPTNumberArray *)fieldIdentifiers
{
return @[];
}
/** @brief The field identifiers that correspond to a particular coordinate.
* @param coord The coordinate for which the corresponding field identifiers are desired.
* @return Array of NSNumber objects for the field identifiers.
**/
-(nonnull CPTNumberArray *)fieldIdentifiersForCoordinate:(CPTCoordinate __unused)coord
{
return @[];
}
/** @brief The coordinate value that corresponds to a particular field identifier.
* @param field The field identifier for which the corresponding coordinate is desired.
* @return The coordinate that corresponds to a particular field identifier or #CPTCoordinateNone if there is no matching coordinate.
*/
-(CPTCoordinate)coordinateForFieldIdentifier:(NSUInteger __unused)field
{
return CPTCoordinateNone;
}
#pragma mark -
#pragma mark Data Labels
/** @brief Adjusts the position of the data label annotation for the plot point at the given index.
* @param label The annotation for the data label.
* @param idx The data index for the label.
**/
-(void)positionLabelAnnotation:(nonnull CPTPlotSpaceAnnotation *__unused)label forIndex:(NSUInteger __unused)idx
{
// do nothing--implementation provided by subclasses
}
#pragma mark -
#pragma mark User Interaction
/**
* @brief Determines the index of the data element that is under the given point.
* @param point The coordinates of the interaction.
* @return The index of the data point that is under the given point or @ref NSNotFound if none was found.
*/
-(NSUInteger)dataIndexFromInteractionPoint:(CGPoint __unused)point
{
return NSNotFound;
}
@end
| {
"content_hash": "48efbe4a8ddea6b6820a7c43de498ffe",
"timestamp": "",
"source": "github",
"line_count": 2315,
"max_line_length": 153,
"avg_line_length": 36.309719222462206,
"alnum_prop": 0.6219827022139739,
"repo_name": "bendermh/RombergLab",
"id": "f15d59c1a9bb9482a70c32d1157537ee0c3ecafd",
"size": "84058",
"binary": false,
"copies": "1",
"ref": "refs/heads/RombergLab-1.5",
"path": "CorePlot/framework/Source/CPTPlot.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "10827"
},
{
"name": "C++",
"bytes": "5632"
},
{
"name": "DTrace",
"bytes": "263"
},
{
"name": "HTML",
"bytes": "71714"
},
{
"name": "Objective-C",
"bytes": "2349859"
},
{
"name": "Python",
"bytes": "6566"
}
],
"symlink_target": ""
} |
/* $NetBSD: setprogname.c,v 1.3 2003/07/26 19:24:44 salo Exp $ */
/*
* Copyright (c) 2001 Christopher G. Demetriou
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed for the
* NetBSD Project. See http://www.NetBSD.org/ for
* information about NetBSD.
* 4. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: setprogname.c,v 1.3 2003/07/26 19:24:44 salo Exp $");
#endif /* LIBC_SCCS and not lint */
/* In NetBSD, the program name is set by crt0. It can't be overridden. */
#undef REALLY_SET_PROGNAME
#include <stdlib.h>
#ifdef REALLY_SET_PROGNAME
#include <string.h>
extern const char *__progname;
#endif
/*ARGSUSED*/
void
setprogname(const char *progname)
{
#ifdef REALLY_SET_PROGNAME
__progname = strrchr(progname, '/');
if (__progname == NULL)
__progname = progname;
else
__progname++;
#endif
}
| {
"content_hash": "d4b354ccad59e90f836da5500dd82146",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 76,
"avg_line_length": 38.10769230769231,
"alnum_prop": 0.7274929350020186,
"repo_name": "execunix/vinos",
"id": "489952371182e2354187a29e2ca545f2da57ffc7",
"size": "2477",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "lib/libc/gen/setprogname.c",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
require 'spec_helper'
describe "RailsAdmin Basic Update" do
subject { page }
describe "update with errors" do
before(:each) do
@player = FactoryGirl.create :player
visit rails_admin_edit_path(:model_name => "player", :id => @player.id)
end
it "should return to edit page" do
fill_in "player[name]", :with => ""
click_button "Save"
page.driver.status_code.should eql(406)
should have_selector "form", :action => "/admin/players/#{@player.id}"
end
end
describe "update and add another" do
before(:each) do
@player = FactoryGirl.create :player
visit rails_admin_edit_path(:model_name => "player", :id => @player.id)
fill_in "player[name]", :with => "Jackie Robinson"
fill_in "player[number]", :with => "42"
fill_in "player[position]", :with => "Second baseman"
check "player[suspended]"
click_button "Save"
@player = RailsAdmin::AbstractModel.new("Player").first
end
it "should update an object with correct attributes" do
@player.name.should eql("Jackie Robinson")
@player.number.should eql(42)
@player.position.should eql("Second baseman")
@player.should be_suspended
end
end
describe "update and edit" do
before(:each) do
@player = FactoryGirl.create :player
visit rails_admin_edit_path(:model_name => "player", :id => @player.id)
fill_in "player[name]", :with => "Jackie Robinson"
fill_in "player[number]", :with => "42"
fill_in "player[position]", :with => "Second baseman"
check "player[suspended]"
click_button "Save and edit"
@player.reload
end
it "should update an object with correct attributes" do
@player.name.should eql("Jackie Robinson")
@player.number.should eql(42)
@player.position.should eql("Second baseman")
@player.should be_suspended
end
end
describe "update with has-one association" do
before(:each) do
@player = FactoryGirl.create :player
@draft = FactoryGirl.create :draft
visit rails_admin_edit_path(:model_name => "player", :id => @player.id)
fill_in "player[name]", :with => "Jackie Robinson"
fill_in "player[number]", :with => "42"
fill_in "player[position]", :with => "Second baseman"
select "Draft ##{@draft.id}"
click_button "Save"
@player.reload
end
it "should update an object with correct attributes" do
@player.name.should eql("Jackie Robinson")
@player.number.should eql(42)
@player.position.should eql("Second baseman")
end
it "should update an object with correct associations" do
@draft.reload
@player.draft.should eql(@draft)
end
end
describe "update with has-many association", :given => ["a league exists", "three teams exist"] do
before(:each) do
@league = FactoryGirl.create :league
@divisions = 3.times.map { FactoryGirl.create :division }
visit rails_admin_edit_path(:model_name => "league", :id => @league.id)
fill_in "league[name]", :with => "National League"
select @divisions[0].name, :from => "league_division_ids"
click_button "Save"
@league.reload
@histories = RailsAdmin::History.where(:item => @league.id)
end
it "should update an object with correct attributes" do
@league.name.should eql("National League")
end
it "should update an object with correct associations" do
@divisions[0].reload
@league.divisions.should include(@divisions[0])
end
it "should not update an object with incorrect associations" do
@league.divisions.should_not include(@divisions[1])
@league.divisions.should_not include(@divisions[2])
end
it "should log a history message about the update" do
@histories.collect(&:message).should include("Added Divisions ##{@divisions[0].id} associations, Changed name")
end
describe "removing has-many associations" do
before(:each) do
visit rails_admin_edit_path(:model_name => "league", :id => @league.id)
unselect @divisions[0].name, :from => "league_division_ids"
click_button "Save"
@league.reload
@histories.reload
end
it "should have empty associations" do
@league.divisions.should be_empty
end
it "should log a message to history about removing associations" do
@histories.collect(&:message).should include("Removed Divisions ##{@divisions[0].id} associations")
end
end
end
describe "update with has-and-belongs-to-many association" do
before(:each) do
@teams = 3.times.map { FactoryGirl.create :team }
@fan = FactoryGirl.create :fan, :teams => [@teams[0]]
visit rails_admin_edit_path(:model_name => "fan", :id => @fan.id)
select @teams[1].name, :from => "fan_team_ids"
click_button "Save"
@fan.reload
end
it "should update an object with correct associations" do
@fan.teams.should include(@teams[0])
@fan.teams.should include(@teams[1])
end
it "should not update an object with incorrect associations" do
@fan.teams.should_not include(@teams[2])
end
end
describe "update with missing object" do
before(:each) do
page.driver.put(rails_admin_update_path(:model_name => "player", :id => 1), :params => {:player => {:name => "Jackie Robinson", :number => 42, :position => "Second baseman"}})
end
it "should raise NotFound" do
page.driver.status_code.should eql(404)
end
end
describe "update with invalid object" do
before(:each) do
@player = FactoryGirl.create :player
visit rails_admin_edit_path(:model_name => "player", :id => @player.id)
fill_in "player[name]", :with => "Jackie Robinson"
fill_in "player[number]", :with => "a"
fill_in "player[position]", :with => "Second baseman"
click_button "Save"
@player.reload
end
it "should show an error message" do
body.should have_content("Player failed to be updated")
end
end
describe "update with serialized objects" do
before(:each) do
@user = FactoryGirl.create :user
visit rails_admin_edit_path(:model_name => "user", :id => @user.id)
fill_in "user[roles]", :with => "[\"admin\", \"user\"]"
click_button "Save"
@user.reload
end
it "should save the serialized data" do
@user.roles.should eql(['admin','user'])
end
end
end
| {
"content_hash": "4dcf6636cc38468f28d9418129f798e5",
"timestamp": "",
"source": "github",
"line_count": 218,
"max_line_length": 181,
"avg_line_length": 29.894495412844037,
"alnum_prop": 0.6344943992634647,
"repo_name": "10to1/rails_admin",
"id": "7ab8c88a1f785cf10d1c71ef2d83ffbda93765fa",
"size": "6517",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/requests/basic/update/rails_admin_basic_update_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "122771"
},
{
"name": "Ruby",
"bytes": "317363"
}
],
"symlink_target": ""
} |
/**
*/
package fr.obeo.dsl.sPrototyper.impl;
import fr.obeo.dsl.sPrototyper.AcceleoExpression;
import fr.obeo.dsl.sPrototyper.SPrototyperPackage;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Acceleo Expression</b></em>'.
* <!-- end-user-doc -->
* <p>
* </p>
*
* @generated
*/
public class AcceleoExpressionImpl extends RequestOrCreateExpressionImpl implements AcceleoExpression
{
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected AcceleoExpressionImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return SPrototyperPackage.Literals.ACCELEO_EXPRESSION;
}
} //AcceleoExpressionImpl
| {
"content_hash": "3ea5153d6d994143e106cfe4461d9b9b",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 101,
"avg_line_length": 19.714285714285715,
"alnum_prop": 0.643719806763285,
"repo_name": "glefur/s-prototyper",
"id": "19e3504b9b5e5e356718834072ae3738767a3606",
"size": "828",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugins/fr.obeo.dsl.sprototyper/src-gen/fr/obeo/dsl/sPrototyper/impl/AcceleoExpressionImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GAP",
"bytes": "1287040"
},
{
"name": "Java",
"bytes": "6930613"
},
{
"name": "Xtend",
"bytes": "3152"
}
],
"symlink_target": ""
} |
Date and Time masks.
# Aliases
- datetime
# Options
## inputFormat
Format used to input the date
ex:
- dd/mm/yyyy
- mm/dd/yyyy
- dd.mm.yyyy HH:MM:ss
### Supported symbols
- d
Day of the month as digits; no leading zero for single-digit days.
- dd
Day of the month as digits; leading zero for single-digit days.
- ddd
Day of the week as a three-letter abbreviation.
- dddd
Day of the week as its full name.
- m
Month as digits; no leading zero for single-digit months.
- mm
Month as digits; leading zero for single-digit months.
- mmm
Month as a three-letter abbreviation.
- mmmm
Month as its full name.
- yy
Year as last two digits; leading zero for years less than 10.
- yyyy
Year as 4 digits.
- h
Hours; no leading zero for single-digit hours (12-hour clock).
- hh
Hours; leading zero for single-digit hours (12-hour clock).
- hx
Hours; no limit; x = number of digits ~ use as h2, h3, ...
-H
Hours; no leading zero for single-digit hours (24-hour clock).
- HH
Hours; leading zero for single-digit hours (24-hour clock).
- Hx
Hours; no limit; x = number of digits ~ use as H2, H3, ...
- M
Minutes; no leading zero for single-digit minutes. Uppercase M unlike CF timeFormat's m to avoid conflict with months.
- MM
Minutes; leading zero for single-digit minutes. Uppercase MM unlike CF timeFormat's mm to avoid conflict with months.
- s
Seconds; no leading zero for single-digit seconds.
- ss
Seconds; leading zero for single-digit seconds.
- l
Milliseconds. 3 digits.
- L
Milliseconds. 2 digits.
- t
Lowercase, single-character time marker string: a or p.
- tt
Two-character time marker string: am or pm.
- T
Single-character time marker string: A or P.
- TT
Two-character time marker string: AM or PM.
- Z
US timezone abbreviation, e.g. EST or MDT. With non-US timezones or in the Opera browser, the GMT/UTC offset is returned, e.g. GMT-0500
- o
GMT/UTC timezone offset, e.g. -0500 or +0230.
- S
The date's ordinal suffix (st, nd, rd, or th). Works well with d.
### Optional parts
To mark a part of the inputFormat as optional, use the [] as you would for other masks.
Ex.
inputFormat: "dd/mm/yyyy [HH]"
## displayFormat
Visual format when the input looses focus
## outputFormat
Unmasking format
## min
Minimum value.
This needs to be in the same format as the inputformat.
## max
Maximum value.
This needs to be in the same format as the inputformat.
## prefillYear
Enable/disable prefilling of the year.
Default: true
Although you can just over type the proposed value without deleting, many seems to see a problem with the year prediction.
This options is to disable this feature. | {
"content_hash": "1e59697e2b523a129aef1997399894b2",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 135,
"avg_line_length": 26.544554455445546,
"alnum_prop": 0.7154046997389034,
"repo_name": "RobinHerbots/Inputmask",
"id": "1579830bf362d40993feccb960d58140a2fa714b",
"size": "2704",
"binary": false,
"copies": "2",
"ref": "refs/heads/5.x",
"path": "README_date.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "829"
},
{
"name": "JavaScript",
"bytes": "551306"
}
],
"symlink_target": ""
} |
#ifndef GREP_SEARCH_H
#define GREP_SEARCH_H 1
#include <config.h>
#include <sys/types.h>
#include "mbsupport.h"
#include <wchar.h>
#include <wctype.h>
#include <regex.h>
#include "system.h"
#include "error.h"
#include "grep.h"
#include "kwset.h"
#include "xalloc.h"
/* searchutils.c */
extern void kwsinit (kwset_t *);
extern char *mbtolower (const char *, size_t *);
extern bool is_mb_middle (const char **, const char *, const char *, size_t);
/* dfasearch.c */
extern void GEAcompile (char const *, size_t, reg_syntax_t);
extern size_t EGexecute (char const *, size_t, size_t *, char const *);
/* kwsearch.c */
extern void Fcompile (char const *, size_t);
extern size_t Fexecute (char const *, size_t, size_t *, char const *);
/* pcresearch.c */
extern void Pcompile (char const *, size_t);
extern size_t Pexecute (char const *, size_t, size_t *, char const *);
#endif /* GREP_SEARCH_H */
| {
"content_hash": "e342f8f24164f111d34d381e760f68cd",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 77,
"avg_line_length": 22.625,
"alnum_prop": 0.6674033149171271,
"repo_name": "c9/node-gnu-tools",
"id": "3074407e7ecf8f7af056ac6ebcd6ba2556bf58fe",
"size": "1763",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "grep-src/src/search.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Awk",
"bytes": "3921"
},
{
"name": "Batchfile",
"bytes": "16119"
},
{
"name": "C",
"bytes": "7126588"
},
{
"name": "C++",
"bytes": "291988"
},
{
"name": "CMake",
"bytes": "32166"
},
{
"name": "Clojure",
"bytes": "4798"
},
{
"name": "Groff",
"bytes": "640328"
},
{
"name": "HTML",
"bytes": "591926"
},
{
"name": "JavaScript",
"bytes": "7085"
},
{
"name": "Logos",
"bytes": "100159"
},
{
"name": "Makefile",
"bytes": "192257"
},
{
"name": "Pascal",
"bytes": "26071"
},
{
"name": "Perl",
"bytes": "18230"
},
{
"name": "Shell",
"bytes": "819110"
},
{
"name": "Tcl",
"bytes": "21952"
},
{
"name": "TeX",
"bytes": "1186600"
},
{
"name": "Yacc",
"bytes": "40487"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_60) on Tue Aug 26 20:50:07 PDT 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.schema.TextField (Solr 4.10.0 API)</title>
<meta name="date" content="2014-08-26">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.schema.TextField (Solr 4.10.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/solr/schema/TextField.html" title="class in org.apache.solr.schema">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/schema/class-use/TextField.html" target="_top">Frames</a></li>
<li><a href="TextField.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.solr.schema.TextField" class="title">Uses of Class<br>org.apache.solr.schema.TextField</h2>
</div>
<div class="classUseContainer">No usage of org.apache.solr.schema.TextField</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/solr/schema/TextField.html" title="class in org.apache.solr.schema">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/schema/class-use/TextField.html" target="_top">Frames</a></li>
<li><a href="TextField.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2014 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| {
"content_hash": "0919684e1fe1fa61701d051d85ac6740",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 127,
"avg_line_length": 35.916030534351144,
"alnum_prop": 0.5904357066950053,
"repo_name": "jamesvanmil/solr_config",
"id": "f366c54b509417d55737190dcc58930fdbbab39c",
"size": "4705",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/solr-core/org/apache/solr/schema/class-use/TextField.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "310805"
},
{
"name": "JavaScript",
"bytes": "1019096"
},
{
"name": "Shell",
"bytes": "70598"
},
{
"name": "XSLT",
"bytes": "124615"
}
],
"symlink_target": ""
} |
#include "saveConfig.h"
#include <boost/filesystem.hpp>
#include <fstream>
#include <iostream>
#include <vector>
#include "stringTool.h"
namespace SaveConfig
{
ConfigItem::ConfigItem()
{
key = "";
value = "";
}
ConfigItem::ConfigItem(const std::string &key, const std::string &value)
{
this->key = key;
this->value = value;
}
int Config::pushItem(ConfigItem item)
{
_configList.push_back(item);
return 0;
}
int Config::load(const std::string &filename)
{
std::ifstream ifs;
ifs.open(filename);
if (!(ifs.is_open())) {
std::cerr << "Config:Can't open file:" << filename << std::endl;
return -1;
}
if (!(_configList.empty())) {
_configList.clear();
_configList.shrink_to_fit();
}
while (!(ifs.eof())) {
std::string line;
std::getline(ifs, line);
line = StringTool::strTrim(line);
if (line.c_str()[0] == '#') continue;
size_t equal = line.find("=");
if (equal == std::string::npos) continue;
std::vector<std::string> split = StringTool::strSep(line, equal, 1);
_configList.push_back(
ConfigItem(StringTool::strTrim(split[0]), StringTool::strTrim(split[1])));
}
ifs.close();
return 0;
}
int Config::save(const std::string &filename)
{
if (_configList.empty()) {
std::cerr << "Config:The config is empty" << std::endl;
return -3;
}
std::ifstream ifs;
ifs.open(filename);
if (!(ifs.is_open())) {
std::ofstream ofs2;
ofs2.open(filename, std::ofstream::trunc);
if (!(ofs2.is_open())) {
std::cerr << "Config:Can't create file:" << filename << std::endl;
return -1;
}
for (auto item : _configList) {
ofs2 << item.key << "\t=\t" << item.value << std::endl;
}
ofs2.close();
return 0;
}
std::string swapFile = filename;
swapFile += ".swp";
std::ofstream ofs;
ofs.open(swapFile, std::ofstream::trunc);
if (!(ifs.is_open())) {
std::cerr << "Config:Can't create file:" << swapFile << std::endl;
return -2;
}
int totalWrite = _configList.size();
char written[totalWrite];
int i;
for (i = 0; i < totalWrite; i++) written[i] = 0;
while (!(ifs.eof())) {
std::string line;
std::getline(ifs, line);
if (line == "" && ifs.eof()) break;
std::string trimline = StringTool::strTrim(line);
if (trimline.c_str()[0] == '#') {
ofs << line << std::endl;
continue;
}
size_t equal = line.find("=");
if (equal == std::string::npos) {
ofs << line << std::endl;
continue;
}
std::vector<std::string> split = StringTool::strSep(trimline, equal, 1);
std::string key = StringTool::strTrim(split[0]);
int index;
if ((index = getIndexByKey(key)) < 0) {
ofs << line << std::endl;
} else {
if (written[index] == 1)
std::cerr << "Config:Warning,the key:" << getKeyByIndex(index)
<< " has already be written" << std::endl;
ofs << getKeyByIndex(index) << "\t=\t" << getValueByIndex(index) << std::endl;
written[index] = 1;
}
}
for (i = 0; i < totalWrite; i++) {
if (!(written[i]))
ofs << getKeyByIndex(i) << "\t=\t" << getValueByIndex(i) << std::endl;
}
ifs.close();
ofs.close();
const boost::filesystem::path path(filename.c_str());
const boost::filesystem::path path2(swapFile.c_str());
try {
boost::filesystem::remove(path);
boost::filesystem::rename(path2, path);
} catch (boost::filesystem::filesystem_error &ex) {
std::cerr << "Config:Can't overwrite the config," << ex.what() << std::endl;
return -4;
}
return 0;
}
std::string Config::getValueByKey(const std::string &key)
{
return getValueByIndex(getIndexByKey(key));
}
std::string Config::getValueByIndex(int index)
{
if (index < 0 || index >= _configList.size()) return "";
return _configList[index].value;
}
std::string Config::getKeyByIndex(int index)
{
if (index < 0 || index >= _configList.size()) return "";
return _configList[index].key;
}
int Config::getIndexByKey(const std::string &key)
{
int i, maxi = _configList.size();
for (i = 0; i < maxi; i++) {
if (_configList[i].key == key) return i;
}
return -1;
}
int Config::setValueByKey(const std::string &value, const std::string &key)
{
int ret;
if ((ret = setValueByIndex(value, getIndexByKey(key))) < 0) {
pushItem(ConfigItem(key, value));
}
return ret;
}
int Config::setValueByIndex(const std::string &value, int index)
{
if (index < 0 || index >= _configList.size()) {
return -1;
} else {
_configList[index].value = value;
}
return 0;
}
}
| {
"content_hash": "8fa454ca4e393a9397207fa1e7f7c59c",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 94,
"avg_line_length": 31.178770949720672,
"alnum_prop": 0.4843218061279341,
"repo_name": "holmesfems/PasswordBook",
"id": "fc0b8e17c87975082fdc5a50b03a2e40250b53bd",
"size": "5739",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/saveConfig.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "338"
},
{
"name": "C++",
"bytes": "69928"
},
{
"name": "CMake",
"bytes": "8558"
},
{
"name": "HTML",
"bytes": "598"
},
{
"name": "JavaScript",
"bytes": "7271"
},
{
"name": "Makefile",
"bytes": "1047"
},
{
"name": "Protocol Buffer",
"bytes": "402"
},
{
"name": "Python",
"bytes": "749"
}
],
"symlink_target": ""
} |
package notify
import (
"bytes"
"crypto/sha256"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"mime"
"mime/multipart"
"net"
"net/http"
"net/mail"
"net/smtp"
"net/textproto"
"net/url"
"strings"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/common/model"
"github.com/prometheus/common/version"
"golang.org/x/net/context"
"golang.org/x/net/context/ctxhttp"
"github.com/prometheus/alertmanager/config"
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
)
type notifierConfig interface {
SendResolved() bool
}
// A Notifier notifies about alerts under constraints of the given context.
// It returns an error if unsuccessful and a flag whether the error is
// recoverable. This information is useful for a retry logic.
type Notifier interface {
Notify(context.Context, ...*types.Alert) (bool, error)
}
// An Integration wraps a notifier and its config to be uniquely identified by
// name and index from its origin in the configuration.
type Integration struct {
notifier Notifier
conf notifierConfig
name string
idx int
}
// Notify implements the Notifier interface.
func (i *Integration) Notify(ctx context.Context, alerts ...*types.Alert) (bool, error) {
var res []*types.Alert
// Resolved alerts have to be filtered only at this point, because they need
// to end up unfiltered in the SetNotifiesStage.
if i.conf.SendResolved() {
res = alerts
} else {
for _, a := range alerts {
if a.Status() != model.AlertResolved {
res = append(res, a)
}
}
}
if len(res) == 0 {
return false, nil
}
return i.notifier.Notify(ctx, res...)
}
// BuildReceiverIntegrations builds a list of integration notifiers off of a
// receivers config.
func BuildReceiverIntegrations(nc *config.Receiver, tmpl *template.Template, logger log.Logger) []Integration {
var (
integrations []Integration
add = func(name string, i int, n Notifier, nc notifierConfig) {
integrations = append(integrations, Integration{
notifier: n,
conf: nc,
name: name,
idx: i,
})
}
)
for i, c := range nc.WebhookConfigs {
n := NewWebhook(c, tmpl, logger)
add("webhook", i, n, c)
}
for i, c := range nc.EmailConfigs {
n := NewEmail(c, tmpl, logger)
add("email", i, n, c)
}
for i, c := range nc.PagerdutyConfigs {
n := NewPagerDuty(c, tmpl, logger)
add("pagerduty", i, n, c)
}
for i, c := range nc.OpsGenieConfigs {
n := NewOpsGenie(c, tmpl, logger)
add("opsgenie", i, n, c)
}
for i, c := range nc.WechatConfigs {
n := NewWechat(c, tmpl, logger)
add("wechat", i, n, c)
}
for i, c := range nc.SlackConfigs {
n := NewSlack(c, tmpl, logger)
add("slack", i, n, c)
}
for i, c := range nc.HipchatConfigs {
n := NewHipchat(c, tmpl, logger)
add("hipchat", i, n, c)
}
for i, c := range nc.VictorOpsConfigs {
n := NewVictorOps(c, tmpl, logger)
add("victorops", i, n, c)
}
for i, c := range nc.PushoverConfigs {
n := NewPushover(c, tmpl, logger)
add("pushover", i, n, c)
}
return integrations
}
const contentTypeJSON = "application/json"
var userAgentHeader = fmt.Sprintf("Alertmanager/%s", version.Version)
// Webhook implements a Notifier for generic webhooks.
type Webhook struct {
// The URL to which notifications are sent.
URL string
tmpl *template.Template
logger log.Logger
}
// NewWebhook returns a new Webhook.
func NewWebhook(conf *config.WebhookConfig, t *template.Template, l log.Logger) *Webhook {
return &Webhook{URL: conf.URL, tmpl: t, logger: l}
}
// WebhookMessage defines the JSON object send to webhook endpoints.
type WebhookMessage struct {
*template.Data
// The protocol version.
Version string `json:"version"`
GroupKey string `json:"groupKey"`
}
// Notify implements the Notifier interface.
func (w *Webhook) Notify(ctx context.Context, alerts ...*types.Alert) (bool, error) {
data := w.tmpl.Data(receiverName(ctx, w.logger), groupLabels(ctx, w.logger), alerts...)
groupKey, ok := GroupKey(ctx)
if !ok {
level.Error(w.logger).Log("msg", "group key missing")
}
msg := &WebhookMessage{
Version: "4",
Data: data,
GroupKey: groupKey,
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(msg); err != nil {
return false, err
}
req, err := http.NewRequest("POST", w.URL, &buf)
if err != nil {
return true, err
}
req.Header.Set("Content-Type", contentTypeJSON)
req.Header.Set("User-Agent", userAgentHeader)
resp, err := ctxhttp.Do(ctx, http.DefaultClient, req)
if err != nil {
return true, err
}
resp.Body.Close()
return w.retry(resp.StatusCode)
}
func (w *Webhook) retry(statusCode int) (bool, error) {
// Webhooks are assumed to respond with 2xx response codes on a successful
// request and 5xx response codes are assumed to be recoverable.
if statusCode/100 != 2 {
return (statusCode/100 == 5), fmt.Errorf("unexpected status code %v from %s", statusCode, w.URL)
}
return false, nil
}
// Email implements a Notifier for email notifications.
type Email struct {
conf *config.EmailConfig
tmpl *template.Template
logger log.Logger
}
// NewEmail returns a new Email notifier.
func NewEmail(c *config.EmailConfig, t *template.Template, l log.Logger) *Email {
if _, ok := c.Headers["Subject"]; !ok {
c.Headers["Subject"] = config.DefaultEmailSubject
}
if _, ok := c.Headers["To"]; !ok {
c.Headers["To"] = c.To
}
if _, ok := c.Headers["From"]; !ok {
c.Headers["From"] = c.From
}
return &Email{conf: c, tmpl: t, logger: l}
}
// auth resolves a string of authentication mechanisms.
func (n *Email) auth(mechs string) (smtp.Auth, error) {
username := n.conf.AuthUsername
for _, mech := range strings.Split(mechs, " ") {
switch mech {
case "CRAM-MD5":
secret := string(n.conf.AuthSecret)
if secret == "" {
continue
}
return smtp.CRAMMD5Auth(username, secret), nil
case "PLAIN":
password := string(n.conf.AuthPassword)
if password == "" {
continue
}
identity := n.conf.AuthIdentity
// We need to know the hostname for both auth and TLS.
host, _, err := net.SplitHostPort(n.conf.Smarthost)
if err != nil {
return nil, fmt.Errorf("invalid address: %s", err)
}
return smtp.PlainAuth(identity, username, password, host), nil
case "LOGIN":
password := string(n.conf.AuthPassword)
if password == "" {
continue
}
return LoginAuth(username, password), nil
}
}
return nil, nil
}
// Notify implements the Notifier interface.
func (n *Email) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
// We need to know the hostname for both auth and TLS.
var c *smtp.Client
host, port, err := net.SplitHostPort(n.conf.Smarthost)
if err != nil {
return false, fmt.Errorf("invalid address: %s", err)
}
if port == "465" {
conn, err := tls.Dial("tcp", n.conf.Smarthost, &tls.Config{ServerName: host})
if err != nil {
return true, err
}
c, err = smtp.NewClient(conn, n.conf.Smarthost)
if err != nil {
return true, err
}
} else {
// Connect to the SMTP smarthost.
c, err = smtp.Dial(n.conf.Smarthost)
if err != nil {
return true, err
}
}
defer c.Quit()
if n.conf.Hello != "" {
err := c.Hello(n.conf.Hello)
if err != nil {
return true, err
}
}
// Global Config guarantees RequireTLS is not nil
if *n.conf.RequireTLS {
if ok, _ := c.Extension("STARTTLS"); !ok {
return true, fmt.Errorf("require_tls: true (default), but %q does not advertise the STARTTLS extension", n.conf.Smarthost)
}
tlsConf := &tls.Config{ServerName: host}
if err := c.StartTLS(tlsConf); err != nil {
return true, fmt.Errorf("starttls failed: %s", err)
}
}
if ok, mech := c.Extension("AUTH"); ok {
auth, err := n.auth(mech)
if err != nil {
return true, err
}
if auth != nil {
if err := c.Auth(auth); err != nil {
return true, fmt.Errorf("%T failed: %s", auth, err)
}
}
}
var (
data = n.tmpl.Data(receiverName(ctx, n.logger), groupLabels(ctx, n.logger), as...)
tmpl = tmplText(n.tmpl, data, &err)
from = tmpl(n.conf.From)
to = tmpl(n.conf.To)
)
if err != nil {
return false, err
}
addrs, err := mail.ParseAddressList(from)
if err != nil {
return false, fmt.Errorf("parsing from addresses: %s", err)
}
if len(addrs) != 1 {
return false, fmt.Errorf("must be exactly one from address")
}
if err := c.Mail(addrs[0].Address); err != nil {
return true, fmt.Errorf("sending mail from: %s", err)
}
addrs, err = mail.ParseAddressList(to)
if err != nil {
return false, fmt.Errorf("parsing to addresses: %s", err)
}
for _, addr := range addrs {
if err := c.Rcpt(addr.Address); err != nil {
return true, fmt.Errorf("sending rcpt to: %s", err)
}
}
// Send the email body.
wc, err := c.Data()
if err != nil {
return true, err
}
defer wc.Close()
for header, t := range n.conf.Headers {
value, err := n.tmpl.ExecuteTextString(t, data)
if err != nil {
return false, fmt.Errorf("executing %q header template: %s", header, err)
}
fmt.Fprintf(wc, "%s: %s\r\n", header, mime.QEncoding.Encode("utf-8", value))
}
buffer := &bytes.Buffer{}
multipartWriter := multipart.NewWriter(buffer)
fmt.Fprintf(wc, "Date: %s\r\n", time.Now().Format(time.RFC1123Z))
fmt.Fprintf(wc, "Content-Type: multipart/alternative; boundary=%s\r\n", multipartWriter.Boundary())
fmt.Fprintf(wc, "MIME-Version: 1.0\r\n")
// TODO: Add some useful headers here, such as URL of the alertmanager
// and active/resolved.
fmt.Fprintf(wc, "\r\n")
if len(n.conf.Text) > 0 {
// Text template
w, err := multipartWriter.CreatePart(textproto.MIMEHeader{"Content-Type": {"text/plain; charset=UTF-8"}})
if err != nil {
return false, fmt.Errorf("creating part for text template: %s", err)
}
body, err := n.tmpl.ExecuteTextString(n.conf.Text, data)
if err != nil {
return false, fmt.Errorf("executing email text template: %s", err)
}
_, err = w.Write([]byte(body))
if err != nil {
return true, err
}
}
if len(n.conf.HTML) > 0 {
// Html template
// Preferred alternative placed last per section 5.1.4 of RFC 2046
// https://www.ietf.org/rfc/rfc2046.txt
w, err := multipartWriter.CreatePart(textproto.MIMEHeader{"Content-Type": {"text/html; charset=UTF-8"}})
if err != nil {
return false, fmt.Errorf("creating part for html template: %s", err)
}
body, err := n.tmpl.ExecuteHTMLString(n.conf.HTML, data)
if err != nil {
return false, fmt.Errorf("executing email html template: %s", err)
}
_, err = w.Write([]byte(body))
if err != nil {
return true, err
}
}
multipartWriter.Close()
wc.Write(buffer.Bytes())
return false, nil
}
// PagerDuty implements a Notifier for PagerDuty notifications.
type PagerDuty struct {
conf *config.PagerdutyConfig
tmpl *template.Template
logger log.Logger
}
// NewPagerDuty returns a new PagerDuty notifier.
func NewPagerDuty(c *config.PagerdutyConfig, t *template.Template, l log.Logger) *PagerDuty {
return &PagerDuty{conf: c, tmpl: t, logger: l}
}
const (
pagerDutyEventTrigger = "trigger"
pagerDutyEventResolve = "resolve"
)
type pagerDutyMessage struct {
RoutingKey string `json:"routing_key,omitempty"`
ServiceKey string `json:"service_key,omitempty"`
DedupKey string `json:"dedup_key,omitempty"`
IncidentKey string `json:"incident_key,omitempty"`
EventType string `json:"event_type,omitempty"`
Description string `json:"description,omitempty"`
EventAction string `json:"event_action"`
Payload *pagerDutyPayload `json:"payload"`
Client string `json:"client,omitempty"`
ClientURL string `json:"client_url,omitempty"`
Details map[string]string `json:"details,omitempty"`
}
type pagerDutyPayload struct {
Summary string `json:"summary"`
Source string `json:"source"`
Severity string `json:"severity"`
Timestamp string `json:"timestamp,omitempty"`
Class string `json:"class,omitempty"`
Component string `json:"component,omitempty"`
Group string `json:"group,omitempty"`
CustomDetails map[string]string `json:"custom_details,omitempty"`
}
func (n *PagerDuty) notifyV1(ctx context.Context, eventType, key string, tmpl func(string) string, details map[string]string, as ...*types.Alert) (bool, error) {
msg := &pagerDutyMessage{
ServiceKey: tmpl(string(n.conf.ServiceKey)),
EventType: eventType,
IncidentKey: hashKey(key),
Description: tmpl(n.conf.Description),
Details: details,
}
n.conf.URL = "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
if eventType == pagerDutyEventTrigger {
msg.Client = tmpl(n.conf.Client)
msg.ClientURL = tmpl(n.conf.ClientURL)
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(msg); err != nil {
return false, err
}
resp, err := ctxhttp.Post(ctx, http.DefaultClient, n.conf.URL, contentTypeJSON, &buf)
if err != nil {
return true, err
}
defer resp.Body.Close()
return n.retryV1(resp.StatusCode)
}
func (n *PagerDuty) notifyV2(ctx context.Context, eventType, key string, tmpl func(string) string, details map[string]string, as ...*types.Alert) (bool, error) {
if n.conf.Severity == "" {
n.conf.Severity = "error"
}
var payload *pagerDutyPayload
if eventType == pagerDutyEventTrigger {
payload = &pagerDutyPayload{
Summary: tmpl(n.conf.Description),
Source: tmpl(n.conf.Client),
Severity: tmpl(n.conf.Severity),
CustomDetails: details,
Class: tmpl(n.conf.Class),
Component: tmpl(n.conf.Component),
Group: tmpl(n.conf.Group),
}
}
msg := &pagerDutyMessage{
RoutingKey: tmpl(string(n.conf.RoutingKey)),
EventAction: eventType,
DedupKey: hashKey(key),
Payload: payload,
}
if eventType == pagerDutyEventTrigger {
msg.Client = tmpl(n.conf.Client)
msg.ClientURL = tmpl(n.conf.ClientURL)
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(msg); err != nil {
return false, err
}
resp, err := ctxhttp.Post(ctx, http.DefaultClient, n.conf.URL, contentTypeJSON, &buf)
if err != nil {
return true, err
}
defer resp.Body.Close()
return n.retryV2(resp.StatusCode)
}
// Notify implements the Notifier interface.
//
// https://v2.developer.pagerduty.com/docs/events-api-v2
func (n *PagerDuty) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
key, ok := GroupKey(ctx)
if !ok {
return false, fmt.Errorf("group key missing")
}
var err error
var (
alerts = types.Alerts(as...)
data = n.tmpl.Data(receiverName(ctx, n.logger), groupLabels(ctx, n.logger), as...)
tmpl = tmplText(n.tmpl, data, &err)
eventType = pagerDutyEventTrigger
)
if alerts.Status() == model.AlertResolved {
eventType = pagerDutyEventResolve
}
level.Debug(n.logger).Log("msg", "Notifying PagerDuty", "incident", key, "eventType", eventType)
details := make(map[string]string, len(n.conf.Details))
for k, v := range n.conf.Details {
details[k] = tmpl(v)
}
if err != nil {
return false, err
}
if n.conf.ServiceKey != "" {
return n.notifyV1(ctx, eventType, key, tmpl, details, as...)
}
return n.notifyV2(ctx, eventType, key, tmpl, details, as...)
}
func (n *PagerDuty) retryV1(statusCode int) (bool, error) {
// Retrying can solve the issue on 403 (rate limiting) and 5xx response codes.
// 2xx response codes indicate a successful request.
// https://v2.developer.pagerduty.com/docs/trigger-events
if statusCode/100 != 2 {
return (statusCode == 403 || statusCode/100 == 5), fmt.Errorf("unexpected status code %v", statusCode)
}
return false, nil
}
func (n *PagerDuty) retryV2(statusCode int) (bool, error) {
// Retrying can solve the issue on 429 (rate limiting) and 5xx response codes.
// 2xx response codes indicate a successful request.
// https://v2.developer.pagerduty.com/docs/events-api-v2#api-response-codes--retry-logic
if statusCode/100 != 2 {
return (statusCode == 429 || statusCode/100 == 5), fmt.Errorf("unexpected status code %v", statusCode)
}
return false, nil
}
// Slack implements a Notifier for Slack notifications.
type Slack struct {
conf *config.SlackConfig
tmpl *template.Template
logger log.Logger
}
// NewSlack returns a new Slack notification handler.
func NewSlack(c *config.SlackConfig, t *template.Template, l log.Logger) *Slack {
return &Slack{
conf: c,
tmpl: t,
logger: l,
}
}
// slackReq is the request for sending a slack notification.
type slackReq struct {
Channel string `json:"channel,omitempty"`
Username string `json:"username,omitempty"`
IconEmoji string `json:"icon_emoji,omitempty"`
IconURL string `json:"icon_url,omitempty"`
LinkNames bool `json:"link_names,omitempty"`
Attachments []slackAttachment `json:"attachments"`
}
// slackAttachment is used to display a richly-formatted message block.
type slackAttachment struct {
Title string `json:"title,omitempty"`
TitleLink string `json:"title_link,omitempty"`
Pretext string `json:"pretext,omitempty"`
Text string `json:"text"`
Fallback string `json:"fallback"`
Fields []slackAttachmentField `json:"fields"`
Footer string `json:"footer"`
Color string `json:"color,omitempty"`
MrkdwnIn []string `json:"mrkdwn_in,omitempty"`
}
// slackAttachmentField is displayed in a table inside the message attachment.
type slackAttachmentField struct {
Title string `json:"title"`
Value string `json:"value"`
Short bool `json:"short,omitempty"`
}
// Notify implements the Notifier interface.
func (n *Slack) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
var err error
var (
data = n.tmpl.Data(receiverName(ctx, n.logger), groupLabels(ctx, n.logger), as...)
tmplText = tmplText(n.tmpl, data, &err)
)
attachment := &slackAttachment{
Title: tmplText(n.conf.Title),
TitleLink: tmplText(n.conf.TitleLink),
Pretext: tmplText(n.conf.Pretext),
Text: tmplText(n.conf.Text),
Fallback: tmplText(n.conf.Fallback),
Footer: tmplText(n.conf.Footer),
Color: tmplText(n.conf.Color),
MrkdwnIn: []string{"fallback", "pretext", "text"},
}
var numFields = len(n.conf.Fields)
if numFields > 0 {
var fields = make([]slackAttachmentField, numFields)
for k, v := range n.conf.Fields {
fields[k] = slackAttachmentField{
tmplText(v["title"]),
tmplText(v["value"]),
n.conf.ShortFields,
}
}
attachment.Fields = fields
}
req := &slackReq{
Channel: tmplText(n.conf.Channel),
Username: tmplText(n.conf.Username),
IconEmoji: tmplText(n.conf.IconEmoji),
IconURL: tmplText(n.conf.IconURL),
LinkNames: n.conf.LinkNames,
Attachments: []slackAttachment{*attachment},
}
if err != nil {
return false, err
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(req); err != nil {
return false, err
}
resp, err := ctxhttp.Post(ctx, http.DefaultClient, string(n.conf.APIURL), contentTypeJSON, &buf)
if err != nil {
return true, err
}
resp.Body.Close()
return n.retry(resp.StatusCode)
}
func (n *Slack) retry(statusCode int) (bool, error) {
// Only 5xx response codes are recoverable and 2xx codes are successful.
// https://api.slack.com/incoming-webhooks#handling_errors
// https://api.slack.com/changelog/2016-05-17-changes-to-errors-for-incoming-webhooks
if statusCode/100 != 2 {
return (statusCode/100 == 5), fmt.Errorf("unexpected status code %v", statusCode)
}
return false, nil
}
// Hipchat implements a Notifier for Hipchat notifications.
type Hipchat struct {
conf *config.HipchatConfig
tmpl *template.Template
logger log.Logger
}
// NewHipchat returns a new Hipchat notification handler.
func NewHipchat(c *config.HipchatConfig, t *template.Template, l log.Logger) *Hipchat {
return &Hipchat{
conf: c,
tmpl: t,
logger: l,
}
}
type hipchatReq struct {
From string `json:"from"`
Notify bool `json:"notify"`
Message string `json:"message"`
MessageFormat string `json:"message_format"`
Color string `json:"color"`
}
// Notify implements the Notifier interface.
func (n *Hipchat) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
var err error
var msg string
var (
data = n.tmpl.Data(receiverName(ctx, n.logger), groupLabels(ctx, n.logger), as...)
tmplText = tmplText(n.tmpl, data, &err)
tmplHTML = tmplHTML(n.tmpl, data, &err)
url = fmt.Sprintf("%sv2/room/%s/notification?auth_token=%s", n.conf.APIURL, n.conf.RoomID, n.conf.AuthToken)
)
if n.conf.MessageFormat == "html" {
msg = tmplHTML(n.conf.Message)
} else {
msg = tmplText(n.conf.Message)
}
req := &hipchatReq{
From: tmplText(n.conf.From),
Notify: n.conf.Notify,
Message: msg,
MessageFormat: n.conf.MessageFormat,
Color: tmplText(n.conf.Color),
}
if err != nil {
return false, err
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(req); err != nil {
return false, err
}
resp, err := ctxhttp.Post(ctx, http.DefaultClient, url, contentTypeJSON, &buf)
if err != nil {
return true, err
}
defer resp.Body.Close()
return n.retry(resp.StatusCode)
}
func (n *Hipchat) retry(statusCode int) (bool, error) {
// Response codes 429 (rate limiting) and 5xx can potentially recover. 2xx
// responce codes indicate successful requests.
// https://developer.atlassian.com/hipchat/guide/hipchat-rest-api/api-response-codes
if statusCode/100 != 2 {
return (statusCode == 429 || statusCode/100 == 5), fmt.Errorf("unexpected status code %v", statusCode)
}
return false, nil
}
// Wechat implements a Notfier for wechat notifications
type Wechat struct {
conf *config.WechatConfig
tmpl *template.Template
logger log.Logger
accessToken string
accessTokenAt time.Time
}
// Wechat AccessToken with corpid and corpsecret.
type WechatToken struct {
AccessToken string `json:"access_token"`
// Catches all undefined fields and must be empty after parsing.
XXX map[string]interface{} `json:"-"`
}
type weChatMessage struct {
Text weChatMessageContent `yaml:"text,omitempty" json:"text,omitempty"`
ToUser string `yaml:"touser,omitempty" json:"touser,omitempty"`
ToParty string `yaml:"toparty,omitempty" json:"toparty,omitempty"`
Totag string `yaml:"totag,omitempty" json:"totag,omitempty"`
AgentID string `yaml:"agentid,omitempty" json:"agentid,omitempty"`
Safe string `yaml:"safe,omitempty" json:"safe,omitempty"`
Type string `yaml:"msgtype,omitempty" json:"msgtype,omitempty"`
}
type weChatMessageContent struct {
Content string `json:"content"`
}
type weChatResponse struct {
Code int `json:"code"`
Error string `json:"error"`
}
// NewWechat returns a new Wechat notifier.
func NewWechat(c *config.WechatConfig, t *template.Template, l log.Logger) *Wechat {
return &Wechat{conf: c, tmpl: t, logger: l}
}
// Notify implements the Notifier interface.
func (n *Wechat) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
key, ok := GroupKey(ctx)
if !ok {
return false, fmt.Errorf("group key missing")
}
level.Debug(n.logger).Log("msg", "Notifying Wechat", "incident", key)
data := n.tmpl.Data(receiverName(ctx, n.logger), groupLabels(ctx, n.logger), as...)
var err error
tmpl := tmplText(n.tmpl, data, &err)
if err != nil {
return false, err
}
// Refresh AccessToken over 2 hours
if n.accessToken == "" || time.Now().Sub(n.accessTokenAt) > 2*time.Hour {
parameters := url.Values{}
parameters.Add("corpsecret", tmpl(string(n.conf.APISecret)))
parameters.Add("corpid", tmpl(string(n.conf.CorpID)))
apiURL := n.conf.APIURL + "gettoken"
u, err := url.Parse(apiURL)
if err != nil {
return false, err
}
u.RawQuery = parameters.Encode()
level.Debug(n.logger).Log("msg", "Sending Wechat message", "incident", key, "url", u.String())
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
return true, err
}
req.Header.Set("Content-Type", contentTypeJSON)
resp, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
return true, err
}
defer resp.Body.Close()
var wechatToken WechatToken
if err := json.NewDecoder(resp.Body).Decode(&wechatToken); err != nil {
return false, err
}
if wechatToken.AccessToken == "" {
return false, fmt.Errorf("invalid APISecret for CorpID: %s", n.conf.CorpID)
}
// Cache accessToken
n.accessToken = wechatToken.AccessToken
n.accessTokenAt = time.Now()
}
msg := &weChatMessage{
Text: weChatMessageContent{
Content: tmpl(n.conf.Message),
},
ToUser: n.conf.ToUser,
ToParty: n.conf.ToParty,
Totag: n.conf.ToTag,
AgentID: n.conf.AgentID,
Type: "text",
Safe: "0",
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(msg); err != nil {
return false, err
}
postMessageURL := n.conf.APIURL + "message/send?access_token=" + n.accessToken
req, err := http.NewRequest(http.MethodPost, postMessageURL, &buf)
if err != nil {
return true, err
}
resp, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
return true, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
level.Debug(n.logger).Log("msg", "response: "+string(body), "incident", key)
if resp.StatusCode != 200 {
return true, fmt.Errorf("unexpected status code %v", resp.StatusCode)
} else {
var weResp weChatResponse
if err := json.Unmarshal(body, &weResp); err != nil {
return true, err
}
// https://work.weixin.qq.com/api/doc#10649
if weResp.Code == 0 {
return false, nil
}
// AccessToken is expired
if weResp.Code == 42001 {
n.accessToken = ""
return true, errors.New(weResp.Error)
}
return false, errors.New(weResp.Error)
}
}
// OpsGenie implements a Notifier for OpsGenie notifications.
type OpsGenie struct {
conf *config.OpsGenieConfig
tmpl *template.Template
logger log.Logger
}
// NewOpsGenie returns a new OpsGenie notifier.
func NewOpsGenie(c *config.OpsGenieConfig, t *template.Template, l log.Logger) *OpsGenie {
return &OpsGenie{conf: c, tmpl: t, logger: l}
}
type opsGenieCreateMessage struct {
Alias string `json:"alias"`
Message string `json:"message"`
Description string `json:"description,omitempty"`
Details map[string]string `json:"details"`
Source string `json:"source"`
Teams []map[string]string `json:"teams,omitempty"`
Tags []string `json:"tags,omitempty"`
Note string `json:"note,omitempty"`
Priority string `json:"priority,omitempty"`
}
type opsGenieCloseMessage struct {
Source string `json:"source"`
}
// Notify implements the Notifier interface.
func (n *OpsGenie) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
req, retry, err := n.createRequest(ctx, as...)
if err != nil {
return retry, err
}
resp, err := ctxhttp.Do(ctx, http.DefaultClient, req)
if err != nil {
return true, err
}
defer resp.Body.Close()
return n.retry(resp.StatusCode)
}
// Like Split but filter out empty strings.
func safeSplit(s string, sep string) []string {
a := strings.Split(strings.TrimSpace(s), sep)
b := a[:0]
for _, x := range a {
if x != "" {
b = append(b, x)
}
}
return b
}
// Create requests for a list of alerts.
func (n *OpsGenie) createRequest(ctx context.Context, as ...*types.Alert) (*http.Request, bool, error) {
key, ok := GroupKey(ctx)
if !ok {
return nil, false, fmt.Errorf("group key missing")
}
data := n.tmpl.Data(receiverName(ctx, n.logger), groupLabels(ctx, n.logger), as...)
level.Debug(n.logger).Log("msg", "Notifying OpsGenie", "incident", key)
var err error
tmpl := tmplText(n.tmpl, data, &err)
details := make(map[string]string, len(n.conf.Details))
for k, v := range n.conf.Details {
details[k] = tmpl(v)
}
var (
msg interface{}
apiURL string
alias = hashKey(key)
alerts = types.Alerts(as...)
)
switch alerts.Status() {
case model.AlertResolved:
apiURL = fmt.Sprintf("%sv2/alerts/%s/close?identifierType=alias", n.conf.APIURL, alias)
msg = &opsGenieCloseMessage{Source: tmpl(n.conf.Source)}
default:
message := tmpl(n.conf.Message)
if len(message) > 130 {
message = message[:127] + "..."
level.Debug(n.logger).Log("msg", "Truncated message to %q due to OpsGenie message limit", "truncated_message", message, "incident", key)
}
apiURL = n.conf.APIURL + "v2/alerts"
var teams []map[string]string
for _, t := range safeSplit(string(tmpl(n.conf.Teams)), ",") {
teams = append(teams, map[string]string{"name": t})
}
tags := safeSplit(string(tmpl(n.conf.Tags)), ",")
msg = &opsGenieCreateMessage{
Alias: alias,
Message: message,
Description: tmpl(n.conf.Description),
Details: details,
Source: tmpl(n.conf.Source),
Teams: teams,
Tags: tags,
Note: tmpl(n.conf.Note),
Priority: tmpl(n.conf.Priority),
}
}
if err != nil {
return nil, false, fmt.Errorf("templating error: %s", err)
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(msg); err != nil {
return nil, false, err
}
req, err := http.NewRequest("POST", apiURL, &buf)
if err != nil {
return nil, true, err
}
req.Header.Set("Content-Type", contentTypeJSON)
req.Header.Set("Authorization", fmt.Sprintf("GenieKey %s", n.conf.APIKey))
return req, true, nil
}
func (n *OpsGenie) retry(statusCode int) (bool, error) {
// https://docs.opsgenie.com/docs/response#section-response-codes
// Response codes 429 (rate limiting) and 5xx are potentially recoverable
if statusCode/100 == 5 || statusCode == 429 {
return true, fmt.Errorf("unexpected status code %v", statusCode)
} else if statusCode/100 != 2 {
return false, fmt.Errorf("unexpected status code %v", statusCode)
}
return false, nil
}
// VictorOps implements a Notifier for VictorOps notifications.
type VictorOps struct {
conf *config.VictorOpsConfig
tmpl *template.Template
logger log.Logger
}
// NewVictorOps returns a new VictorOps notifier.
func NewVictorOps(c *config.VictorOpsConfig, t *template.Template, l log.Logger) *VictorOps {
return &VictorOps{
conf: c,
tmpl: t,
logger: l,
}
}
const (
victorOpsEventTrigger = "CRITICAL"
victorOpsEventResolve = "RECOVERY"
)
type victorOpsMessage struct {
MessageType string `json:"message_type"`
EntityID string `json:"entity_id"`
EntityDisplayName string `json:"entity_display_name"`
StateMessage string `json:"state_message"`
MonitoringTool string `json:"monitoring_tool"`
}
type victorOpsErrorResponse struct {
Result string `json:"result"`
Message string `json:"message"`
}
// Notify implements the Notifier interface.
func (n *VictorOps) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
victorOpsAllowedEvents := map[string]bool{
"INFO": true,
"WARNING": true,
"CRITICAL": true,
}
key, ok := GroupKey(ctx)
if !ok {
return false, fmt.Errorf("group key missing")
}
var err error
var (
alerts = types.Alerts(as...)
data = n.tmpl.Data(receiverName(ctx, n.logger), groupLabels(ctx, n.logger), as...)
tmpl = tmplText(n.tmpl, data, &err)
apiURL = fmt.Sprintf("%s%s/%s", n.conf.APIURL, n.conf.APIKey, tmpl(n.conf.RoutingKey))
messageType = tmpl(n.conf.MessageType)
stateMessage = tmpl(n.conf.StateMessage)
)
if alerts.Status() == model.AlertFiring && !victorOpsAllowedEvents[messageType] {
messageType = victorOpsEventTrigger
}
if alerts.Status() == model.AlertResolved {
messageType = victorOpsEventResolve
}
if len(stateMessage) > 20480 {
stateMessage = stateMessage[0:20475] + "\n..."
level.Debug(n.logger).Log("msg", "Truncated stateMessage due to VictorOps stateMessage limit", "truncated_state_message", stateMessage, "incident", key)
}
msg := &victorOpsMessage{
MessageType: messageType,
EntityID: hashKey(key),
EntityDisplayName: tmpl(n.conf.EntityDisplayName),
StateMessage: stateMessage,
MonitoringTool: tmpl(n.conf.MonitoringTool),
}
if err != nil {
return false, fmt.Errorf("templating error: %s", err)
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(msg); err != nil {
return false, err
}
resp, err := ctxhttp.Post(ctx, http.DefaultClient, apiURL, contentTypeJSON, &buf)
if err != nil {
return true, err
}
defer resp.Body.Close()
return n.retry(resp.StatusCode)
}
func (n *VictorOps) retry(statusCode int) (bool, error) {
// Missing documentation therefore assuming only 5xx response codes are
// recoverable.
if statusCode/100 == 5 {
return true, fmt.Errorf("unexpected status code %v", statusCode)
} else if statusCode/100 != 2 {
return false, fmt.Errorf("unexpected status code %v", statusCode)
}
return false, nil
}
// Pushover implements a Notifier for Pushover notifications.
type Pushover struct {
conf *config.PushoverConfig
tmpl *template.Template
logger log.Logger
}
// NewPushover returns a new Pushover notifier.
func NewPushover(c *config.PushoverConfig, t *template.Template, l log.Logger) *Pushover {
return &Pushover{conf: c, tmpl: t, logger: l}
}
// Notify implements the Notifier interface.
func (n *Pushover) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
key, ok := GroupKey(ctx)
if !ok {
return false, fmt.Errorf("group key missing")
}
data := n.tmpl.Data(receiverName(ctx, n.logger), groupLabels(ctx, n.logger), as...)
level.Debug(n.logger).Log("msg", "Notifying Pushover", "incident", key)
var err error
tmpl := tmplText(n.tmpl, data, &err)
parameters := url.Values{}
parameters.Add("token", tmpl(string(n.conf.Token)))
parameters.Add("user", tmpl(string(n.conf.UserKey)))
title := tmpl(n.conf.Title)
if len(title) > 250 {
title = title[:247] + "..."
level.Debug(n.logger).Log("msg", "Truncated title due to Pushover title limit", "truncated_title", title, "incident", key)
}
parameters.Add("title", title)
message := tmpl(n.conf.Message)
if len(message) > 1024 {
message = message[:1021] + "..."
level.Debug(n.logger).Log("msg", "Truncated message due to Pushover message limit", "truncated_message", message, "incident", key)
}
message = strings.TrimSpace(message)
if message == "" {
// Pushover rejects empty messages.
message = "(no details)"
}
parameters.Add("message", message)
supplementaryURL := tmpl(n.conf.URL)
if len(supplementaryURL) > 512 {
supplementaryURL = supplementaryURL[:509] + "..."
level.Debug(n.logger).Log("msg", "Truncated URL due to Pushover url limit", "truncated_url", supplementaryURL, "incident", key)
}
parameters.Add("url", supplementaryURL)
parameters.Add("priority", tmpl(n.conf.Priority))
parameters.Add("retry", fmt.Sprintf("%d", int64(time.Duration(n.conf.Retry).Seconds())))
parameters.Add("expire", fmt.Sprintf("%d", int64(time.Duration(n.conf.Expire).Seconds())))
if err != nil {
return false, err
}
apiURL := "https://api.pushover.net/1/messages.json"
u, err := url.Parse(apiURL)
if err != nil {
return false, err
}
u.RawQuery = parameters.Encode()
level.Debug(n.logger).Log("msg", "Sending Pushover message", "incident", key, "url", u.String())
resp, err := ctxhttp.Post(ctx, http.DefaultClient, u.String(), "text/plain", nil)
if err != nil {
return true, err
}
defer resp.Body.Close()
return n.retry(resp.StatusCode)
}
func (n *Pushover) retry(statusCode int) (bool, error) {
// Only documented behaviour is that 2xx response codes are successful and
// 4xx are unsuccessful, therefore assuming only 5xx are recoverable.
// https://pushover.net/api#response
if statusCode/100 == 5 {
return true, fmt.Errorf("unexpected status code %v", statusCode)
} else if statusCode/100 != 2 {
return false, fmt.Errorf("unexpected status code %v", statusCode)
}
return false, nil
}
func tmplText(tmpl *template.Template, data *template.Data, err *error) func(string) string {
return func(name string) (s string) {
if *err != nil {
return
}
s, *err = tmpl.ExecuteTextString(name, data)
return s
}
}
func tmplHTML(tmpl *template.Template, data *template.Data, err *error) func(string) string {
return func(name string) (s string) {
if *err != nil {
return
}
s, *err = tmpl.ExecuteHTMLString(name, data)
return s
}
}
type loginAuth struct {
username, password string
}
func LoginAuth(username, password string) smtp.Auth {
return &loginAuth{username, password}
}
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
return "LOGIN", []byte{}, nil
}
// Used for AUTH LOGIN. (Maybe password should be encrypted)
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if more {
switch strings.ToLower(string(fromServer)) {
case "username:":
return []byte(a.username), nil
case "password:":
return []byte(a.password), nil
default:
return nil, errors.New("unexpected server challenge")
}
}
return nil, nil
}
// hashKey returns the sha256 for a group key as integrations may have
// maximum length requirements on deduplication keys.
func hashKey(s string) string {
h := sha256.New()
h.Write([]byte(s))
return fmt.Sprintf("%x", h.Sum(nil))
}
| {
"content_hash": "3270a7621d53751d966fca3fde31fb36",
"timestamp": "",
"source": "github",
"line_count": 1336,
"max_line_length": 161,
"avg_line_length": 28.119011976047904,
"alnum_prop": 0.6705885484600846,
"repo_name": "tyrken/alertmanager",
"id": "179290baca1f0d7e6aedf17ce6a9544472ec71d0",
"size": "38153",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "notify/impl.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "4341"
},
{
"name": "Go",
"bytes": "291781"
},
{
"name": "HTML",
"bytes": "20920"
},
{
"name": "JavaScript",
"bytes": "17193"
},
{
"name": "Makefile",
"bytes": "2070"
},
{
"name": "Protocol Buffer",
"bytes": "3910"
},
{
"name": "Shell",
"bytes": "1096"
}
],
"symlink_target": ""
} |
require "spec_helper"
describe CanCan::Ability do
before(:each) do
@ability = Object.new
@ability.extend(CanCan::Ability)
end
it "should be able to :read anything" do
@ability.can :read, :all
@ability.can?(:read, String).should be_true
@ability.can?(:read, 123).should be_true
end
it "should not have permission to do something it doesn't know about" do
@ability.can?(:foodfight, String).should be_false
end
it "should pass true to `can?` when non false/nil is returned in block" do
@ability.can :read, :all
@ability.can :read, Symbol do |sym|
"foo" # TODO test that sym is nil when no instance is passed
end
@ability.can?(:read, :some_symbol).should == true
end
it "should pass nil to a block when no instance is passed" do
@ability.can :read, Symbol do |sym|
sym.should be_nil
true
end
@ability.can?(:read, Symbol).should be_true
end
it "should pass to previous rule, if block returns false or nil" do
@ability.can :read, Symbol
@ability.can :read, Integer do |i|
i < 5
end
@ability.can :read, Integer do |i|
i > 10
end
@ability.can?(:read, Symbol).should be_true
@ability.can?(:read, 11).should be_true
@ability.can?(:read, 1).should be_true
@ability.can?(:read, 6).should be_false
end
it "should not pass class with object if :all objects are accepted" do
@ability.can :preview, :all do |object|
object.should == 123
@block_called = true
end
@ability.can?(:preview, 123)
@block_called.should be_true
end
it "should not call block when only class is passed, only return true" do
@block_called = false
@ability.can :preview, :all do |object|
@block_called = true
end
@ability.can?(:preview, Hash).should be_true
@block_called.should be_false
end
it "should pass only object for global manage actions" do
@ability.can :manage, String do |object|
object.should == "foo"
@block_called = true
end
@ability.can?(:stuff, "foo").should
@block_called.should be_true
end
it "should alias update or destroy actions to modify action" do
@ability.alias_action :update, :destroy, :to => :modify
@ability.can :modify, :all
@ability.can?(:update, 123).should be_true
@ability.can?(:destroy, 123).should be_true
end
it "should allow deeply nested aliased actions" do
@ability.alias_action :increment, :to => :sort
@ability.alias_action :sort, :to => :modify
@ability.can :modify, :all
@ability.can?(:increment, 123).should be_true
end
it "should raise an Error if alias target is an exist action" do
lambda{ @ability.alias_action :show, :to => :show }.should raise_error(CanCan::Error, "You can't specify target (show) as alias because it is real action name")
end
it "should always call block with arguments when passing no arguments to can" do
@ability.can do |action, object_class, object|
action.should == :foo
object_class.should == 123.class
object.should == 123
@block_called = true
end
@ability.can?(:foo, 123)
@block_called.should be_true
end
it "should pass nil to object when comparing class with can check" do
@ability.can do |action, object_class, object|
action.should == :foo
object_class.should == Hash
object.should be_nil
@block_called = true
end
@ability.can?(:foo, Hash)
@block_called.should be_true
end
it "should automatically alias index and show into read calls" do
@ability.can :read, :all
@ability.can?(:index, 123).should be_true
@ability.can?(:show, 123).should be_true
end
it "should automatically alias new and edit into create and update respectively" do
@ability.can :create, :all
@ability.can :update, :all
@ability.can?(:new, 123).should be_true
@ability.can?(:edit, 123).should be_true
end
it "should not respond to prepare (now using initialize)" do
@ability.should_not respond_to(:prepare)
end
it "should offer cannot? method which is simply invert of can?" do
@ability.cannot?(:tie, String).should be_true
end
it "should be able to specify multiple actions and match any" do
@ability.can [:read, :update], :all
@ability.can?(:read, 123).should be_true
@ability.can?(:update, 123).should be_true
@ability.can?(:count, 123).should be_false
end
it "should be able to specify multiple classes and match any" do
@ability.can :update, [String, Range]
@ability.can?(:update, "foo").should be_true
@ability.can?(:update, 1..3).should be_true
@ability.can?(:update, 123).should be_false
end
it "should support custom objects in the rule" do
@ability.can :read, :stats
@ability.can?(:read, :stats).should be_true
@ability.can?(:update, :stats).should be_false
@ability.can?(:read, :nonstats).should be_false
end
it "should check ancestors of class" do
@ability.can :read, Numeric
@ability.can?(:read, Integer).should be_true
@ability.can?(:read, 1.23).should be_true
@ability.can?(:read, "foo").should be_false
end
it "should support 'cannot' method to define what user cannot do" do
@ability.can :read, :all
@ability.cannot :read, Integer
@ability.can?(:read, "foo").should be_true
@ability.can?(:read, 123).should be_false
end
it "should pass to previous rule, if block returns false or nil" do
@ability.can :read, :all
@ability.cannot :read, Integer do |int|
int > 10 ? nil : ( int > 5 )
end
@ability.can?(:read, "foo").should be_true
@ability.can?(:read, 3).should be_true
@ability.can?(:read, 8).should be_false
@ability.can?(:read, 123).should be_true
end
it "should always return `false` for single cannot definition" do
@ability.cannot :read, Integer do |int|
int > 10 ? nil : ( int > 5 )
end
@ability.can?(:read, "foo").should be_false
@ability.can?(:read, 3).should be_false
@ability.can?(:read, 8).should be_false
@ability.can?(:read, 123).should be_false
end
it "should pass to previous cannot definition, if block returns false or nil" do
@ability.cannot :read, :all
@ability.can :read, Integer do |int|
int > 10 ? nil : ( int > 5 )
end
@ability.can?(:read, "foo").should be_false
@ability.can?(:read, 3).should be_false
@ability.can?(:read, 10).should be_true
@ability.can?(:read, 123).should be_false
end
it "should append aliased actions" do
@ability.alias_action :update, :to => :modify
@ability.alias_action :destroy, :to => :modify
@ability.aliased_actions[:modify].should == [:update, :destroy]
end
it "should clear aliased actions" do
@ability.alias_action :update, :to => :modify
@ability.clear_aliased_actions
@ability.aliased_actions[:modify].should be_nil
end
it "should pass additional arguments to block from can?" do
@ability.can :read, Integer do |int, x|
int > x
end
@ability.can?(:read, 2, 1).should be_true
@ability.can?(:read, 2, 3).should be_false
end
it "should use conditions as third parameter and determine abilities from it" do
@ability.can :read, Range, :begin => 1, :end => 3
@ability.can?(:read, 1..3).should be_true
@ability.can?(:read, 1..4).should be_false
@ability.can?(:read, Range).should be_true
end
it "should allow an array of options in conditions hash" do
@ability.can :read, Range, :begin => [1, 3, 5]
@ability.can?(:read, 1..3).should be_true
@ability.can?(:read, 2..4).should be_false
@ability.can?(:read, 3..5).should be_true
end
it "should allow a range of options in conditions hash" do
@ability.can :read, Range, :begin => 1..3
@ability.can?(:read, 1..10).should be_true
@ability.can?(:read, 3..30).should be_true
@ability.can?(:read, 4..40).should be_false
end
it "should allow nested hashes in conditions hash" do
@ability.can :read, Range, :begin => { :to_i => 5 }
@ability.can?(:read, 5..7).should be_true
@ability.can?(:read, 6..8).should be_false
end
it "should match any element passed in to nesting if it's an array (for has_many associations)" do
@ability.can :read, Range, :to_a => { :to_i => 3 }
@ability.can?(:read, 1..5).should be_true
@ability.can?(:read, 4..6).should be_false
end
it "should accept a set as a condition value" do
mock(object_with_foo_2 = Object.new).foo { 2 }
mock(object_with_foo_3 = Object.new).foo { 3 }
@ability.can :read, Object, :foo => [1, 2, 5].to_set
@ability.can?(:read, object_with_foo_2).should be_true
@ability.can?(:read, object_with_foo_3).should be_false
end
it "should not match subjects return nil for methods that must match nested a nested conditions hash" do
mock(object_with_foo = Object.new).foo { :bar }
@ability.can :read, Array, :first => { :foo => :bar }
@ability.can?(:read, [object_with_foo]).should be_true
@ability.can?(:read, []).should be_false
end
it "should not stop at cannot definition when comparing class" do
@ability.can :read, Range
@ability.cannot :read, Range, :begin => 1
@ability.can?(:read, 2..5).should be_true
@ability.can?(:read, 1..5).should be_false
@ability.can?(:read, Range).should be_true
end
it "should stop at cannot definition when no hash is present" do
@ability.can :read, :all
@ability.cannot :read, Range
@ability.can?(:read, 1..5).should be_false
@ability.can?(:read, Range).should be_false
end
it "should allow to check ability for Module" do
module B; end
class A; include B; end
@ability.can :read, B
@ability.can?(:read, A).should be_true
@ability.can?(:read, A.new).should be_true
end
it "should pass nil to a block for ability on Module when no instance is passed" do
module B; end
class A; include B; end
@ability.can :read, B do |sym|
sym.should be_nil
true
end
@ability.can?(:read, B).should be_true
@ability.can?(:read, A).should be_true
end
it "passing a hash of subjects should check permissions through association" do
@ability.can :read, Range, :string => {:length => 3}
@ability.can?(:read, "foo" => Range).should be_true
@ability.can?(:read, "foobar" => Range).should be_false
@ability.can?(:read, 123 => Range).should be_true
end
it "passing a hash of subjects with multiple definitions should check permissions correctly" do
@ability.can :read, Range, :string => {:length => 4}
@ability.can [:create, :read], Range, :string => {:upcase => 'FOO'}
@ability.can?(:read, "foo" => Range).should be_true
@ability.can?(:read, "foobar" => Range).should be_false
@ability.can?(:read, 1234 => Range).should be_true
end
it "should allow to check ability on Hash-like object" do
class Container < Hash; end
@ability.can :read, Container
@ability.can?(:read, Container.new).should be_true
end
it "should have initial attributes based on hash conditions of 'new' action" do
@ability.can :manage, Range, :foo => "foo", :hash => {:skip => "hashes"}
@ability.can :create, Range, :bar => 123, :array => %w[skip arrays]
@ability.can :new, Range, :baz => "baz", :range => 1..3
@ability.cannot :new, Range, :ignore => "me"
@ability.attributes_for(:new, Range).should == {:foo => "foo", :bar => 123, :baz => "baz"}
end
it "should raise access denied exception if ability us unauthorized to perform a certain action" do
begin
@ability.authorize! :read, :foo, 1, 2, 3, :message => "Access denied!"
rescue CanCan::AccessDenied => e
e.message.should == "Access denied!"
e.action.should == :read
e.subject.should == :foo
else
fail "Expected CanCan::AccessDenied exception to be raised"
end
end
it "should not raise access denied exception if ability is authorized to perform an action and return subject" do
@ability.can :read, :foo
lambda {
@ability.authorize!(:read, :foo).should == :foo
}.should_not raise_error
end
it "should know when block is used in conditions" do
@ability.can :read, :foo
@ability.should_not have_block(:read, :foo)
@ability.can :read, :foo do |foo|
false
end
@ability.should have_block(:read, :foo)
end
it "should know when raw sql is used in conditions" do
@ability.can :read, :foo
@ability.should_not have_raw_sql(:read, :foo)
@ability.can :read, :foo, 'false'
@ability.should have_raw_sql(:read, :foo)
end
it "should raise access denied exception with default message if not specified" do
begin
@ability.authorize! :read, :foo
rescue CanCan::AccessDenied => e
e.default_message = "Access denied!"
e.message.should == "Access denied!"
else
fail "Expected CanCan::AccessDenied exception to be raised"
end
end
it "should determine model adapter class by asking AbstractAdapter" do
model_class = Object.new
adapter_class = Object.new
stub(CanCan::ModelAdapters::AbstractAdapter).adapter_class(model_class) { adapter_class }
stub(adapter_class).new(model_class, []) { :adapter_instance }
@ability.model_adapter(model_class, :read).should == :adapter_instance
end
it "should raise an error when attempting to use a block with a hash condition since it's not likely what they want" do
lambda {
@ability.can :read, Array, :published => true do
false
end
}.should raise_error(CanCan::Error, "You are not able to supply a block with a hash of conditions in read Array ability. Use either one.")
end
describe "unauthorized message" do
after(:each) do
I18n.backend = nil
end
it "should use action/subject in i18n" do
I18n.backend.store_translations :en, :unauthorized => {:update => {:array => "foo"}}
@ability.unauthorized_message(:update, Array).should == "foo"
@ability.unauthorized_message(:update, [1, 2, 3]).should == "foo"
@ability.unauthorized_message(:update, :missing).should be_nil
end
it "should use symbol as subject directly" do
I18n.backend.store_translations :en, :unauthorized => {:has => {:cheezburger => "Nom nom nom. I eated it."}}
@ability.unauthorized_message(:has, :cheezburger).should == "Nom nom nom. I eated it."
end
it "should fall back to 'manage' and 'all'" do
I18n.backend.store_translations :en, :unauthorized => {
:manage => {:all => "manage all", :array => "manage array"},
:update => {:all => "update all", :array => "update array"}
}
@ability.unauthorized_message(:update, Array).should == "update array"
@ability.unauthorized_message(:update, Hash).should == "update all"
@ability.unauthorized_message(:foo, Array).should == "manage array"
@ability.unauthorized_message(:foo, Hash).should == "manage all"
end
it "should follow aliased actions" do
I18n.backend.store_translations :en, :unauthorized => {:modify => {:array => "modify array"}}
@ability.alias_action :update, :to => :modify
@ability.unauthorized_message(:update, Array).should == "modify array"
@ability.unauthorized_message(:edit, Array).should == "modify array"
end
it "should have variables for action and subject" do
I18n.backend.store_translations :en, :unauthorized => {:manage => {:all => "%{action} %{subject}"}} # old syntax for now in case testing with old I18n
@ability.unauthorized_message(:update, Array).should == "update array"
@ability.unauthorized_message(:update, ArgumentError).should == "update argument error"
@ability.unauthorized_message(:edit, 1..3).should == "edit range"
end
end
describe "#merge" do
it "should add the rules from the given ability" do
@ability.can :use, :tools
another_ability = Object.new
another_ability.extend(CanCan::Ability)
another_ability.can :use, :search
@ability.merge(another_ability)
@ability.can?(:use, :search).should be_true
@ability.send(:rules).size.should == 2
end
end
end
| {
"content_hash": "215f691beac04bce30be1bdc38d0dfa0",
"timestamp": "",
"source": "github",
"line_count": 452,
"max_line_length": 164,
"avg_line_length": 35.75,
"alnum_prop": 0.6530107061080512,
"repo_name": "StartupWeekend/cancan",
"id": "0cc84e5dc6690391f9b38776bb304ced4405c306",
"size": "16159",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/cancan/ability_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "144697"
}
],
"symlink_target": ""
} |
<!-- dx-header -->
# Bismark-ENCODE-WGBS (DNAnexus Platform Workflow)
Pipeline for ENCODE WGBS analysis using Bismark
This is the source code for an app that runs on the DNAnexus Platform.
For more information about how to run or modify it, see
https://wiki.dnanexus.com/.
<!-- /dx-header -->
<!--
TODO: This app directory was automatically generated by dx-app-wizard;
please edit this Readme.md file to include essential documentation about
your app that would be helpful to users. (Also see the
Readme.developer.md.) Once you're done, you can remove these TODO
comments.
For more info, see https://wiki.dnanexus.com/Developer-Portal.
-->
| {
"content_hash": "32b969bc0c0061de898ccfc7d9039322",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 72,
"avg_line_length": 30.761904761904763,
"alnum_prop": 0.7554179566563467,
"repo_name": "ENCODE-DCC/dna-me-pipeline",
"id": "4c4b7f104d6e37b18b0f212bffbf20dc70b4eabc",
"size": "646",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dnanexus/Readme.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AngelScript",
"bytes": "2964"
},
{
"name": "Perl",
"bytes": "5671065"
},
{
"name": "Python",
"bytes": "323535"
},
{
"name": "Shell",
"bytes": "168884"
},
{
"name": "Smarty",
"bytes": "1781004"
}
],
"symlink_target": ""
} |
package controllers;
import java.io.IOException;
import java.io.InputStream;
import ninja.Context;
import ninja.Renderable;
import ninja.Result;
import ninja.Results;
import ninja.exceptions.InternalServerErrorException;
import ninja.i18n.Lang;
import ninja.utils.MimeTypes;
import ninja.utils.ResponseStreams;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.util.Streams;
import org.slf4j.Logger;
import com.google.common.io.ByteStreams;
import com.google.inject.Inject;
import com.google.inject.Singleton;
@Singleton
public class UploadController {
/**
* This is the system wide logger. You can still use any config you like. Or
* create your own custom logger.
*
* But often this is just a simple solution:
*/
@Inject
public Logger logger;
@Inject
Lang lang;
private final MimeTypes mimeTypes;
@Inject
public UploadController(MimeTypes mimeTypes) {
this.mimeTypes = mimeTypes;
}
public Result upload() {
// simply renders the default view for this controller
return Results.html();
}
/**
*
* This upload method expects a file and simply displays the file in the
* multipart upload again to the user (in the correct mime encoding).
*
* @param context
* @return
* @throws Exception
*/
public Result uploadFinish(Context context) throws Exception {
// we are using a renderable inner class to stream the input again to
// the user
Renderable renderable = new Renderable() {
@Override
public void render(Context context, Result result) {
try {
// make sure the context really is a multipart context...
if (context.isMultipart()) {
// This is the iterator we can use to iterate over the
// contents
// of the request.
FileItemIterator fileItemIterator = context
.getFileItemIterator();
while (fileItemIterator.hasNext()) {
FileItemStream item = fileItemIterator.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
String contentType = item.getContentType();
if (contentType != null) {
result.contentType(contentType);
} else {
contentType = mimeTypes.getMimeType(name);
}
ResponseStreams responseStreams = context
.finalizeHeaders(result);
if (item.isFormField()) {
System.out.println("Form field " + name
+ " with value " + Streams.asString(stream)
+ " detected.");
} else {
System.out.println("File field " + name
+ " with file name " + item.getName()
+ " detected.");
// Process the input stream
ByteStreams.copy(stream,
responseStreams.getOutputStream());
}
}
}
} catch (IOException | FileUploadException exception) {
throw new InternalServerErrorException(exception);
}
}
};
return new Result(200).render(renderable);
}
}
| {
"content_hash": "018d1ff7aed46351920c93cdd6fd62c4",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 80,
"avg_line_length": 29.99236641221374,
"alnum_prop": 0.5332145584118096,
"repo_name": "tom1120/ninja",
"id": "8e6a5b41f3ca69d64dc92bfb86e4612c6bb1c096",
"size": "4553",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ninja-servlet-integration-test/src/main/java/controllers/UploadController.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1769079"
},
{
"name": "FreeMarker",
"bytes": "193300"
},
{
"name": "HTML",
"bytes": "640943"
},
{
"name": "Java",
"bytes": "3137200"
},
{
"name": "JavaScript",
"bytes": "3201287"
},
{
"name": "Roff",
"bytes": "17565"
}
],
"symlink_target": ""
} |
package org.apache.flink.table.typeutils
import org.apache.flink.api.common.ExecutionConfig
import org.apache.flink.api.common.typeinfo.TypeInformation
import org.apache.flink.api.common.typeutils.TypeSerializer
import org.apache.flink.api.common.typeutils.base.MapSerializer
import org.apache.flink.table.api.dataview.MapView
/**
* [[MapView]] type information.
*
* @param keyType key type information
* @param valueType value type information
* @tparam K key type
* @tparam V value type
*/
class MapViewTypeInfo[K, V](
val keyType: TypeInformation[K],
val valueType: TypeInformation[V],
var nullSerializer: Boolean = false,
val nullAware: Boolean = false)
extends TypeInformation[MapView[K, V]] {
override def isBasicType = false
override def isTupleType = false
override def getArity = 1
override def getTotalFields = 1
override def getTypeClass: Class[MapView[K, V]] = classOf[MapView[K, V]]
override def isKeyType: Boolean = false
override def createSerializer(config: ExecutionConfig): TypeSerializer[MapView[K, V]] = {
if (nullSerializer) {
new NullSerializer().asInstanceOf[TypeSerializer[MapView[K, V]]]
} else {
val keySer = keyType.createSerializer(config)
val valueSer = valueType.createSerializer(config)
if (nullAware) {
new MapViewSerializer[K, V](new NullAwareMapSerializer[K, V](keySer, valueSer))
} else {
new MapViewSerializer[K, V](new MapSerializer[K, V](keySer, valueSer))
}
}
}
override def canEqual(obj: scala.Any): Boolean = obj != null && obj.getClass == getClass
override def hashCode(): Int = {
31 * 31 * 31 * keyType.hashCode + 31* 31 * valueType.hashCode +
31 * nullSerializer.hashCode + nullAware.hashCode()
}
override def equals(obj: Any): Boolean = canEqual(obj) && {
obj match {
case other: MapViewTypeInfo[_, _] =>
keyType.equals(other.keyType) &&
valueType.equals(other.valueType) &&
nullSerializer == other.nullSerializer &&
nullAware == other.nullAware
case _ => false
}
}
override def toString: String = s"MapView<$keyType, $valueType>"
}
| {
"content_hash": "4973e9c24915f830281001cb38529516",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 91,
"avg_line_length": 30.774647887323944,
"alnum_prop": 0.6892448512585813,
"repo_name": "ueshin/apache-flink",
"id": "421312ab3c52cbfcb13016588ae46bbf972db30b",
"size": "2990",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/typeutils/MapViewTypeInfo.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5667"
},
{
"name": "CSS",
"bytes": "18100"
},
{
"name": "Clojure",
"bytes": "88796"
},
{
"name": "CoffeeScript",
"bytes": "91220"
},
{
"name": "Dockerfile",
"bytes": "9788"
},
{
"name": "HTML",
"bytes": "86821"
},
{
"name": "Java",
"bytes": "42052018"
},
{
"name": "JavaScript",
"bytes": "8267"
},
{
"name": "Python",
"bytes": "249644"
},
{
"name": "Scala",
"bytes": "8365242"
},
{
"name": "Shell",
"bytes": "398033"
}
],
"symlink_target": ""
} |
package root
import (
"fmt"
controlplane "github.com/kubernetes-incubator/kube-aws/core/controlplane/cluster"
config "github.com/kubernetes-incubator/kube-aws/core/controlplane/config"
nodepool "github.com/kubernetes-incubator/kube-aws/core/nodepool/cluster"
)
// TemplateParams is the set of parameters exposed for templating cfn stack template for the root stack
type TemplateParams struct {
cluster clusterImpl
}
func (p TemplateParams) ExtraCfnResources() map[string]interface{} {
return p.cluster.ExtraCfnResources
}
func (p TemplateParams) ClusterName() string {
return p.cluster.controlPlane.ClusterName
}
func (p TemplateParams) KubeAwsVersion() string {
return controlplane.VERSION
}
func (p TemplateParams) CloudWatchLogging() config.CloudWatchLogging {
return p.cluster.controlPlane.CloudWatchLogging
}
func (p TemplateParams) KubeDnsMasq() config.KubeDns {
return p.cluster.controlPlane.KubeDns
}
func newTemplateParams(c clusterImpl) TemplateParams {
return TemplateParams{
cluster: c,
}
}
type NestedStack interface {
Name() string
Tags() map[string]string
TemplateURL() (string, error)
NeedToExportIAMroles() bool
}
type controlPlane struct {
controlPlane *controlplane.Cluster
}
func (p controlPlane) Name() string {
return p.controlPlane.NestedStackName()
}
func (p controlPlane) Tags() map[string]string {
return p.controlPlane.StackTags
}
func (p controlPlane) NeedToExportIAMroles() bool {
return p.controlPlane.Controller.IAMConfig.InstanceProfile.Arn == ""
}
func (p controlPlane) TemplateURL() (string, error) {
u, err := p.controlPlane.TemplateURL()
if u == "" || err != nil {
return "", fmt.Errorf("failed to get TemplateURL for %+v: %v", p.controlPlane.String(), err)
}
return u, nil
}
func (p controlPlane) CloudWatchLogging() config.CloudWatchLogging {
return p.controlPlane.CloudWatchLogging
}
func (p controlPlane) KubeDns() config.KubeDns {
return p.controlPlane.KubeDns
}
type nodePool struct {
nodePool *nodepool.Cluster
}
func (p nodePool) Name() string {
return p.nodePool.NestedStackName()
}
func (p nodePool) Tags() map[string]string {
return p.nodePool.StackTags
}
func (p nodePool) TemplateURL() (string, error) {
u, err := p.nodePool.TemplateURL()
if err != nil || u == "" {
return "", fmt.Errorf("failed to get template url: %v", err)
}
return u, nil
}
func (p nodePool) CloudWatchLogging() config.CloudWatchLogging {
return p.nodePool.CloudWatchLogging
}
func (p nodePool) KubeDns() config.KubeDns {
return p.nodePool.KubeDns
}
func (p nodePool) NeedToExportIAMroles() bool {
return p.nodePool.IAMConfig.InstanceProfile.Arn == ""
}
func (c TemplateParams) ControlPlane() controlPlane {
return controlPlane{
controlPlane: c.cluster.controlPlane,
}
}
func (c TemplateParams) NodePools() []NestedStack {
nps := []NestedStack{}
for _, np := range c.cluster.nodePools {
nps = append(nps, nodePool{
nodePool: np,
})
}
return nps
}
| {
"content_hash": "9187603619c540df17fdbcbbc6a12df0",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 103,
"avg_line_length": 22.549618320610687,
"alnum_prop": 0.7437373053486798,
"repo_name": "camilb/kube-aws",
"id": "492053887dc1bd591e27f4e0708b2c3286a00484",
"size": "2954",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "core/root/template_params.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "598127"
},
{
"name": "Makefile",
"bytes": "4587"
},
{
"name": "Shell",
"bytes": "76171"
}
],
"symlink_target": ""
} |
/* $Xorg: lcConv.c,v 1.4 2000/08/17 19:45:17 cpqbld Exp $ */
/*
* Copyright 1992, 1993 by TOSHIBA Corp.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted, provided
* that the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of TOSHIBA not be used in advertising
* or publicity pertaining to distribution of the software without specific,
* written prior permission. TOSHIBA make no representations about the
* suitability of this software for any purpose. It is provided "as is"
* without express or implied warranty.
*
* TOSHIBA DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
* TOSHIBA BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
* ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
*
* Author: Katsuhisa Yano TOSHIBA Corp.
* mopi@osa.ilab.toshiba.co.jp
*/
/* $XFree86: xc/lib/X11/lcConv.c,v 1.5 2000/12/04 18:49:26 dawes Exp $ */
#include "Xlibint.h"
#include "XlcPubI.h"
#include <stdio.h>
typedef struct _XlcConverterListRec {
XLCd from_lcd;
const char *from;
XrmQuark from_type;
XLCd to_lcd;
const char *to;
XrmQuark to_type;
XlcOpenConverterProc converter;
struct _XlcConverterListRec *next;
} XlcConverterListRec, *XlcConverterList;
static XlcConverterList conv_list = NULL;
static void
close_converter(
XlcConv conv)
{
(*conv->methods->close)(conv);
}
static XlcConv
get_converter(
XLCd from_lcd,
XrmQuark from_type,
XLCd to_lcd,
XrmQuark to_type)
{
XlcConverterList list, prev = NULL;
for (list = conv_list; list; list = list->next) {
if (list->from_lcd == from_lcd && list->to_lcd == to_lcd
&& list->from_type == from_type && list->to_type == to_type) {
if (prev && prev != conv_list) { /* XXX */
prev->next = list->next;
list->next = conv_list;
conv_list = list;
}
return (*list->converter)(from_lcd, list->from, to_lcd, list->to);
}
prev = list;
}
return (XlcConv) NULL;
}
Bool
_XlcSetConverter(
XLCd from_lcd,
const char *from,
XLCd to_lcd,
const char *to,
XlcOpenConverterProc converter)
{
XlcConverterList list;
XrmQuark from_type, to_type;
from_type = XrmStringToQuark(from);
to_type = XrmStringToQuark(to);
for (list = conv_list; list; list = list->next) {
if (list->from_lcd == from_lcd && list->to_lcd == to_lcd
&& list->from_type == from_type && list->to_type == to_type) {
list->converter = converter;
return True;
}
}
list = (XlcConverterList) Xmalloc(sizeof(XlcConverterListRec));
if (list == NULL)
return False;
list->from_lcd = from_lcd;
list->from = from;
list->from_type = from_type;
list->to_lcd = to_lcd;
list->to = to;
list->to_type = to_type;
list->converter = converter;
list->next = conv_list;
conv_list = list;
return True;
}
typedef struct _ConvRec {
XlcConv from_conv;
XlcConv to_conv;
} ConvRec, *Conv;
static int
indirect_convert(
XlcConv lc_conv,
XPointer *from,
int *from_left,
XPointer *to,
int *to_left,
XPointer *args,
int num_args)
{
Conv conv = (Conv) lc_conv->state;
XlcConv from_conv = conv->from_conv;
XlcConv to_conv = conv->to_conv;
XlcCharSet charset;
char buf[BUFSIZ], *cs;
XPointer tmp_args[1];
int cs_left, ret, length, unconv_num = 0;
if (from == NULL || *from == NULL) {
if (from_conv->methods->reset)
(*from_conv->methods->reset)(from_conv);
if (to_conv->methods->reset)
(*to_conv->methods->reset)(to_conv);
return 0;
}
while (*from_left > 0) {
cs = buf;
cs_left = BUFSIZ;
tmp_args[0] = (XPointer) &charset;
ret = (*from_conv->methods->convert)(from_conv, from, from_left, &cs,
&cs_left, tmp_args, 1);
if (ret < 0)
break;
unconv_num += ret;
length = cs - buf;
if (length > 0) {
cs_left = length;
cs = buf;
tmp_args[0] = (XPointer) charset;
ret = (*to_conv->methods->convert)(to_conv, &cs, &cs_left, to, to_left,
tmp_args, 1);
if (ret < 0) {
unconv_num += length / (charset->char_size > 0 ? charset->char_size : 1);
continue;
}
unconv_num += ret;
if (*to_left < 1)
break;
}
}
return unconv_num;
}
static void
close_indirect_converter(
XlcConv lc_conv)
{
Conv conv = (Conv) lc_conv->state;
if (conv) {
if (conv->from_conv)
close_converter(conv->from_conv);
if (conv->to_conv)
close_converter(conv->to_conv);
Xfree((char *) conv);
}
Xfree((char *) lc_conv);
}
static void
reset_indirect_converter(
XlcConv lc_conv)
{
Conv conv = (Conv) lc_conv->state;
if (conv) {
if (conv->from_conv && conv->from_conv->methods->reset)
(*conv->from_conv->methods->reset)(conv->from_conv);
if (conv->to_conv && conv->to_conv->methods->reset)
(*conv->to_conv->methods->reset)(conv->to_conv);
}
}
static XlcConvMethodsRec conv_methods = {
close_indirect_converter,
indirect_convert,
reset_indirect_converter
} ;
static XlcConv
open_indirect_converter(
XLCd from_lcd,
const char *from,
XLCd to_lcd,
const char *to)
{
XlcConv lc_conv, from_conv, to_conv;
Conv conv;
XrmQuark from_type, to_type;
static XrmQuark QChar, QCharSet, QCTCharSet = (XrmQuark) 0;
if (QCTCharSet == (XrmQuark) 0) {
QCTCharSet = XrmStringToQuark(XlcNCTCharSet);
QCharSet = XrmStringToQuark(XlcNCharSet);
QChar = XrmStringToQuark(XlcNChar);
}
from_type = XrmStringToQuark(from);
to_type = XrmStringToQuark(to);
if (from_type == QCharSet || from_type == QChar || to_type == QCharSet ||
to_type == QChar)
return (XlcConv) NULL;
lc_conv = (XlcConv) Xmalloc(sizeof(XlcConvRec));
if (lc_conv == NULL)
return (XlcConv) NULL;
lc_conv->methods = &conv_methods;
lc_conv->state = (XPointer) Xcalloc(1, sizeof(ConvRec));
if (lc_conv->state == NULL)
goto err;
conv = (Conv) lc_conv->state;
from_conv = get_converter(from_lcd, from_type, from_lcd, QCTCharSet);
if (from_conv == NULL)
from_conv = get_converter(from_lcd, from_type, from_lcd, QCharSet);
if (from_conv == NULL)
from_conv = get_converter((XLCd)NULL, from_type, (XLCd)NULL, QCharSet);
if (from_conv == NULL)
from_conv = get_converter(from_lcd, from_type, from_lcd, QChar);
if (from_conv == NULL)
goto err;
conv->from_conv = from_conv;
to_conv = get_converter(to_lcd, QCTCharSet, to_lcd, to_type);
if (to_conv == NULL)
to_conv = get_converter(to_lcd, QCharSet, to_lcd, to_type);
if (to_conv == NULL)
to_conv = get_converter((XLCd) NULL, QCharSet, (XLCd) NULL, to_type);
if (to_conv == NULL)
goto err;
conv->to_conv = to_conv;
return lc_conv;
err:
close_indirect_converter(lc_conv);
return (XlcConv) NULL;
}
XlcConv
_XlcOpenConverter(
XLCd from_lcd,
const char *from,
XLCd to_lcd,
const char *to)
{
XlcConv conv;
XrmQuark from_type, to_type;
from_type = XrmStringToQuark(from);
to_type = XrmStringToQuark(to);
if ((conv = get_converter(from_lcd, from_type, to_lcd, to_type)))
return conv;
return open_indirect_converter(from_lcd, from, to_lcd, to);
}
void
_XlcCloseConverter(
XlcConv conv)
{
close_converter(conv);
}
int
_XlcConvert(
XlcConv conv,
XPointer *from,
int *from_left,
XPointer *to,
int *to_left,
XPointer *args,
int num_args)
{
return (*conv->methods->convert)(conv, from, from_left, to, to_left, args,
num_args);
}
void
_XlcResetConverter(
XlcConv conv)
{
if (conv->methods->reset)
(*conv->methods->reset)(conv);
}
| {
"content_hash": "3f01e42d3355122e86ae8f2412ad0de8",
"timestamp": "",
"source": "github",
"line_count": 338,
"max_line_length": 78,
"avg_line_length": 23.869822485207102,
"alnum_prop": 0.6388200297471492,
"repo_name": "easion/os_sdk",
"id": "88ae52f400b903f960446ed65f0b4f5d3a5ccea9",
"size": "8068",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xlibs/X11/lcConv.c",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "980392"
},
{
"name": "Awk",
"bytes": "1743"
},
{
"name": "Bison",
"bytes": "113274"
},
{
"name": "C",
"bytes": "60384056"
},
{
"name": "C++",
"bytes": "6888586"
},
{
"name": "CSS",
"bytes": "3092"
},
{
"name": "Component Pascal",
"bytes": "295471"
},
{
"name": "D",
"bytes": "275403"
},
{
"name": "Erlang",
"bytes": "130334"
},
{
"name": "Groovy",
"bytes": "15362"
},
{
"name": "JavaScript",
"bytes": "437486"
},
{
"name": "Logos",
"bytes": "6575"
},
{
"name": "Makefile",
"bytes": "145054"
},
{
"name": "Max",
"bytes": "4350"
},
{
"name": "Nu",
"bytes": "1315315"
},
{
"name": "Objective-C",
"bytes": "209666"
},
{
"name": "PHP",
"bytes": "246706"
},
{
"name": "Perl",
"bytes": "1767429"
},
{
"name": "Prolog",
"bytes": "1387207"
},
{
"name": "Python",
"bytes": "14909"
},
{
"name": "R",
"bytes": "46561"
},
{
"name": "Ruby",
"bytes": "290155"
},
{
"name": "Scala",
"bytes": "184297"
},
{
"name": "Shell",
"bytes": "5748626"
},
{
"name": "TeX",
"bytes": "346362"
},
{
"name": "XC",
"bytes": "6266"
}
],
"symlink_target": ""
} |
title: Apache Mesos - Committers
layout: documentation
---
# Committers
An Apache Mesos committer is a contributor who has been given write access to the Apache Mesos code repository and related Apache infrastructure. In the Mesos project, each committer is also a voting member of the PMC.
## Becoming a committer
Every new committer has to be proposed by a current committer and then voted in by the members of the Mesos PMC. For details about this process and for candidate requirements see the general [Apache guidelines for assessing new candidates for committership](https://community.apache.org/newcommitter.html). Candidates prepare for their nomination as committer by contributing to the Mesos project and its community, by acting according to the [Apache Way](http://theapacheway.com), and by generally following the path [from contributor to committer](https://community.apache.org/contributors/) for Apache projects. Specifically for the Mesos project, you can make use of the [Apache Mesos Committer Candidate Checklist](committer-candidate-checklist.md) for suggestions of what kind of contributions and demonstrated behaviors can be instrumental, and to keep track of your progress.
## Current Committers
We'd like to thank the following committers to the Apache Mesos project who have helped get the project to where it is today. This list might be stale, the canonical list is located on [Apache's website](http://people.apache.org/committers-by-project.html#mesos).
<table class="table table-hover table-condensed">
<thead>
<tr>
<th>Timezone GMT</th>
<th>Full Name</th>
<th>Company/Organization</th>
<th>IRC Handle</th>
<th>Email Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>-8</td>
<td>Ross Allen</td>
<td>Facebook</td>
<td></td>
<td>ssorallen@apache.org</td>
</tr>
<tr>
<td>-5</td>
<td>Kapil Arya</td>
<td>Mesosphere / Northeastern University</td>
<td></td>
<td>kapil@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Adam B</td>
<td>Mesosphere</td>
<td>adam-mesos</td>
<td>me@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Tim Chen</td>
<td>Mesosphere</td>
<td>tnachen</td>
<td>tnachen@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Neil Conway</td>
<td>Mesosphere</td>
<td>neilc</td>
<td>neilc@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Ian Downes</td>
<td>Twitter</td>
<td>idownes</td>
<td>idownes@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Ali Ghodsi</td>
<td>UC Berkeley</td>
<td></td>
<td>alig@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Dominic Hamon</td>
<td>YouTube</td>
<td></td>
<td>dma@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Benjamin Hindman</td>
<td>Mesosphere</td>
<td>_benh_</td>
<td>benh@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Ian Holsman</td>
<td></td>
<td></td>
<td>ianh@apache.org</td>
</tr>
<tr>
<td>+8</td>
<td>Haosdent Huang</td>
<td>Shopee</td>
<td>haosdent</td>
<td>haosdent@apache.org</td>
</tr>
<tr>
<td>+8</td>
<td>Kevin Klues</td>
<td>Mesosphere</td>
<td>klueska</td>
<td>klueska@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Vinod Kone</td>
<td>Mesosphere</td>
<td>vinodkone</td>
<td>vinodkone@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Andy Konwinski</td>
<td>Databricks</td>
<td></td>
<td>andrew@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Dave Lester</td>
<td>Apple</td>
<td>dlester</td>
<td>dlester@apache.org</td>
</tr>
<tr>
<td>+8</td>
<td>Guangya Liu</td>
<td>IBM</td>
<td>gyliu513</td>
<td>gyliu@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Benjamin Mahler</td>
<td>Mesosphere</td>
<td>bmahler</td>
<td>bmahler@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Thomas Marshall</td>
<td>Carnegie Mellon University</td>
<td></td>
<td>tmarshall@apache.org</td>
</tr>
<tr>
<td>+1</td>
<td>Bernd Mathiske</td>
<td>Mesosphere</td>
<td>bernd</td>
<td>bernd@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Brenden Matthews</td>
<td>Mesosphere</td>
<td>brenden_</td>
<td>brenden@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Chris Mattmann</td>
<td>NASA JPL</td>
<td></td>
<td>mattmann@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Anand Mazumdar</td>
<td>Mesosphere</td>
<td>anandm</td>
<td>anand@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Brian McCallister</td>
<td>Groupon</td>
<td></td>
<td>brianm@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Niklas Quarfot Nielsen</td>
<td>Intel</td>
<td>niq_</td>
<td>nnielsen@apache.org</td>
</tr>
<tr>
<td>-5</td>
<td>Michael Park</td>
<td>Mesosphere</td>
<td>mpark</td>
<td>mpark@apache.org</td>
</tr>
<tr>
<td>+1</td>
<td>Alex R</td>
<td>Mesosphere</td>
<td>alexr</td>
<td>alexr@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Charles Reiss</td>
<td>UC Berkeley</td>
<td></td>
<td>woggle@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Joris Van Remoortere</td>
<td>Mesosphere</td>
<td>joris</td>
<td>joris@apache.org</td>
</tr>
<tr>
<td>-5</td>
<td>Timothy St Clair</td>
<td>Redhat</td>
<td>tstclair</td>
<td>tstclair@apache.org</td>
</tr>
<tr>
<td>+1</td>
<td>Till Toenshoff</td>
<td>Mesosphere</td>
<td>tillt</td>
<td>tillt@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Thomas White</td>
<td>Cloudera</td>
<td></td>
<td>tomwhite@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Joseph Wu</td>
<td>Mesosphere</td>
<td></td>
<td>josephwu@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Yan Xu</td>
<td>Apple</td>
<td>xujyan</td>
<td>yan@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Jie Yu</td>
<td>Mesosphere</td>
<td>jieyu</td>
<td>jieyu@apache.org</td>
</tr>
<tr>
<td>-8</td>
<td>Matei Alexandru Zaharia</td>
<td>Databricks</td>
<td></td>
<td>matei@apache.org</td>
</tr>
<tr>
<td>+8</td>
<td>Qian Zhang</td>
<td>IBM</td>
<td></td>
<td>qianzhang@apache.org</td>
</tr>
</tbody>
</table>
If you're interested in becoming a committer yourself, the best way to do so is by participating in developer discussions and contributing patches to the project.
# Maintainers
**Maintainers are committers that have spent a significant amount of time and effort
in the maintenance of a component in the project.** Since maintainers have generally
lived through the experience of maintaining a part of the project, they tend to have
additional context, a sense of direction, a long-term outlook, and an increased
incentive to ensure that development is done in a sustainable manner. Maintainers are
responsible for the following:
* Providing timely feedback on bug reports and review requests.
* Ensuring the code is straightforward, easy to read / understand.
* Keeping technical debt within reasonable levels.
* Ensuring the code is generally covered by tests.
* Ensuring the code follows the style guidelines.
* Ensuring that any unintuitive or difficult pieces of code are explained with
comments.
* Ensuring that any hacks, known limitations, or future considerations are
accompanied with TODOs as appropriate.
We’re here to build great software together! Maintainers are a means to ensure that
we can continue to build great software while scaling the amount of contributors and
committers in the project. The responsibilities listed above are expected from all
committers in the project in the work that they do, no matter which component they
touch. Maintainers additionally carry the above responsibilities for all changes
going into a particular component, no matter who is doing the work.
**All committers of the Mesos project are expected to use good judgement when
committing patches as to whether the maintainers should be consulted.**
Examples of changes that would benefit from maintainer consultation:
* Changing or adding functionality.
* Fixing a non-trivial bug.
* Non-trivial refactoring.
* Non-trivial performance improvements.
* Substantial additions or updates to documentation.
Examples of changes that do not generally require maintainer consultation:
* Fixing typos.
* Trivial bug fixes.
* Trivial cleanups, e.g. cleaning up headers.
We aim to have more than one maintainer for each component, in order to ensure that
contributors can obtain timely feedback. To avoid information silos, we encourage
committers to learn about areas of the code that they are unfamiliar with.
## Current Maintainers
<table class="table table-hover table-condensed">
<thead>
<tr>
<th>Component</th>
<th>Maintainers (alphabetical)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Master / Agent</td>
<td>Benjamin Hindman, Vinod Kone, Benjamin Mahler, Jie Yu</td>
</tr>
<tr>
<td>Framework API</td>
<td>Benjamin Hindman, Vinod Kone, Benjamin Mahler, Jie Yu</td>
</tr>
<tr>
<td>State Libraries</td>
<td>Benjamin Hindman, Benjamin Mahler</td>
</tr>
<tr>
<td>Replicated Log</td>
<td>Benjamin Hindman, Jie Yu</td>
</tr>
<tr>
<td>ZooKeeper Bindings</td>
<td>Benjamin Hindman, Vinod Kone, Benjamin Mahler, Yan Xu</td>
</tr>
<tr>
<td>Authentication / Authorization</td>
<td>Adam B, Vinod Kone, Till Toenshoff</td>
</tr>
<tr>
<td>Modules / Hooks</td>
<td>Kapil Arya, Benjamin Hindman, Niklas Nielsen</td>
</tr>
<tr>
<td>Oversubscription</td>
<td>Vinod Kone, Niklas Nielsen, Jie Yu</td>
</tr>
<tr>
<td>CLI</td>
<td><i>maintainers needed</i></td>
</tr>
<tr>
<td>WebUI</td>
<td>Haosdent Huang</td>
</tr>
<tr>
<td>Project Website</td>
<td>Dave Lester</td>
</tr>
</tbody>
</table>
#### Containerization
<table class="table table-hover table-condensed">
<thead>
<tr>
<th>Component</th>
<th>Maintainers (alphabetical)</th>
</tr>
<tbody>
<tr>
<td>Mesos Containerizer</td>
<td>Ian Downes, Jie Yu</td>
</tr>
<tr>
<td>Docker Containerizer</td>
<td>Tim Chen, Benjamin Hindman</td>
</tr>
</tbody>
</thead>
</table>
#### C++ Libraries
<table class="table table-hover table-condensed">
<thead>
<tr>
<th>Component</th>
<th>Maintainers (alphabetical)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Libprocess</td>
<td>Benjamin Hindman, Benjamin Mahler, Jie Yu</td>
</tr>
<tr>
<td>Stout</td>
<td>Benjamin Hindman, Vinod Kone, Benjamin Mahler, Jie Yu</td>
</tr>
</tbody>
</table>
| {
"content_hash": "d828dc942f8f82228523615fe485a97e",
"timestamp": "",
"source": "github",
"line_count": 431,
"max_line_length": 883,
"avg_line_length": 26.691415313225058,
"alnum_prop": 0.5910118219749653,
"repo_name": "yuquanshan/customizedMesos",
"id": "1968c61b2f3bb1579b953f3fbf6c595861eb921d",
"size": "11510",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/committers.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "94"
},
{
"name": "Batchfile",
"bytes": "8237"
},
{
"name": "C++",
"bytes": "9926255"
},
{
"name": "CMake",
"bytes": "102381"
},
{
"name": "CSS",
"bytes": "6696"
},
{
"name": "HTML",
"bytes": "82569"
},
{
"name": "Java",
"bytes": "141425"
},
{
"name": "JavaScript",
"bytes": "1010067"
},
{
"name": "M4",
"bytes": "167524"
},
{
"name": "Makefile",
"bytes": "101307"
},
{
"name": "Protocol Buffer",
"bytes": "407521"
},
{
"name": "Python",
"bytes": "190741"
},
{
"name": "Ruby",
"bytes": "8859"
},
{
"name": "Shell",
"bytes": "111926"
}
],
"symlink_target": ""
} |
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>ScalaTest 3.0.7 - org.scalatest.Entry</title>
<meta name="description" content="ScalaTest 3.0.7 - org.scalatest.Entry" />
<meta name="keywords" content="ScalaTest 3.0.7 org.scalatest.Entry" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="../../lib/index.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />
<script type="text/javascript" src="../../lib/jquery.js"></script>
<script type="text/javascript" src="../../lib/jquery.panzoom.min.js"></script>
<script type="text/javascript" src="../../lib/jquery.mousewheel.min.js"></script>
<script type="text/javascript" src="../../lib/index.js"></script>
<script type="text/javascript" src="../../index.js"></script>
<script type="text/javascript" src="../../lib/scheduler.js"></script>
<script type="text/javascript" src="../../lib/template.js"></script>
<script type="text/javascript" src="../../lib/tools.tooltip.js"></script>
<script type="text/javascript">
/* this variable can be used by the JS to determine the path to the root document */
var toRoot = '../../';
</script>
<!-- gtag [javascript] -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-71294502-1"></script>
<script defer>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-71294502-1');
</script>
</head>
<body>
<div id="search">
<span id="doc-title">ScalaTest 3.0.7<span id="doc-version"></span></span>
<span class="close-results"><span class="left"><</span> Back</span>
<div id="textfilter">
<span class="input">
<input autocapitalize="none" placeholder="Search" id="index-input" type="text" accesskey="/" />
<i class="clear material-icons"></i>
<i id="search-icon" class="material-icons"></i>
</span>
</div>
</div>
<div id="search-results">
<div id="search-progress">
<div id="progress-fill"></div>
</div>
<div id="results-content">
<div id="entity-results"></div>
<div id="member-results"></div>
</div>
</div>
<div id="content-scroll-container" style="-webkit-overflow-scrolling: touch;">
<div id="content-container" style="-webkit-overflow-scrolling: touch;">
<div id="subpackage-spacer">
<div id="packages">
<h1>Packages</h1>
<ul>
<li name="_root_.root" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="_root_"></a><a id="root:_root_"></a>
<span class="permalink">
<a href="index.html#_root_" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="../../index.html"><span class="name">root</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../index.html" class="extype" name="_root_">root</a></dd></dl></div>
</li><li name="_root_.org" visbl="pub" class="indented1 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="org"></a><a id="org:org"></a>
<span class="permalink">
<a href="index.html#org" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="../index.html"><span class="name">org</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../index.html" class="extype" name="_root_">root</a></dd></dl></div>
</li><li name="org.scalatest" visbl="pub" class="indented2 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="scalatest"></a><a id="scalatest:scalatest"></a>
<span class="permalink">
<a href="../org/index.html#scalatest" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter." href="index.html"><span class="name">scalatest</span></a>
</span>
<p class="shortcomment cmt">ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.</p><div class="fullcomment"><div class="comment cmt"><p>ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.
</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../index.html" class="extype" name="org">org</a></dd></dl></div>
</li><li name="org.scalatest.compatible" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="compatible"></a><a id="compatible:compatible"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#compatible" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="compatible/index.html"><span class="name">compatible</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.concurrent" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="concurrent"></a><a id="concurrent:concurrent"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#concurrent" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter." href="concurrent/index.html"><span class="name">concurrent</span></a>
</span>
<p class="shortcomment cmt">ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.</p><div class="fullcomment"><div class="comment cmt"><p>ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.
</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.easymock" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="easymock"></a><a id="easymock:easymock"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#easymock" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="easymock/index.html"><span class="name">easymock</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.enablers" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="enablers"></a><a id="enablers:enablers"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#enablers" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="enablers/index.html"><span class="name">enablers</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.events" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="events"></a><a id="events:events"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#events" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="events/index.html"><span class="name">events</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.exceptions" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="exceptions"></a><a id="exceptions:exceptions"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#exceptions" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="exceptions/index.html"><span class="name">exceptions</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.fixture" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="fixture"></a><a id="fixture:fixture"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#fixture" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="fixture/index.html"><span class="name">fixture</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.jmock" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="jmock"></a><a id="jmock:jmock"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#jmock" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="jmock/index.html"><span class="name">jmock</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.junit" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="junit"></a><a id="junit:junit"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#junit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="junit/index.html"><span class="name">junit</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.matchers" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="matchers"></a><a id="matchers:matchers"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#matchers" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="matchers/index.html"><span class="name">matchers</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.mockito" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="mockito"></a><a id="mockito:mockito"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#mockito" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="mockito/index.html"><span class="name">mockito</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.path" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="path"></a><a id="path:path"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#path" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="path/index.html"><span class="name">path</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.prop" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="prop"></a><a id="prop:prop"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#prop" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter." href="prop/index.html"><span class="name">prop</span></a>
</span>
<p class="shortcomment cmt">ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.</p><div class="fullcomment"><div class="comment cmt"><p>ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.
</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.refspec" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="refspec"></a><a id="refspec:refspec"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#refspec" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="refspec/index.html"><span class="name">refspec</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.selenium" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="selenium"></a><a id="selenium:selenium"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#selenium" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="selenium/index.html"><span class="name">selenium</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.tagobjects" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="tagobjects"></a><a id="tagobjects:tagobjects"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#tagobjects" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="tagobjects/index.html"><span class="name">tagobjects</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.tags" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="tags"></a><a id="tags:tags"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#tags" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="tags/index.html"><span class="name">tags</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.testng" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="testng"></a><a id="testng:testng"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#testng" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="testng/index.html"><span class="name">testng</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.time" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="time"></a><a id="time:time"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#time" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="time/index.html"><span class="name">time</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.tools" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="tools"></a><a id="tools:tools"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#tools" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="tools/index.html"><span class="name">tools</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li name="org.scalatest.words" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="words"></a><a id="words:words"></a>
<span class="permalink">
<a href="../../org/scalatest/index.html#words" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="words/index.html"><span class="name">words</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="Alerter.html" title="Trait providing an apply method to which alert messages about a running suite of tests can be reported."></a>
<a href="Alerter.html" title="Trait providing an apply method to which alert messages about a running suite of tests can be reported.">Alerter</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="Alerting.html" title="Trait that contains the alert method, which can be used to send an alert to the reporter."></a>
<a href="Alerting.html" title="Trait that contains the alert method, which can be used to send an alert to the reporter.">Alerting</a>
</li><li class="current-entities indented2">
<a class="object" href="AppendedClues$.html" title="Companion object that facilitates the importing of AppendedClues members as an alternative to mixing it in."></a>
<a class="trait" href="AppendedClues.html" title="Trait providing an implicit conversion that allows clues to be placed after a block of code."></a>
<a href="AppendedClues.html" title="Trait providing an implicit conversion that allows clues to be placed after a block of code.">AppendedClues</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="Args.html" title="Arguments bundle passed to four of ScalaTest's lifecycle methods: run, runNestedSuites, runTests, and runTest."></a>
<a href="Args.html" title="Arguments bundle passed to four of ScalaTest's lifecycle methods: run, runNestedSuites, runTests, and runTest.">Args</a>
</li><li class="current-entities indented2">
<a class="object" href="Assertions$.html" title="Companion object that facilitates the importing of Assertions members as an alternative to mixing it in."></a>
<a class="trait" href="Assertions.html" title="Trait that contains ScalaTest's basic assertion methods."></a>
<a href="Assertions.html" title="Trait that contains ScalaTest's basic assertion methods.">Assertions</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="AsyncFeatureSpec.html" title="Enables testing of asynchronous code without blocking, using a style consistent with traditional FeatureSpec tests."></a>
<a href="AsyncFeatureSpec.html" title="Enables testing of asynchronous code without blocking, using a style consistent with traditional FeatureSpec tests.">AsyncFeatureSpec</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="AsyncFeatureSpecLike.html" title="Implementation trait for class AsyncFeatureSpec, which represents a suite of tests in which each test represents one scenario of a feature."></a>
<a href="AsyncFeatureSpecLike.html" title="Implementation trait for class AsyncFeatureSpec, which represents a suite of tests in which each test represents one scenario of a feature.">AsyncFeatureSpecLike</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="AsyncFlatSpec.html" title="Enables testing of asynchronous code without blocking, using a style consistent with traditional FlatSpec tests."></a>
<a href="AsyncFlatSpec.html" title="Enables testing of asynchronous code without blocking, using a style consistent with traditional FlatSpec tests.">AsyncFlatSpec</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="AsyncFlatSpecLike.html" title="Implementation trait for class AsyncFlatSpec, which facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify."></a>
<a href="AsyncFlatSpecLike.html" title="Implementation trait for class AsyncFlatSpec, which facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify.">AsyncFlatSpecLike</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="AsyncFreeSpec.html" title="Enables testing of asynchronous code without blocking, using a style consistent with traditional FreeSpec tests."></a>
<a href="AsyncFreeSpec.html" title="Enables testing of asynchronous code without blocking, using a style consistent with traditional FreeSpec tests.">AsyncFreeSpec</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="AsyncFreeSpecLike.html" title="Implementation trait for class AsyncFreeSpec, which facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are nested inside text clauses denoted with the dash operator (-)."></a>
<a href="AsyncFreeSpecLike.html" title="Implementation trait for class AsyncFreeSpec, which facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are nested inside text clauses denoted with the dash operator (-).">AsyncFreeSpecLike</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="AsyncFunSpec.html" title="Enables testing of asynchronous code without blocking, using a style consistent with traditional FunSpec tests."></a>
<a href="AsyncFunSpec.html" title="Enables testing of asynchronous code without blocking, using a style consistent with traditional FunSpec tests.">AsyncFunSpec</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="AsyncFunSpecLike.html" title="Implementation trait for class AsyncFunSpec, which facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify."></a>
<a href="AsyncFunSpecLike.html" title="Implementation trait for class AsyncFunSpec, which facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify.">AsyncFunSpecLike</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="AsyncFunSuite.html" title="Enables testing of asynchronous code without blocking, using a style consistent with traditional FunSuite tests."></a>
<a href="AsyncFunSuite.html" title="Enables testing of asynchronous code without blocking, using a style consistent with traditional FunSuite tests.">AsyncFunSuite</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="AsyncFunSuiteLike.html" title="Implementation trait for class AsyncFunSuite, which represents a suite of tests in which each test is represented as a function value."></a>
<a href="AsyncFunSuiteLike.html" title="Implementation trait for class AsyncFunSuite, which represents a suite of tests in which each test is represented as a function value.">AsyncFunSuiteLike</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="AsyncTestRegistration.html" title="Trait declaring methods that can be used to register by-name test functions that have result type Future[Assertion]."></a>
<a href="AsyncTestRegistration.html" title="Trait declaring methods that can be used to register by-name test functions that have result type Future[Assertion].">AsyncTestRegistration</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="AsyncTestSuite.html" title="The base trait of ScalaTest's asynchronous testing styles, which defines a withFixture lifecycle method that accepts as its parameter a test function that returns a FutureOutcome."></a>
<a href="AsyncTestSuite.html" title="The base trait of ScalaTest's asynchronous testing styles, which defines a withFixture lifecycle method that accepts as its parameter a test function that returns a FutureOutcome.">AsyncTestSuite</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="AsyncTestSuiteMixin.html" title="Trait defining abstract "lifecycle" methods that are implemented in AsyncTestSuite and can be overridden in stackable modification traits."></a>
<a href="AsyncTestSuiteMixin.html" title="Trait defining abstract "lifecycle" methods that are implemented in AsyncTestSuite and can be overridden in stackable modification traits.">AsyncTestSuiteMixin</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="AsyncWordSpec.html" title="Enables testing of asynchronous code without blocking, using a style consistent with traditional WordSpec tests."></a>
<a href="AsyncWordSpec.html" title="Enables testing of asynchronous code without blocking, using a style consistent with traditional WordSpec tests.">AsyncWordSpec</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="AsyncWordSpecLike.html" title="Implementation trait for class AsyncWordSpec, which facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify."></a>
<a href="AsyncWordSpecLike.html" title="Implementation trait for class AsyncWordSpec, which facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify.">AsyncWordSpecLike</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="BeforeAndAfter.html" title="Trait that can be mixed into suites that need code executed before and after running each test."></a>
<a href="BeforeAndAfter.html" title="Trait that can be mixed into suites that need code executed before and after running each test.">BeforeAndAfter</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="BeforeAndAfterAll.html" title="Stackable trait that can be mixed into suites that need methods invoked before and after executing the suite."></a>
<a href="BeforeAndAfterAll.html" title="Stackable trait that can be mixed into suites that need methods invoked before and after executing the suite.">BeforeAndAfterAll</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="BeforeAndAfterAllConfigMap.html" title="Trait that can be mixed into suites that need methods that make use of the config map invoked before and/or after executing the suite."></a>
<a href="BeforeAndAfterAllConfigMap.html" title="Trait that can be mixed into suites that need methods that make use of the config map invoked before and/or after executing the suite.">BeforeAndAfterAllConfigMap</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="BeforeAndAfterEach.html" title="Stackable trait that can be mixed into suites that need code executed before and/or after running each test."></a>
<a href="BeforeAndAfterEach.html" title="Stackable trait that can be mixed into suites that need code executed before and/or after running each test.">BeforeAndAfterEach</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="BeforeAndAfterEachTestData.html" title="Stackable trait that can be mixed into suites that need code that makes use of test data (test name, tags, config map, etc.) executed before and/or after running each test."></a>
<a href="BeforeAndAfterEachTestData.html" title="Stackable trait that can be mixed into suites that need code that makes use of test data (test name, tags, config map, etc.) executed before and/or after running each test.">BeforeAndAfterEachTestData</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="CancelAfterFailure.html" title="Trait that when mixed into a TestSuite cancels any remaining tests in that TestSuite instance after a test fails."></a>
<a href="CancelAfterFailure.html" title="Trait that when mixed into a TestSuite cancels any remaining tests in that TestSuite instance after a test fails.">CancelAfterFailure</a>
</li><li class="current-entities indented2">
<a class="object" href="Canceled$.html" title="Companion object to class Canceled that provides, in addition to the extractor and factory method provided by the compiler given its companion is a case class, a second factory method that produces a Canceled outcome given a string message."></a>
<a class="class" href="Canceled.html" title="Outcome for a test that was canceled, containing an exception describing the cause of the cancelation."></a>
<a href="Canceled.html" title="Outcome for a test that was canceled, containing an exception describing the cause of the cancelation.">Canceled</a>
</li><li class="current-entities indented2">
<a class="object" href="Checkpoints$.html" title="Companion object that facilitates the importing the members of trait Checkpoints as an alternative to mixing it in."></a>
<a class="trait" href="Checkpoints.html" title="Trait providing class Checkpoint, which enables multiple assertions to be performed within a test, with any failures accumulated and reported together at the end of the test."></a>
<a href="Checkpoints.html" title="Trait providing class Checkpoint, which enables multiple assertions to be performed within a test, with any failures accumulated and reported together at the end of the test.">Checkpoints</a>
</li><li class="current-entities indented2">
<a class="object" href="CompleteLastly$.html" title="Companion object that facilitates the importing of CompleteLastly members as an alternative to mixing it in."></a>
<a class="trait" href="CompleteLastly.html" title="Trait that provides a complete-lastly construct, which ensures cleanup code in lastly is executed whether the code passed to complete completes abruptly with an exception or successfully results in a Future, FutureOutcome, or other type with an implicit Futuristic instance."></a>
<a href="CompleteLastly.html" title="Trait that provides a complete-lastly construct, which ensures cleanup code in lastly is executed whether the code passed to complete completes abruptly with an exception or successfully results in a Future, FutureOutcome, or other type with an implicit Futuristic instance.">CompleteLastly</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="CompositeStatus.html" title="Composite Status that aggregates its completion and failed states of set of other Statuses passed to its constructor."></a>
<a href="CompositeStatus.html" title="Composite Status that aggregates its completion and failed states of set of other Statuses passed to its constructor.">CompositeStatus</a>
</li><li class="current-entities indented2">
<a class="object" href="ConfigMap$.html" title="Companion object to class ConfigMap containing factory methods."></a>
<a class="class" href="ConfigMap.html" title="A map of configuration data."></a>
<a href="ConfigMap.html" title="A map of configuration data.">ConfigMap</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="ConfigMapWrapperSuite.html" title="Wrapper Suite that passes an instance of the config map to the constructor of the wrapped Suite when run is invoked."></a>
<a href="ConfigMapWrapperSuite.html" title="Wrapper Suite that passes an instance of the config map to the constructor of the wrapped Suite when run is invoked.">ConfigMapWrapperSuite</a>
</li><li class="current-entities indented2">
<a class="object" href="DiagrammedAssertions$.html" title="Companion object that facilitates the importing of DiagrammedAssertions members as an alternative to mixing it in."></a>
<a class="trait" href="DiagrammedAssertions.html" title="Sub-trait of Assertions that override assert and assume methods to include a diagram showing the values of expression in the error message when the assertion or assumption fails."></a>
<a href="DiagrammedAssertions.html" title="Sub-trait of Assertions that override assert and assume methods to include a diagram showing the values of expression in the error message when the assertion or assumption fails.">DiagrammedAssertions</a>
</li><li class="current-entities indented2">
<a class="object" href="DiagrammedExpr$.html" title="DiagrammedExpr companion object that provides factory methods to create different sub types of DiagrammedExpr"></a>
<a class="trait" href="DiagrammedExpr.html" title="A trait that represent an expression recorded by DiagrammedExprMacro, which includes the following members:"></a>
<a href="DiagrammedExpr.html" title="A trait that represent an expression recorded by DiagrammedExprMacro, which includes the following members:">DiagrammedExpr</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="DistributedSuiteSorter.html" title="A sorter for the events of a run's distributed suites."></a>
<a href="DistributedSuiteSorter.html" title="A sorter for the events of a run's distributed suites.">DistributedSuiteSorter</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="DistributedTestSorter.html" title="A sorter for the events of a suite's distributed tests."></a>
<a href="DistributedTestSorter.html" title="A sorter for the events of a suite's distributed tests.">DistributedTestSorter</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="Distributor.html" title="Trait whose instances facilitate parallel execution of Suites."></a>
<a href="Distributor.html" title="Trait whose instances facilitate parallel execution of Suites.">Distributor</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="DoNotDiscover.html" title="Annotation used to indicate that an otherwise discoverable test class should not be discovered."></a>
<a href="DoNotDiscover.html" title="Annotation used to indicate that an otherwise discoverable test class should not be discovered.">DoNotDiscover</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="Documenter.html" title="Trait to which markup text tests can be reported."></a>
<a href="Documenter.html" title="Trait to which markup text tests can be reported.">Documenter</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="Documenting.html" title="Trait that contains a markup method, which can be used to send markup to the Reporter."></a>
<a href="Documenting.html" title="Trait that contains a markup method, which can be used to send markup to the Reporter.">Documenting</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="DynaTags.html" title="Dynamic tags for a run."></a>
<a href="DynaTags.html" title="Dynamic tags for a run.">DynaTags</a>
</li><li class="current-entities indented2">
<a class="object" href="EitherValues$.html" title="Companion object that facilitates the importing of ValueEither members as an alternative to mixing it in."></a>
<a class="trait" href="EitherValues.html" title="Trait that provides an implicit conversion that adds left.value and right.value methods to Either, which will return the selected value of the Either if defined, or throw TestFailedException if not."></a>
<a href="EitherValues.html" title="Trait that provides an implicit conversion that adds left.value and right.value methods to Either, which will return the selected value of the Either if defined, or throw TestFailedException if not.">EitherValues</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="" title="A case class implementation of java.util.Map.Entry to make it easier to test Java Maps with ScalaTest Matchers."></a>
<a href="" title="A case class implementation of java.util.Map.Entry to make it easier to test Java Maps with ScalaTest Matchers.">Entry</a>
</li><li class="current-entities indented2">
<a class="object" href="Exceptional$.html" title="Companion object to class Exceptional that provides a factory method and an extractor that enables patterns that match both Failed and Canceled outcomes and extracts the contained exception and a factory method."></a>
<a class="class" href="Exceptional.html" title="Superclass for the two outcomes of running a test that contain an exception: Failed and Canceled."></a>
<a href="Exceptional.html" title="Superclass for the two outcomes of running a test that contain an exception: Failed and Canceled.">Exceptional</a>
</li><li class="current-entities indented2">
<a class="object" href="Failed$.html" title=""></a>
<a class="class" href="Failed.html" title="Outcome for a test that failed, containing an exception describing the cause of the failure."></a>
<a href="Failed.html" title="Outcome for a test that failed, containing an exception describing the cause of the failure.">Failed</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="object" href="FailedStatus$.html" title="Singleton status that represents an already completed run with at least one failed test or aborted suite."></a>
<a href="FailedStatus$.html" title="Singleton status that represents an already completed run with at least one failed test or aborted suite.">FailedStatus</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="FeatureSpec.html" title="A suite of tests in which each test represents one scenario of a feature."></a>
<a href="FeatureSpec.html" title="A suite of tests in which each test represents one scenario of a feature.">FeatureSpec</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="FeatureSpecLike.html" title="Implementation trait for class FeatureSpec, which represents a suite of tests in which each test represents one scenario of a feature."></a>
<a href="FeatureSpecLike.html" title="Implementation trait for class FeatureSpec, which represents a suite of tests in which each test represents one scenario of a feature.">FeatureSpecLike</a>
</li><li class="current-entities indented2">
<a class="object" href="Filter$.html" title=""></a>
<a class="class" href="Filter.html" title="Filter whose apply method determines which of the passed tests to run and ignore based on tags to include and exclude passed as as class parameters."></a>
<a href="Filter.html" title="Filter whose apply method determines which of the passed tests to run and ignore based on tags to include and exclude passed as as class parameters.">Filter</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="Finders.html" title="Annotation used to mark a trait or class as defining a testing style that has a org.scalatest.finders.Finder implementation, which IDEs and other tools can use to discover tests and scopes."></a>
<a href="Finders.html" title="Annotation used to mark a trait or class as defining a testing style that has a org.scalatest.finders.Finder implementation, which IDEs and other tools can use to discover tests and scopes.">Finders</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="FixtureContext.html" title="Marker trait for fixture-context objects, that enables them to be used in testing styles that require type Assertion"></a>
<a href="FixtureContext.html" title="Marker trait for fixture-context objects, that enables them to be used in testing styles that require type Assertion">FixtureContext</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="FlatSpec.html" title="Facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify."></a>
<a href="FlatSpec.html" title="Facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify.">FlatSpec</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="FlatSpecLike.html" title="Implementation trait for class FlatSpec, which facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify."></a>
<a href="FlatSpecLike.html" title="Implementation trait for class FlatSpec, which facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify.">FlatSpecLike</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="FreeSpec.html" title="Facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are nested inside text clauses denoted with the dash operator (-)."></a>
<a href="FreeSpec.html" title="Facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are nested inside text clauses denoted with the dash operator (-).">FreeSpec</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="FreeSpecLike.html" title="Implementation trait for class FreeSpec, which facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are nested inside text clauses denoted with the dash operator (-)."></a>
<a href="FreeSpecLike.html" title="Implementation trait for class FreeSpec, which facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are nested inside text clauses denoted with the dash operator (-).">FreeSpecLike</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="FunSpec.html" title="Facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify."></a>
<a href="FunSpec.html" title="Facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify.">FunSpec</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="FunSpecLike.html" title="Implementation trait for class FunSpec, which facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify."></a>
<a href="FunSpecLike.html" title="Implementation trait for class FunSpec, which facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify.">FunSpecLike</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="FunSuite.html" title="A suite of tests in which each test is represented as a function value."></a>
<a href="FunSuite.html" title="A suite of tests in which each test is represented as a function value.">FunSuite</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="FunSuiteLike.html" title="Implementation trait for class FunSuite, which represents a suite of tests in which each test is represented as a function value."></a>
<a href="FunSuiteLike.html" title="Implementation trait for class FunSuite, which represents a suite of tests in which each test is represented as a function value.">FunSuiteLike</a>
</li><li class="current-entities indented2">
<a class="object" href="FutureOutcome$.html" title="Companion object to FutureOutcomes that contains factory methods for creating already-completed FutureOutcomes."></a>
<a class="class" href="FutureOutcome.html" title="Wrapper class for Future[Outcome] that presents a more convenient API for manipulation in withFixture methods in async styles."></a>
<a href="FutureOutcome.html" title="Wrapper class for Future[Outcome] that presents a more convenient API for manipulation in withFixture methods in async styles.">FutureOutcome</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="GivenWhenThen.html" title="Trait that contains methods named given, when, then, and and, which take a string message and implicit Informer, and forward the message to the informer."></a>
<a href="GivenWhenThen.html" title="Trait that contains methods named given, when, then, and and, which take a string message and implicit Informer, and forward the message to the informer.">GivenWhenThen</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="Ignore.html" title="Annotation used to tag a test, or suite of tests, as ignored."></a>
<a href="Ignore.html" title="Annotation used to tag a test, or suite of tests, as ignored.">Ignore</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="Informer.html" title="Trait to which custom information about a running suite of tests can be reported."></a>
<a href="Informer.html" title="Trait to which custom information about a running suite of tests can be reported.">Informer</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="Informing.html" title="Trait that contains the info method, which can be used to send info to the reporter."></a>
<a href="Informing.html" title="Trait that contains the info method, which can be used to send info to the reporter.">Informing</a>
</li><li class="current-entities indented2">
<a class="object" href="Inside$.html" title="Companion object that facilitates the importing of the inside construct as an alternative to mixing it in."></a>
<a class="trait" href="Inside.html" title="Trait containing the inside construct, which allows you to make statements about nested object graphs using pattern matching."></a>
<a href="Inside.html" title="Trait containing the inside construct, which allows you to make statements about nested object graphs using pattern matching.">Inside</a>
</li><li class="current-entities indented2">
<a class="object" href="Inspectors$.html" title="Companion object that facilitates the importing of Inspectors members as an alternative to mixing it in."></a>
<a class="trait" href="Inspectors.html" title="Provides nestable inspector methods (or just inspectors) that enable assertions to be made about collections."></a>
<a href="Inspectors.html" title="Provides nestable inspector methods (or just inspectors) that enable assertions to be made about collections.">Inspectors</a>
</li><li class="current-entities indented2">
<a class="object" href="LoneElement$.html" title="Companion object that facilitates the importing of LoneElement members as an alternative to mixing it in."></a>
<a class="trait" href="LoneElement.html" title="Trait that provides an implicit conversion that adds to collection types a loneElement method, which will return the value of the lone element if the collection does indeed contain one and only one element, or throw TestFailedException if not."></a>
<a href="LoneElement.html" title="Trait that provides an implicit conversion that adds to collection types a loneElement method, which will return the value of the lone element if the collection does indeed contain one and only one element, or throw TestFailedException if not.">LoneElement</a>
</li><li class="current-entities indented2">
<a class="object" href="Matchers$.html" title="Companion object that facilitates the importing of Matchers members as an alternative to mixing it the trait."></a>
<a class="trait" href="Matchers.html" title="Trait that provides a domain specific language (DSL) for expressing assertions in tests using the word should."></a>
<a href="Matchers.html" title="Trait that provides a domain specific language (DSL) for expressing assertions in tests using the word should.">Matchers</a>
</li><li class="current-entities indented2">
<a class="object" href="MustMatchers$.html" title="Companion object that facilitates the importing of Matchers members as an alternative to mixing it the trait."></a>
<a class="trait" href="MustMatchers.html" title="Trait that provides a domain specific language (DSL) for expressing assertions in tests using the word must."></a>
<a href="MustMatchers.html" title="Trait that provides a domain specific language (DSL) for expressing assertions in tests using the word must.">MustMatchers</a>
</li><li class="current-entities indented2">
<a class="object" href="NonImplicitAssertions$.html" title="Companion object that facilitates the importing of the members of trait Assertions without importing the implicit conversions it provides by default."></a>
<a class="trait" href="NonImplicitAssertions.html" title="Trait that can be mixed into a Suite to disable the implicit conversions provided by default in trait Assertions, which trait Suite extends."></a>
<a href="NonImplicitAssertions.html" title="Trait that can be mixed into a Suite to disable the implicit conversions provided by default in trait Assertions, which trait Suite extends.">NonImplicitAssertions</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="Notifier.html" title="Trait providing an apply method to which status updates about a running suite of tests can be reported."></a>
<a href="Notifier.html" title="Trait providing an apply method to which status updates about a running suite of tests can be reported.">Notifier</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="Notifying.html" title="Trait that contains the note method, which can be used to send a status notification to the reporter."></a>
<a href="Notifying.html" title="Trait that contains the note method, which can be used to send a status notification to the reporter.">Notifying</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="OneInstancePerTest.html" title="Trait that facilitates a style of testing in which each test is run in its own instance of the suite class to isolate each test from the side effects of the other tests in the suite."></a>
<a href="OneInstancePerTest.html" title="Trait that facilitates a style of testing in which each test is run in its own instance of the suite class to isolate each test from the side effects of the other tests in the suite.">OneInstancePerTest</a>
</li><li class="current-entities indented2">
<a class="object" href="OptionValues$.html" title="Companion object that facilitates the importing of OptionValues members as an alternative to mixing it in."></a>
<a class="trait" href="OptionValues.html" title="Trait that provides an implicit conversion that adds a value method to Option, which will return the value of the option if it is defined, or throw TestFailedException if not."></a>
<a href="OptionValues.html" title="Trait that provides an implicit conversion that adds a value method to Option, which will return the value of the option if it is defined, or throw TestFailedException if not.">OptionValues</a>
</li><li class="current-entities indented2">
<a class="object" href="Outcome$.html" title="Companion object for trait Outcome that contains an implicit method that enables collections of Outcomes to be flattened into a collections of contained exceptions."></a>
<a class="class" href="Outcome.html" title="Superclass for the possible outcomes of running a test."></a>
<a href="Outcome.html" title="Superclass for the possible outcomes of running a test.">Outcome</a>
</li><li class="current-entities indented2">
<a class="object" href="OutcomeOf$.html" title="Companion object that facilitates the importing of OutcomeOf's method as an alternative to mixing it in."></a>
<a class="trait" href="OutcomeOf.html" title="Trait that contains the outcomeOf method, which executes a passed code block and transforms the outcome into an Outcome, using the same mechanism used by ScalaTest to produce an Outcome when executing a test."></a>
<a href="OutcomeOf.html" title="Trait that contains the outcomeOf method, which executes a passed code block and transforms the outcome into an Outcome, using the same mechanism used by ScalaTest to produce an Outcome when executing a test.">OutcomeOf</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="ParallelTestExecution.html" title="Trait that causes that the tests of any suite it is mixed into to be run in parallel if a Distributor is passed to runTests."></a>
<a href="ParallelTestExecution.html" title="Trait that causes that the tests of any suite it is mixed into to be run in parallel if a Distributor is passed to runTests.">ParallelTestExecution</a>
</li><li class="current-entities indented2">
<a class="object" href="PartialFunctionValues$.html" title="Companion object that facilitates the importing of PartialFunctionValues members as an alternative to mixing it in."></a>
<a class="trait" href="PartialFunctionValues.html" title="Trait that provides an implicit conversion that adds a valueAt method to PartialFunction, which will return the value (result) of the function applied to the argument passed to valueAt, or throw TestFailedException if the partial function is not defined at the argument."></a>
<a href="PartialFunctionValues.html" title="Trait that provides an implicit conversion that adds a valueAt method to PartialFunction, which will return the value (result) of the function applied to the argument passed to valueAt, or throw TestFailedException if the partial function is not defined at the argument.">PartialFunctionValues</a>
</li><li class="current-entities indented2">
<a class="object" href="Payloads$.html" title="Companion object that facilitates the importing of Payloads members as an alternative to mixing it in."></a>
<a class="trait" href="Payloads.html" title="Trait facilitating the inclusion of a payload in a thrown ScalaTest exception."></a>
<a href="Payloads.html" title="Trait facilitating the inclusion of a payload in a thrown ScalaTest exception.">Payloads</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="object" href="Pending$.html" title="Outcome for a test that was pending, which contains an optional string giving more information on what exactly is needed for the test to become non-pending."></a>
<a href="Pending$.html" title="Outcome for a test that was pending, which contains an optional string giving more information on what exactly is needed for the test to become non-pending.">Pending</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="PendingStatement.html" title="Trait mixed into the result type of the pending statement of trait Assertions, which always throws TestPendingException."></a>
<a href="PendingStatement.html" title="Trait mixed into the result type of the pending statement of trait Assertions, which always throws TestPendingException.">PendingStatement</a>
</li><li class="current-entities indented2">
<a class="object" href="PrivateMethodTester$.html" title="Companion object that facilitates the importing of PrivateMethodTester members as an alternative to mixing it in."></a>
<a class="trait" href="PrivateMethodTester.html" title="Trait that facilitates the testing of private methods."></a>
<a href="PrivateMethodTester.html" title="Trait that facilitates the testing of private methods.">PrivateMethodTester</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="PropSpec.html" title="A suite of property-based tests."></a>
<a href="PropSpec.html" title="A suite of property-based tests.">PropSpec</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="PropSpecLike.html" title="Implementation trait for class PropSpec, which represents a suite of property-based tests."></a>
<a href="PropSpecLike.html" title="Implementation trait for class PropSpec, which represents a suite of property-based tests.">PropSpecLike</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="RandomTestOrder.html" title="Trait that causes tests to be run in pseudo-random order."></a>
<a href="RandomTestOrder.html" title="Trait that causes tests to be run in pseudo-random order.">RandomTestOrder</a>
</li><li class="current-entities indented2">
<a class="object" href="RecoverMethods$.html" title="Companion object that facilitates the importing of RecoverMethods's method as an alternative to mixing it in."></a>
<a class="trait" href="RecoverMethods.html" title="Offers two methods for transforming futures when exceptions are expected."></a>
<a href="RecoverMethods.html" title="Offers two methods for transforming futures when exceptions are expected.">RecoverMethods</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="Reporter.html" title="Trait whose instances collect the results of a running suite of tests and presents those results in some way to the user."></a>
<a href="Reporter.html" title="Trait whose instances collect the results of a running suite of tests and presents those results in some way to the user.">Reporter</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="Rerunner.html" title="Trait whose instances can rerun tests or other entities (such as suites)."></a>
<a href="Rerunner.html" title="Trait whose instances can rerun tests or other entities (such as suites).">Rerunner</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="ResourcefulReporter.html" title="Subtrait of Reporter that contains a dispose method for releasing any finite, non-memory resources, such as file handles, held by the Reporter."></a>
<a href="ResourcefulReporter.html" title="Subtrait of Reporter that contains a dispose method for releasing any finite, non-memory resources, such as file handles, held by the Reporter.">ResourcefulReporter</a>
</li><li class="current-entities indented2">
<a class="object" href="Retries$.html" title="Companion object to trait Retries that enables its members to be imported as an alternative to mixing them in."></a>
<a class="trait" href="Retries.html" title="Provides methods that can be used in withFixture implementations to retry tests in various scenarios."></a>
<a href="Retries.html" title="Provides methods that can be used in withFixture implementations to retry tests in various scenarios.">Retries</a>
</li><li class="current-entities indented2">
<a class="object" href="Sequential$.html" title="Companion object to class Sequential that offers an apply factory method for creating a Sequential instance."></a>
<a class="class" href="Sequential.html" title="A Suite class mixing in SequentialNestedSuiteExecution that takes zero to many Suites, which will be returned from its nestedSuites method."></a>
<a href="Sequential.html" title="A Suite class mixing in SequentialNestedSuiteExecution that takes zero to many Suites, which will be returned from its nestedSuites method.">Sequential</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="SequentialNestedSuiteExecution.html" title="Trait that causes the nested suites of any suite it is mixed into to be run sequentially even if a Distributor is passed to runNestedSuites."></a>
<a href="SequentialNestedSuiteExecution.html" title="Trait that causes the nested suites of any suite it is mixed into to be run sequentially even if a Distributor is passed to runNestedSuites.">SequentialNestedSuiteExecution</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="SeveredStackTraces.html" title="Trait that causes StackDepth exceptions thrown by a running test (such as TestFailedExceptions) to have the exception's stack trace severed at the stack depth."></a>
<a href="SeveredStackTraces.html" title="Trait that causes StackDepth exceptions thrown by a running test (such as TestFailedExceptions) to have the exception's stack trace severed at the stack depth.">SeveredStackTraces</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="Shell.html" title="Trait whose instances provide a run method and configuration fields that implement the ScalaTest shell: its DSL for the Scala interpreter."></a>
<a href="Shell.html" title="Trait whose instances provide a run method and configuration fields that implement the ScalaTest shell: its DSL for the Scala interpreter.">Shell</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="StatefulStatus.html" title="Status implementation that can change its state over time."></a>
<a href="StatefulStatus.html" title="Status implementation that can change its state over time.">StatefulStatus</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="Status.html" title="The result status of running a test or a suite, which is used to support parallel and asynchronous execution of tests."></a>
<a href="Status.html" title="The result status of running a test or a suite, which is used to support parallel and asynchronous execution of tests.">Status</a>
</li><li class="current-entities indented2">
<a class="object" href="Stepwise$.html" title="Companion object to class Stepwise that offers an apply factory method for creating a Stepwise instance."></a>
<a class="class" href="Stepwise.html" title="A Suite class that takes zero to many Suites, which will be returned from its nestedSuites method and executed in &ldquo;stepwise&rdquo; fashion by its runNestedSuites method."></a>
<a href="Stepwise.html" title="A Suite class that takes zero to many Suites, which will be returned from its nestedSuites method and executed in &ldquo;stepwise&rdquo; fashion by its runNestedSuites method.">Stepwise</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="StepwiseNestedSuiteExecution.html" title="Trait that causes the nested suites of any suite it is mixed into to be run sequentially even if a Distributor is passed to runNestedSuites."></a>
<a href="StepwiseNestedSuiteExecution.html" title="Trait that causes the nested suites of any suite it is mixed into to be run sequentially even if a Distributor is passed to runNestedSuites.">StepwiseNestedSuiteExecution</a>
</li><li class="current-entities indented2">
<a class="object" href="Stopper$.html" title="Companion object to Stopper that holds a factory method that produces a new Stopper whose stopRequested method returns false until after its requestStop has been invoked."></a>
<a class="trait" href="Stopper.html" title="Trait whose instances can accept a stop request and indicate whether a stop has already been requested."></a>
<a href="Stopper.html" title="Trait whose instances can accept a stop request and indicate whether a stop has already been requested.">Stopper</a>
</li><li class="current-entities indented2">
<a class="object" href="StreamlinedXml$.html" title="Companion object that facilitates the importing of StreamlinedXml members as an alternative to mixing it the trait."></a>
<a class="trait" href="StreamlinedXml.html" title="Trait providing a streamlined method that returns a Uniformity[T] instance for any subtype of scala.xml.NodeSeq that will normalize the XML by removing empty text nodes and trimming non-empty text nodes."></a>
<a href="StreamlinedXml.html" title="Trait providing a streamlined method that returns a Uniformity[T] instance for any subtype of scala.xml.NodeSeq that will normalize the XML by removing empty text nodes and trimming non-empty text nodes.">StreamlinedXml</a>
</li><li class="current-entities indented2">
<a class="object" href="StreamlinedXmlEquality$.html" title="Companion object that facilitates the importing of StreamlinedXmlEquality members as an alternative to mixing it the trait."></a>
<a class="trait" href="StreamlinedXmlEquality.html" title="Trait providing an implicit Equality[T] for subtypes of scala.xml.NodeSeq that before testing for equality, will normalize left and right sides by removing empty XML text nodes and trimming non-empty text nodes."></a>
<a href="StreamlinedXmlEquality.html" title="Trait providing an implicit Equality[T] for subtypes of scala.xml.NodeSeq that before testing for equality, will normalize left and right sides by removing empty XML text nodes and trimming non-empty text nodes.">StreamlinedXmlEquality</a>
</li><li class="current-entities indented2">
<a class="object" href="StreamlinedXmlNormMethods$.html" title="Companion object that facilitates the importing of StreamlinedXmlNormMethods members as an alternative to mixing it the trait."></a>
<a class="trait" href="StreamlinedXmlNormMethods.html" title="Subtrait of NormMethods that provides an implicit Uniformity[T] for subtypes of scala.xml.NodeSeq that enables you to streamline XML by invoking .norm on it."></a>
<a href="StreamlinedXmlNormMethods.html" title="Subtrait of NormMethods that provides an implicit Uniformity[T] for subtypes of scala.xml.NodeSeq that enables you to streamline XML by invoking .norm on it.">StreamlinedXmlNormMethods</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="object" href="Succeeded$.html" title="Outcome for a test that succeeded."></a>
<a href="Succeeded$.html" title="Outcome for a test that succeeded.">Succeeded</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="object" href="SucceededStatus$.html" title="Singleton status that represents an already completed run with no tests failed and no suites aborted."></a>
<a href="SucceededStatus$.html" title="Singleton status that represents an already completed run with no tests failed and no suites aborted.">SucceededStatus</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="Suite.html" title="A suite of tests."></a>
<a href="Suite.html" title="A suite of tests.">Suite</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="SuiteMixin.html" title="Trait defining abstract "lifecycle" methods that are implemented in Suite and can be overridden in stackable modification traits."></a>
<a href="SuiteMixin.html" title="Trait defining abstract "lifecycle" methods that are implemented in Suite and can be overridden in stackable modification traits.">SuiteMixin</a>
</li><li class="current-entities indented2">
<a class="object" href="Suites$.html" title="Companion object to class Suites that offers an apply factory method for creating a Suites instance."></a>
<a class="class" href="Suites.html" title="A Suite class that takes zero to many Suites in its constructor, which will be returned from its nestedSuites method."></a>
<a href="Suites.html" title="A Suite class that takes zero to many Suites in its constructor, which will be returned from its nestedSuites method.">Suites</a>
</li><li class="current-entities indented2">
<a class="object" href="Tag$.html" title="Companion object for Tag, which offers a factory method."></a>
<a class="class" href="Tag.html" title="Class whose subclasses can be used to tag tests in style traits in which tests are defined as functions."></a>
<a href="Tag.html" title="Class whose subclasses can be used to tag tests in style traits in which tests are defined as functions.">Tag</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="TagAnnotation.html" title="Annotation used to annotate annotation interfaces that define tags for ScalaTest tests."></a>
<a href="TagAnnotation.html" title="Annotation used to annotate annotation interfaces that define tags for ScalaTest tests.">TagAnnotation</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="TestData.html" title="A bundle of information about the current test."></a>
<a href="TestData.html" title="A bundle of information about the current test.">TestData</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="TestRegistration.html" title="Trait declaring methods that can be used to register by-name test functions that have any result type."></a>
<a href="TestRegistration.html" title="Trait declaring methods that can be used to register by-name test functions that have any result type.">TestRegistration</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="TestSuite.html" title="The base trait of ScalaTest's synchronous testing styles, which defines a withFixture lifecycle method that accepts as its parameter a test function that returns an Outcome."></a>
<a href="TestSuite.html" title="The base trait of ScalaTest's synchronous testing styles, which defines a withFixture lifecycle method that accepts as its parameter a test function that returns an Outcome.">TestSuite</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="TestSuiteMixin.html" title=""></a>
<a href="TestSuiteMixin.html" title="">TestSuiteMixin</a>
</li><li class="current-entities indented2">
<a class="object" href="Tracker$.html" title=""></a>
<a class="class" href="Tracker.html" title="Class that tracks the progress of a series of Ordinals produced by invoking next and nextNewOldPair on the current Ordinal."></a>
<a href="Tracker.html" title="Class that tracks the progress of a series of Ordinals produced by invoking next and nextNewOldPair on the current Ordinal.">Tracker</a>
</li><li class="current-entities indented2">
<a class="object" href="TryValues$.html" title="Companion object that facilitates the importing of TryValues members as an alternative to mixing it in."></a>
<a class="trait" href="TryValues.html" title="Trait that provides an implicit conversion that adds success and failure methods to scala.util.Try, enabling you to make assertions about the value of a Success or the exception of a Failure."></a>
<a href="TryValues.html" title="Trait that provides an implicit conversion that adds success and failure methods to scala.util.Try, enabling you to make assertions about the value of a Success or the exception of a Failure.">TryValues</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="class" href="WordSpec.html" title="Facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify."></a>
<a href="WordSpec.html" title="Facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify.">WordSpec</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="WordSpecLike.html" title="Implementation trait for class WordSpec, which facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify."></a>
<a href="WordSpecLike.html" title="Implementation trait for class WordSpec, which facilitates a &ldquo;behavior-driven&rdquo; style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify.">WordSpecLike</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="trait" href="WrapWith.html" title="Annotation to associate a wrapper suite with a non-Suite class, so it can be run via ScalaTest."></a>
<a href="WrapWith.html" title="Annotation to associate a wrapper suite with a non-Suite class, so it can be run via ScalaTest.">WrapWith</a>
</li><li class="current-entities indented2">
<span class="separator"></span>
<a class="object" href="run$.html" title="Singleton object providing an apply method for the ScalaTest shell and a main method for ScalaTest's simple runner."></a>
<a href="run$.html" title="Singleton object providing an apply method for the ScalaTest shell and a main method for ScalaTest's simple runner.">run</a>
</li>
</ul>
</div>
</div>
<div id="content">
<body class="class type">
<!-- Top of doc.scalatest.org [javascript] -->
<script type="text/javascript">
var rnd = window.rnd || Math.floor(Math.random()*10e6);
var pid204546 = window.pid204546 || rnd;
var plc204546 = window.plc204546 || 0;
var abkw = window.abkw || '';
var absrc = 'http://ab167933.adbutler-ikon.com/adserve/;ID=167933;size=468x60;setID=204546;type=js;sw='+screen.width+';sh='+screen.height+';spr='+window.devicePixelRatio+';kw='+abkw+';pid='+pid204546+';place='+(plc204546++)+';rnd='+rnd+';click=CLICK_MACRO_PLACEHOLDER';
document.write('<scr'+'ipt src="'+absrc+'" type="text/javascript"></scr'+'ipt>');
</script>
<div id="definition">
<div class="big-circle class">c</div>
<p id="owner"><a href="../index.html" class="extype" name="org">org</a>.<a href="index.html" class="extype" name="org.scalatest">scalatest</a></p>
<h1>Entry<span class="permalink">
<a href="../../org/scalatest/Entry.html" title="Permalink">
<i class="material-icons"></i>
</a>
</span></h1>
<h3><span class="morelinks"></span></h3>
</div>
<h4 id="signature" class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">case class</span>
</span>
<span class="symbol">
<span class="name">Entry</span><span class="tparams">[<span name="K">K</span>, <span name="V">V</span>]</span><span class="params">(<span name="key">key: <span class="extype" name="org.scalatest.Entry.K">K</span></span>, <span name="value">value: <span class="extype" name="org.scalatest.Entry.V">V</span></span>)</span><span class="result"> extends <span class="extype" name="java.util.Map.Entry">java.util.Map.Entry</span>[<span class="extype" name="org.scalatest.Entry.K">K</span>, <span class="extype" name="org.scalatest.Entry.V">V</span>] with <span class="extype" name="scala.Product">Product</span> with <span class="extype" name="scala.Serializable">Serializable</span></span>
</span>
</h4>
<div id="comment" class="fullcommenttop"><div class="comment cmt"><p>A case class implementation of <code>java.util.Map.Entry</code> to make it easier to
test Java <code>Map</code>s with ScalaTest <a href="Matchers.html">Matchers</a>.</p><p>In Java, <code>java.util.Map</code> is not a subtype of <code>java.util.Collection</code>, and does not
actually define an element type. You can ask a Java <code>Map</code> for an “entry set”
via the <code>entrySet</code> method, which will return the <code>Map</code>'s key/value pairs
wrapped in a set of <code>java.util.Map.Entry</code>, but a <code>Map</code> is not actually
a collection of <code>Entry</code>. To make Java <code>Map</code>s easier to work with, however,
ScalaTest matchers allows you to treat a Java <code>Map</code> as a collection of <code>Entry</code>,
and defines this convenience implementation of <code>java.util.Map.Entry</code>.
Here's how you use it:</p><p><pre class="stHighlighted">
javaMap should contain (<span class="stType">Entry</span>(<span class="stLiteral">2</span>, <span class="stLiteral">3</span>))
javaMap should contain oneOf (<span class="stType">Entry</span>(<span class="stLiteral">2</span>, <span class="stLiteral">3</span>), <span class="stType">Entry</span>(<span class="stLiteral">3</span>, <span class="stLiteral">4</span>))
</pre>
</p></div><dl class="paramcmts block"><dt class="param">key</dt><dd class="cmt"><p>the key of this entry</p></dd><dt class="param">value</dt><dd class="cmt"><p>the value of this entry</p></dd></dl><dl class="attributes block"> <dt>Source</dt><dd><a href="https://github.com/scalatest/scalatest/tree/release-3.0.7/scalatest//src/main/scala/org/scalatest/Entry.scala" target="_blank">Entry.scala</a></dd></dl><div class="toggleContainer block">
<span class="toggle">
Linear Supertypes
</span>
<div class="superTypes hiddenContent"><span class="extype" name="scala.Serializable">Serializable</span>, <span class="extype" name="java.io.Serializable">Serializable</span>, <span class="extype" name="scala.Product">Product</span>, <span class="extype" name="scala.Equals">Equals</span>, <span class="extype" name="java.util.Map.Entry">java.util.Map.Entry</span>[<span class="extype" name="org.scalatest.Entry.K">K</span>, <span class="extype" name="org.scalatest.Entry.V">V</span>], <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div>
</div></div>
<div id="mbrsel">
<div class="toggle"></div>
<div id="memberfilter">
<i class="material-icons arrow"></i>
<span class="input">
<input id="mbrsel-input" placeholder="Filter all members" type="text" accesskey="/" />
</span>
<i class="clear material-icons"></i>
</div>
<div id="filterby">
<div id="order">
<span class="filtertype">Ordering</span>
<ol>
<li class="alpha in"><span>Alphabetic</span></li>
<li class="inherit out"><span>By Inheritance</span></li>
</ol>
</div>
<div class="ancestors">
<span class="filtertype">Inherited<br />
</span>
<ol id="linearization">
<li class="in" name="org.scalatest.Entry"><span>Entry</span></li><li class="in" name="scala.Serializable"><span>Serializable</span></li><li class="in" name="java.io.Serializable"><span>Serializable</span></li><li class="in" name="scala.Product"><span>Product</span></li><li class="in" name="scala.Equals"><span>Equals</span></li><li class="in" name="java.util.Map.Entry"><span>Entry</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li>
</ol>
</div><div class="ancestors">
<span class="filtertype"></span>
<ol>
<li class="hideall out"><span>Hide All</span></li>
<li class="showall in"><span>Show All</span></li>
</ol>
</div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
</div>
<div id="template">
<div id="allMembers">
<div id="constructors" class="members">
<h3>Instance Constructors</h3>
<ol><li name="org.scalatest.Entry#<init>" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="<init>(key:K,value:V):org.scalatest.Entry[K,V]"></a><a id="<init>:Entry[K,V]"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#<init>(key:K,value:V):org.scalatest.Entry[K,V]" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">new</span>
</span>
<span class="symbol">
<span class="name">Entry</span><span class="params">(<span name="key">key: <span class="extype" name="org.scalatest.Entry.K">K</span></span>, <span name="value">value: <span class="extype" name="org.scalatest.Entry.V">V</span></span>)</span>
</span>
<p class="shortcomment cmt"></p><div class="fullcomment"><div class="comment cmt"></div><dl class="paramcmts block"><dt class="param">key</dt><dd class="cmt"><p>the key of this entry</p></dd><dt class="param">value</dt><dd class="cmt"><p>the value of this entry</p></dd></dl></div>
</li></ol>
</div>
<div class="values members">
<h3>Value Members</h3>
<ol>
<li name="scala.AnyRef#!=" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:Any):Boolean"></a><a id="!=(Any):Boolean"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#!=(x$1:Any):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef###" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="##():Int"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html###():Int" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#==" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:Any):Boolean"></a><a id="==(Any):Boolean"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#==(x$1:Any):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.Any#asInstanceOf" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="asInstanceOf[T0]:T0"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#asInstanceOf[T0]:T0" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#clone" visbl="prt" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="clone():Object"></a><a id="clone():AnyRef"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#clone():Object" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../java/lang/index.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#eq" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="eq(x$1:AnyRef):Boolean"></a><a id="eq(AnyRef):Boolean"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#eq(x$1:AnyRef):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="org.scalatest.Entry#equals" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="equals(other:Any):Boolean"></a><a id="equals(Any):Boolean"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#equals(other:Any):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">equals</span><span class="params">(<span name="other">other: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
<p class="shortcomment cmt">Compares the specified object with this entry for equality.</p><div class="fullcomment"><div class="comment cmt"><p>Compares the specified object with this entry for equality.
</p></div><dl class="paramcmts block"><dt class="param">other</dt><dd class="cmt"><p>the object to be compared for equality with this map entry</p></dd><dt>returns</dt><dd class="cmt"><p>true if the specified object is equal to this map entry</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="org.scalatest.Entry">Entry</a> → Equals → Entry → AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#finalize" visbl="prt" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="finalize():Unit"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#finalize():Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../java/lang/index.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="symbol">classOf[java.lang.Throwable]</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#getClass" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getClass():Class[_]"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#getClass():Class[_]" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
</dd></dl></div>
</li><li name="org.scalatest.Entry#getKey" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getKey():K"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#getKey():K" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getKey</span><span class="params">()</span><span class="result">: <span class="extype" name="org.scalatest.Entry.K">K</span></span>
</span>
<p class="shortcomment cmt">Returns the key corresponding to this <code>Entry</code>.</p><div class="fullcomment"><div class="comment cmt"><p>Returns the key corresponding to this <code>Entry</code>.
</p></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>the key corresponding to this entry</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="org.scalatest.Entry">Entry</a> → Entry</dd></dl></div>
</li><li name="org.scalatest.Entry#getValue" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getValue():V"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#getValue():V" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getValue</span><span class="params">()</span><span class="result">: <span class="extype" name="org.scalatest.Entry.V">V</span></span>
</span>
<p class="shortcomment cmt">Returns the value corresponding to this entry.</p><div class="fullcomment"><div class="comment cmt"><p>Returns the value corresponding to this entry.
</p></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>the value corresponding to this entry</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="org.scalatest.Entry">Entry</a> → Entry</dd></dl></div>
</li><li name="org.scalatest.Entry#hashCode" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="hashCode():Int"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#hashCode():Int" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
<p class="shortcomment cmt">Returns the hash code value for this map entry.</p><div class="fullcomment"><div class="comment cmt"><p>Returns the hash code value for this map entry.
</p></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>the hash code value for this map entry</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="org.scalatest.Entry">Entry</a> → Entry → AnyRef → Any</dd></dl></div>
</li><li name="scala.Any#isInstanceOf" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isInstanceOf[T0]:Boolean"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#isInstanceOf[T0]:Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="org.scalatest.Entry#key" visbl="pub" class="indented0 " data-isabs="false" fullComment="no" group="Ungrouped">
<a id="key:K"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#key:K" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">key</span><span class="result">: <span class="extype" name="org.scalatest.Entry.K">K</span></span>
</span>
</li><li name="scala.AnyRef#ne" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ne(x$1:AnyRef):Boolean"></a><a id="ne(AnyRef):Boolean"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#ne(x$1:AnyRef):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notify" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notify():Unit"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#notify():Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#notifyAll" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notifyAll():Unit"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#notifyAll():Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
</dd></dl></div>
</li><li name="org.scalatest.Entry#setValue" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="setValue(v:V):V"></a><a id="setValue(V):V"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#setValue(v:V):V" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">setValue</span><span class="params">(<span name="v">v: <span class="extype" name="org.scalatest.Entry.V">V</span></span>)</span><span class="result">: <span class="extype" name="org.scalatest.Entry.V">V</span></span>
</span>
<p class="shortcomment cmt">Throws <code>UnsupportedOperationException</code>.</p><div class="fullcomment"><div class="comment cmt"><p>Throws <code>UnsupportedOperationException</code>.
</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="org.scalatest.Entry">Entry</a> → Entry</dd><dt>Exceptions thrown</dt><dd><span class="cmt"><p><span class="extype" name="UnsupportedOperationException"><code>UnsupportedOperationException</code></span> unconditionally</p></span></dd></dl></div>
</li><li name="scala.AnyRef#synchronized" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="synchronized[T0](x$1:=>T0):T0"></a><a id="synchronized[T0](⇒T0):T0"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#synchronized[T0](x$1:=>T0):T0" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="org.scalatest.Entry#toString" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="toString():String"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#toString():String" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Predef.String">String</span></span>
</span>
<p class="shortcomment cmt">Returns a <code>String</code> representation of this <code>Entry</code> consisting of
concatenating the result of invoking <code>toString</code> on the <code>key</code>,
an equals sign, and the result of invoking <code>toString</code> on the <code>value</code>.</p><div class="fullcomment"><div class="comment cmt"><p>Returns a <code>String</code> representation of this <code>Entry</code> consisting of
concatenating the result of invoking <code>toString</code> on the <code>key</code>,
an equals sign, and the result of invoking <code>toString</code> on the <code>value</code>.
</p></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>a <code>String</code> already!</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="org.scalatest.Entry">Entry</a> → AnyRef → Any</dd></dl></div>
</li><li name="org.scalatest.Entry#value" visbl="pub" class="indented0 " data-isabs="false" fullComment="no" group="Ungrouped">
<a id="value:V"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#value:V" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">value</span><span class="result">: <span class="extype" name="org.scalatest.Entry.V">V</span></span>
</span>
</li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait():Unit"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#wait():Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long,x$2:Int):Unit"></a><a id="wait(Long,Int):Unit"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#wait(x$1:Long,x$2:Int):Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long):Unit"></a><a id="wait(Long):Unit"></a>
<span class="permalink">
<a href="../../org/scalatest/Entry.html#wait(x$1:Long):Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li>
</ol>
</div>
</div>
<div id="inheritedMembers">
<div class="parent" name="scala.Serializable">
<h3>Inherited from <span class="extype" name="scala.Serializable">Serializable</span></h3>
</div><div class="parent" name="java.io.Serializable">
<h3>Inherited from <span class="extype" name="java.io.Serializable">Serializable</span></h3>
</div><div class="parent" name="scala.Product">
<h3>Inherited from <span class="extype" name="scala.Product">Product</span></h3>
</div><div class="parent" name="scala.Equals">
<h3>Inherited from <span class="extype" name="scala.Equals">Equals</span></h3>
</div><div class="parent" name="java.util.Map.Entry">
<h3>Inherited from <span class="extype" name="java.util.Map.Entry">java.util.Map.Entry</span>[<span class="extype" name="org.scalatest.Entry.K">K</span>, <span class="extype" name="org.scalatest.Entry.V">V</span>]</h3>
</div><div class="parent" name="scala.AnyRef">
<h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3>
</div><div class="parent" name="scala.Any">
<h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3>
</div>
</div>
<div id="groupedMembers">
<div class="group" name="Ungrouped">
<h3>Ungrouped</h3>
</div>
</div>
</div>
<div id="tooltip"></div>
<div id="footer"> </div>
</body>
</div>
</div>
</div>
</body>
</html>
| {
"content_hash": "d4b0dc4dc599276667fbc7ce2b68ff00",
"timestamp": "",
"source": "github",
"line_count": 1553,
"max_line_length": 693,
"avg_line_length": 81.1120412105602,
"alnum_prop": 0.6258623290226806,
"repo_name": "scalatest/scalatest-website",
"id": "f3353ddcd620520f99f182b157a1bc0b2370d263",
"size": "126111",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/scaladoc/3.0.7/org/scalatest/Entry.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "8401192"
},
{
"name": "HTML",
"bytes": "4508833233"
},
{
"name": "JavaScript",
"bytes": "12256885"
},
{
"name": "Procfile",
"bytes": "62"
},
{
"name": "Scala",
"bytes": "136544"
}
],
"symlink_target": ""
} |
title: "Bretagne Atelier"
date: 2016-11-02 19:06
layout: post
category: ["entreprise"]
tags: []
tagid: "Bretagne Atelier"
#embed_youtube:
illustration: /images/bretagneatelier.jpg
entreprise.geocode: [48.053525,-1.698077]
entreprise.effectif: 600
entreprise.chiffredaffaire: 21 M€
entreprise.activite: Fabrication d'autres équipements automobiles
entreprise.identifiant_national: 304602527
---
Cette entreprise de 500 employés donc plus de 400 travailleurs handicapés est spécialisée dans le secteur industriel (montage de pièces automobiles, transports, dématérialisation, ...). A travers son projet CRISTAL, elle a mis en place un management participatif et social. Elle réalise 21 millions d'euros de chiffre d'affaire.
[Consulter la page dédiée au Management sur le site de l'entreprise](http://www.bretagne-ateliers.com/bretagne-ateliers/management/)
| {
"content_hash": "cb6631e3216d94e4c7ddeca30387efdf",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 328,
"avg_line_length": 47.72222222222222,
"alnum_prop": 0.8009313154831199,
"repo_name": "organisationsliberees/organisationsliberees.github.io",
"id": "8cd65221658e9941a6e00ea491fee6d7d3e35a81",
"size": "876",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2016-11-02-bretagne-atelier.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10835"
},
{
"name": "HTML",
"bytes": "27744"
},
{
"name": "Makefile",
"bytes": "370"
},
{
"name": "Shell",
"bytes": "1761"
}
],
"symlink_target": ""
} |
//
// ScribbleEraseView.m
#import "ScribbleEraseView.h"
#import "Scribble.h"
#import "ScribCapControl.h"
#import "TLogControlMacro.h"
#define kEraseWidthAmplifyFactor (4.0)
float const TScribbleLineWidth = 4.0;
@interface ScribbleEraseView ()<ScribProcessor,ScribbleViewDelegate>
@property (nonatomic,strong) NSMutableDictionary* scribbles;
@property (nonatomic, strong) NSMutableArray *finishedScribbles;
@end
@implementation ScribbleEraseView
#pragma mark - Scribble Erase view Initilization
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
ScribCapControl *scribbleControl = [ScribCapControl sharedControl];
scribbleControl.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) ;
scribbleControl.controller = self;
scribbleControl.scribTarget = self;
self.scribbleDelegate = self;
[self addSubview:scribbleControl];
self.scribbles = [NSMutableDictionary dictionary];
self.lineWidth = self.eraseWidth = TScribbleLineWidth;
self.finishedScribbles = [NSMutableArray array];
self.currentScribbleStrokeColor = [UIColor blackColor];
}
return self;
}
#pragma mark - Draw Scribbles in context
- (void)drawScribble:(Scribble *)scribble inContext:(CGContextRef)context{
CGColorRef colorRef = [scribble.strokeColor CGColor];
CGContextAddPath(context, scribble.drawingPath);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, self.lineWidth);
CGContextSetStrokeColorWithColor(context, colorRef);
CGContextStrokePath(context);
}
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
for (NSString *key in self.scribbles){
Scribble *scribble = [self.scribbles valueForKey:key];
[self drawScribble:scribble inContext:context];
}
for (Scribble *scribble in self.finishedScribbles) {
if (!scribble.isEraseOn) {
[self drawScribble:scribble inContext:context];
}
}
}
#pragma mark - Clear all scribbles
- (void)resetView{
[self.scribbles removeAllObjects];
[self.finishedScribbles removeAllObjects];
[self setNeedsDisplay];
}
#pragma mark - Scribble manipulation - Helping methods
- (void) initScribble:(Scribble*) scribble WithPoint : (CGPoint) point{
[scribble setStrokeColor:self.currentScribbleStrokeColor];
[scribble setIsEraseOn:self.isEraseOn];
if (scribble.isEraseOn) {
[scribble setLineWidth:(self.eraseWidth * kEraseWidthAmplifyFactor)];
}
else {
[scribble setLineWidth:self.lineWidth];
[scribble addPoint:point];
}
}
- (void) eraseScribbleInRect:(CGRect)eraseRect{
for (Scribble *finishedScribble in self.finishedScribbles)
{
for (int pointIndex = 0; pointIndex < [finishedScribble getPoints].count; pointIndex++) {
CGPoint currentPoint = [finishedScribble getPointAtIndex:pointIndex];
if (CGRectContainsPoint(eraseRect, currentPoint)){
finishedScribble.isEraseOn = YES;
break;
}
}
}
}
#pragma mark - Scribble manipulation depending on touch event
- (void) addTouchPoint:(CGPoint)point forTouch:(UITouch *)touch AndEvent:(UIEvent *) event{
Scribble *scribble = [[Scribble alloc] init];
[self initScribble:scribble WithPoint:point];
if (scribble.isEraseOn) {
if ([self.scribbleDelegate respondsToSelector:@selector(logEraseStart)])
[self.scribbleDelegate logEraseStart];
} else {
if ([self.scribbleDelegate respondsToSelector:@selector(logScribbleStart)])
[self.scribbleDelegate logScribbleStart];
}
NSValue *touchValue = [NSValue valueWithPointer:(__bridge const void *)(touch)];
NSString *key = [NSString stringWithFormat:@"%@", touchValue];
BOOL touchShouldBeCancelled;
NSSet *keysOfScribblesToBeRemoved=[self.scribbles keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) {
Scribble *scrib=(Scribble*)obj;
CGPoint topPoint = scrib.topMostPoint;
return (topPoint.y > point.y);
}];
if ([keysOfScribblesToBeRemoved anyObject]) {
[self.scribbles removeObjectsForKeys:[keysOfScribblesToBeRemoved allObjects]];
}
touchShouldBeCancelled=([[self.scribbles allValues] count]>0)?YES:NO;
if (!touchShouldBeCancelled) {
[self.scribbles setValue:scribble forKey:key];
}
}
- (void) appendTouchPoint:(CGPoint)point forTouch:(UITouch *)touch AndEvent:(UIEvent *) event{
NSValue *touchValue = [NSValue valueWithPointer:(__bridge const void *)(touch)];
Scribble *scribble = [self.scribbles valueForKey:
[NSString stringWithFormat:@"%@", touchValue]];
if (scribble.isEraseOn) {
CGRect eraseRect = CGRectMake(point.x, point.y, scribble.lineWidth, scribble.lineWidth);
[self eraseScribbleInRect:eraseRect];
[self setNeedsDisplay];
}
else {
CGRect drawRect = [scribble addPoint:point];
[self setNeedsDisplayInRect:drawRect];
}
}
- (void) endTouchPoint:(CGPoint)point forTouch:(UITouch *)touch AndEvent:(UIEvent *) event; {
NSValue *touchValue = [NSValue valueWithPointer:(__bridge const void *)(touch)];
NSString *key = [NSString stringWithFormat:@"%@", touchValue];
Scribble *scribble = [self.scribbles valueForKey:key];
if (scribble) {
if (scribble.isEraseOn) {
if ([self.scribbleDelegate respondsToSelector:@selector(logEraseEnd)])
[self.scribbleDelegate logEraseEnd];
} else {
if ([self.scribbleDelegate respondsToSelector:@selector(logScribbleEnd)])
[self.scribbleDelegate logScribbleEnd];
if ([self.scribbleDelegate respondsToSelector:@selector(scribbleDidEnd)])
[self.scribbleDelegate scribbleDidEnd];
}
if (!scribble.isEraseOn) {
[self.finishedScribbles addObject:scribble];
}
[self.scribbles removeObjectForKey:key];
if ([self.finishedScribbles count] == 1) {
if ([self.scribbleDelegate respondsToSelector:@selector(scribbleDidStart)])
[self.scribbleDelegate scribbleDidStart];
}
}
else {
TLog(@"ended scribb, object not found in scrib show view!\n");
}
[self setNeedsDisplay];
}
- (void) cancelTouchPoint:(CGPoint)point forTouch:(UITouch *)touch AndEvent:(UIEvent *) event {
TLog(@"Cancelled touch with point X=%.2f and y=%.2f \n", point.x, point.y);
}
-(void) outOfBounds:(CGPoint)point forTouch:(UITouch*)touch andEvent:(UIEvent*)event
{
NSValue *touchValue = [NSValue valueWithPointer:(__bridge const void *)(touch)];
NSString *key = [NSString stringWithFormat:@"%@", touchValue];
Scribble *scribble = [self.scribbles valueForKey:key];
if (scribble)
{
if (scribble.isEraseOn) {
if ([self.scribbleDelegate respondsToSelector:@selector(logEraseEnd)])
[self.scribbleDelegate logEraseEnd];
} else {
if ([self.scribbleDelegate respondsToSelector:@selector(logScribbleEnd)])
[self.scribbleDelegate logScribbleEnd];
if ([self.scribbleDelegate respondsToSelector:@selector(scribbleDidEnd)])
[self.scribbleDelegate scribbleDidEnd];
}
if (!scribble.isEraseOn) {
[self.finishedScribbles addObject:scribble];
}
[self.scribbles removeObjectForKey:key];
}
[self setNeedsDisplay];
}
#pragma mark - Get Finished Scribbles
-(NSArray*) getFinishedScribbles {
return [NSArray arrayWithArray:self.finishedScribbles];
}
-(void) changeColorOfScribbleTo:(UIColor*)changedColor {
if (changedColor) {
self.currentScribbleStrokeColor =changedColor;
}
[self setNeedsDisplay];
}
#pragma mark - Scribble Processor Delegate
- (void) didPassOnTouch:(UITouch *) touch withEvent:(UIEvent *) event
{
if(!self) return;
CGPoint tPt = [touch locationInView: self];
if (!(CGRectContainsPoint(self.bounds, tPt)))
{
TLog(@"Out of bounds");
[self outOfBounds:tPt forTouch:touch andEvent:event];
return;
}
if (UITouchPhaseBegan == touch.phase) {
[self addTouchPoint:tPt forTouch:touch AndEvent:event];
}
if (UITouchPhaseMoved == touch.phase) {
[self appendTouchPoint:tPt forTouch:touch AndEvent:event];
}
if (UITouchPhaseEnded == touch.phase) {
[self endTouchPoint:tPt forTouch:touch AndEvent:event];
}
if (UITouchPhaseCancelled == touch.phase) {
[self cancelTouchPoint:tPt forTouch:touch AndEvent:event];
}
}
-(void) scribbleDidEnd
{
if (self.scribbleEndCompletion)
self.scribbleEndCompletion();
}
@end
| {
"content_hash": "e9fa5f1e10891642995efa9ad9db0039",
"timestamp": "",
"source": "github",
"line_count": 266,
"max_line_length": 114,
"avg_line_length": 33.59398496240601,
"alnum_prop": 0.6732318710832588,
"repo_name": "npctech/Tattle-UI-iOS",
"id": "277ea25b394a22f19057029eb019c7b7a019ad0f",
"size": "10042",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "TattleControl/ScribbleEraseView.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1367"
},
{
"name": "Objective-C",
"bytes": "153858"
},
{
"name": "Swift",
"bytes": "5094"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<title>Uses of Class org.apache.poi.hssf.record.PageBreakRecord.Break (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.poi.hssf.record.PageBreakRecord.Break (POI API Documentation)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/poi/hssf/record/PageBreakRecord.Break.html" title="class in org.apache.poi.hssf.record">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>PREV</li>
<li>NEXT</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/poi/hssf/record//class-usePageBreakRecord.Break.html" target="_top">FRAMES</a></li>
<li><a href="PageBreakRecord.Break.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.poi.hssf.record.PageBreakRecord.Break" class="title">Uses of Class<br>org.apache.poi.hssf.record.PageBreakRecord.Break</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../org/apache/poi/hssf/record/PageBreakRecord.Break.html" title="class in org.apache.poi.hssf.record">PageBreakRecord.Break</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.poi.hssf.record">org.apache.poi.hssf.record</a></td>
<td class="colLast">
<div class="block">Record package contains class representations for XLS binary strutures.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.poi.hssf.record">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/apache/poi/hssf/record/PageBreakRecord.Break.html" title="class in org.apache.poi.hssf.record">PageBreakRecord.Break</a> in <a href="../../../../../../org/apache/poi/hssf/record/package-summary.html">org.apache.poi.hssf.record</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/apache/poi/hssf/record/package-summary.html">org.apache.poi.hssf.record</a> that return <a href="../../../../../../org/apache/poi/hssf/record/PageBreakRecord.Break.html" title="class in org.apache.poi.hssf.record">PageBreakRecord.Break</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/apache/poi/hssf/record/PageBreakRecord.Break.html" title="class in org.apache.poi.hssf.record">PageBreakRecord.Break</a></code></td>
<td class="colLast"><span class="strong">PageBreakRecord.</span><code><strong><a href="../../../../../../org/apache/poi/hssf/record/PageBreakRecord.html#getBreak(int)">getBreak</a></strong>(int main)</code>
<div class="block">Retrieves the region at the row/column indicated</div>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/apache/poi/hssf/record/package-summary.html">org.apache.poi.hssf.record</a> that return types with arguments of type <a href="../../../../../../org/apache/poi/hssf/record/PageBreakRecord.Break.html" title="class in org.apache.poi.hssf.record">PageBreakRecord.Break</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>java.util.Iterator<<a href="../../../../../../org/apache/poi/hssf/record/PageBreakRecord.Break.html" title="class in org.apache.poi.hssf.record">PageBreakRecord.Break</a>></code></td>
<td class="colLast"><span class="strong">PageBreakRecord.</span><code><strong><a href="../../../../../../org/apache/poi/hssf/record/PageBreakRecord.html#getBreaksIterator()">getBreaksIterator</a></strong>()</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/poi/hssf/record/PageBreakRecord.Break.html" title="class in org.apache.poi.hssf.record">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>PREV</li>
<li>NEXT</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/poi/hssf/record//class-usePageBreakRecord.Break.html" target="_top">FRAMES</a></li>
<li><a href="PageBreakRecord.Break.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright 2014 The Apache Software Foundation or
its licensors, as applicable.</i>
</small></p>
</body>
</html>
| {
"content_hash": "6dcc9b9d060e1d6bdc23a701a297b751",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 376,
"avg_line_length": 44.5919540229885,
"alnum_prop": 0.6427374661683206,
"repo_name": "tringuyen1401/Stock-analyzing",
"id": "7b91fa84e1732512f39cfb769b8ae17e54a8b1d0",
"size": "7759",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "jdbc/lib/poi-3.11/docs/apidocs/org/apache/poi/hssf/record/class-use/PageBreakRecord.Break.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "23219"
},
{
"name": "HTML",
"bytes": "75486542"
},
{
"name": "Java",
"bytes": "2810339"
},
{
"name": "Rust",
"bytes": "92"
}
],
"symlink_target": ""
} |
'use strict';
let Reflux = require('reflux');
let request = require('superagent');
let actions = require('../actions/app-actions');
let ProductStore = Reflux.createStore({
init() {
this.data = {
products: {
food: [],
fashion: []
}
};
this.listenTo(actions.loadPage, this.loadPage);
},
loadPage(productType,cached) {
if(cached !== true || this.data.products[productType].length === 0) {
request.get('data/' + productType +'.json')
.end((err, res) => {
this.data.products[productType] = JSON.parse(res.text)[0].products;
this.trigger(this.data);
});
} else {
this.trigger(this.data);
}
},
getInitialState() {
return this.data;
}
});
module.exports = ProductStore;
| {
"content_hash": "ae77ccac763308962f224d5c854cf5f8",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 77,
"avg_line_length": 21.216216216216218,
"alnum_prop": 0.5745222929936306,
"repo_name": "JonnyCheng/react-reflux-super-fantastic-shop-demo",
"id": "9d1e1607c20c2e356da775a292a3dcf277a20128",
"size": "785",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/js/stores/product-store.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "19612"
},
{
"name": "HTML",
"bytes": "804"
},
{
"name": "JavaScript",
"bytes": "17182"
}
],
"symlink_target": ""
} |
using namespace std;
public ref class jcOWLManager {
public:
System::String^ Run();
}; | {
"content_hash": "5440f0bfb353c0703d9f59917fda3109",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 31,
"avg_line_length": 15,
"alnum_prop": 0.7111111111111111,
"repo_name": "jcapellman/jcOWL",
"id": "1d027e44cec5b3b35caaa3a6bec7953b7806c89d",
"size": "114",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jcOWL.Lib/jcOWLManager.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "291"
},
{
"name": "C#",
"bytes": "1664"
},
{
"name": "C++",
"bytes": "1633"
},
{
"name": "Objective-C",
"bytes": "173"
}
],
"symlink_target": ""
} |
/**
* PublisherQueryLanguageContextErrorReason.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.v201308;
public class PublisherQueryLanguageContextErrorReason implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected PublisherQueryLanguageContextErrorReason(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _UNEXECUTABLE = "UNEXECUTABLE";
public static final java.lang.String _UNKNOWN = "UNKNOWN";
public static final PublisherQueryLanguageContextErrorReason UNEXECUTABLE = new PublisherQueryLanguageContextErrorReason(_UNEXECUTABLE);
public static final PublisherQueryLanguageContextErrorReason UNKNOWN = new PublisherQueryLanguageContextErrorReason(_UNKNOWN);
public java.lang.String getValue() { return _value_;}
public static PublisherQueryLanguageContextErrorReason fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
PublisherQueryLanguageContextErrorReason enumeration = (PublisherQueryLanguageContextErrorReason)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static PublisherQueryLanguageContextErrorReason fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(PublisherQueryLanguageContextErrorReason.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "PublisherQueryLanguageContextError.Reason"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
| {
"content_hash": "5a32ce05a129cbe92c8fd1604f33ad0a",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 157,
"avg_line_length": 44.02857142857143,
"alnum_prop": 0.7128487994808566,
"repo_name": "google-code-export/google-api-dfp-java",
"id": "a8f86e463f91237d3883e09a194adc36be384894",
"size": "3082",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/google/api/ads/dfp/v201308/PublisherQueryLanguageContextErrorReason.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "39950935"
}
],
"symlink_target": ""
} |
import actors.HostingActor
import akka.actor._
import akka.cluster.Cluster
import akka.cluster.ClusterEvent._
import clashcode.Hello
import clashcode.PrisonerRequest
import clashcode.PrisonerResponse
import clashcode.{PrisonerResponse, PrisonerRequest, Hello, NameRequest}
import com.clashcode.web.controllers.Application
import play.api.Application
import play.api.{Play, GlobalSettings, Logger, Application}
import scala.Some
object Global extends GlobalSettings {
var maybeCluster = Option.empty[ActorSystem]
override def onStart(app: Application) {
super.onStart(app)
// start second system (for clustering example)
Play.configuration(app).getConfig("cluster").foreach(clusterConfig => {
// create cluster system
val system = ActorSystem("cluster", clusterConfig.underlying)
maybeCluster = Some(system)
// start tournament hoster
val hostingActor = system.actorOf(Props[HostingActor], "main")
Application.maybeHostingActor = Some(hostingActor)
// hosting actor listens to cluster events
Cluster(system).subscribe(hostingActor, classOf[ClusterDomainEvent])
// start test prisoner on main server
system.actorOf(Props(classOf[Prisoner], "PrisonerX"), "player")
})
}
override def onStop(app: Application) {
super.onStop(app)
maybeCluster.foreach(_.shutdown())
}
}
class Prisoner(name: String) extends Actor {
def receive = {
case NameRequest => sender ! Hello(name)
case PrisonerRequest(other) => sender ! PrisonerResponse(true)
case x : String => println(x)
}
}
| {
"content_hash": "b2fd48f3f0398dc255a061249fff2dbc",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 75,
"avg_line_length": 27.396551724137932,
"alnum_prop": 0.7337948395217118,
"repo_name": "clashcode/clashcode",
"id": "bd433a9f21849f74af4c2ab68be640326fae452f",
"size": "1589",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/Global.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "0"
},
{
"name": "JavaScript",
"bytes": "2653"
},
{
"name": "Scala",
"bytes": "17809"
}
],
"symlink_target": ""
} |
<?php
namespace Encore\Admin\Grid\Displayers;
use Encore\Admin\Admin;
class RowSelector extends AbstractDisplayer
{
public function display()
{
Admin::script($this->script());
return <<<EOT
<input type="checkbox" class="{$this->grid->getGridRowName()}-checkbox" data-id="{$this->getKey()}" autocomplete="off"/>
EOT;
}
protected function script()
{
$all = $this->grid->getSelectAllName();
$row = $this->grid->getGridRowName();
$selected = trans('admin.grid_items_selected');
return <<<EOT
$('.{$row}-checkbox').iCheck({checkboxClass:'icheckbox_minimal-blue'}).on('ifChanged', function () {
var id = $(this).data('id');
if (this.checked) {
\$.admin.grid.select(id);
$(this).closest('tr').css('background-color', '#ffffd5');
} else {
\$.admin.grid.unselect(id);
$(this).closest('tr').css('background-color', '');
}
}).on('ifClicked', function () {
var id = $(this).data('id');
if (this.checked) {
$.admin.grid.unselect(id);
} else {
$.admin.grid.select(id);
}
var selected = $.admin.grid.selected().length;
if (selected > 0) {
$('.{$all}-btn').show();
} else {
$('.{$all}-btn').hide();
}
$('.{$all}-btn .selected').html("{$selected}".replace('{n}', selected));
});
EOT;
}
}
| {
"content_hash": "ddd104b40680d203b4ffc638fbfde615",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 121,
"avg_line_length": 22.916666666666668,
"alnum_prop": 0.5512727272727272,
"repo_name": "qq447665722/laravel-admin",
"id": "bacccbca072ac56d853e26d8d0cc265f275bd397",
"size": "1375",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Grid/Displayers/RowSelector.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "151167"
},
{
"name": "HTML",
"bytes": "62940"
},
{
"name": "JavaScript",
"bytes": "57415"
},
{
"name": "PHP",
"bytes": "561165"
}
],
"symlink_target": ""
} |
#include "RenderBackgroundComponent.h"
#include "Scene.h"
#include "Renderer.h"
namespace af
{
RenderBackgroundComponent::RenderBackgroundComponent(const Image& image,
float imageWidth, float imageHeight,
int zOrder)
: RenderComponent(zOrder, true),
image_(image),
imageWidth_(imageWidth),
imageHeight_(imageHeight),
offset_(0.0f, 0.0f)
{
}
RenderBackgroundComponent::~RenderBackgroundComponent()
{
}
void RenderBackgroundComponent::accept(ComponentVisitor& visitor)
{
visitor.visitRenderComponent(shared_from_this());
}
void RenderBackgroundComponent::update(float dt)
{
}
void RenderBackgroundComponent::render(const std::vector<void*>& parts)
{
RenderTriangleFan rop = renderer.renderTriangleFan(image_.texture());
b2AABB aabb = camera_->getAABB();
rop.addVertex(aabb.lowerBound.x, aabb.lowerBound.y);
rop.addVertex(aabb.upperBound.x, aabb.lowerBound.y);
rop.addVertex(aabb.upperBound.x, aabb.upperBound.y);
rop.addVertex(aabb.lowerBound.x, aabb.upperBound.y);
aabb.lowerBound += offset_;
aabb.upperBound += offset_;
b2Vec2 aabbSize = aabb.upperBound - aabb.lowerBound;
b2Vec2 lowerBound(aabb.lowerBound.x * parent()->linearVelocity().x,
aabb.lowerBound.y * parent()->linearVelocity().y);
aabb.lowerBound = lowerBound;
aabb.upperBound = aabb.lowerBound + aabbSize;
rop.addTexCoord(aabb.lowerBound.x / imageWidth_, aabb.lowerBound.y / imageHeight_);
rop.addTexCoord(aabb.upperBound.x / imageWidth_, aabb.lowerBound.y / imageHeight_);
rop.addTexCoord(aabb.upperBound.x / imageWidth_, aabb.upperBound.y / imageHeight_);
rop.addTexCoord(aabb.lowerBound.x / imageWidth_, aabb.upperBound.y / imageHeight_);
rop.finish();
}
void RenderBackgroundComponent::onRegister()
{
camera_ = scene()->camera()->findComponent<CameraComponent>();
}
void RenderBackgroundComponent::onUnregister()
{
camera_.reset();
}
}
| {
"content_hash": "d5b6f24d69e43c09cfa71fb57ec6066b",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 93,
"avg_line_length": 30.98611111111111,
"alnum_prop": 0.6270730614074406,
"repo_name": "Sheph/airforce",
"id": "68181917f3f9feb44ee04de8464915ab8b929d1a",
"size": "3604",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "game/RenderBackgroundComponent.cpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1887"
},
{
"name": "C",
"bytes": "3010021"
},
{
"name": "C++",
"bytes": "96165969"
},
{
"name": "CMake",
"bytes": "14598"
},
{
"name": "Java",
"bytes": "5137"
},
{
"name": "Lua",
"bytes": "82834"
},
{
"name": "Makefile",
"bytes": "8636"
},
{
"name": "Objective-C",
"bytes": "30562"
},
{
"name": "OpenEdge ABL",
"bytes": "5588"
},
{
"name": "Perl",
"bytes": "6080"
},
{
"name": "Shell",
"bytes": "3326"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The National Checklist of Taiwan
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "b3f3944894ca14c8bab26db62393747e",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 32,
"avg_line_length": 9.76923076923077,
"alnum_prop": 0.7007874015748031,
"repo_name": "mdoering/backbone",
"id": "ead8e92970b0359b0c10b096d2666a6e1ee50c1a",
"size": "183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Bryophyta/Bryopsida/Fissidentales/Fissidentaceae/Fissidens/Fissidens splchnobryoides/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
namespace frontend\models;
use Yii;
/**
* This is the model class for table "user".
*
* @property integer $id
* @property string $username
* @property string $auth_key
* @property string $password_hash
* @property string $password_reset_token
* @property string $email
* @property integer $status
* @property integer $created_at
* @property integer $updated_at
*/
class User extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'user';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['username', 'auth_key', 'password_hash', 'email', 'created_at', 'updated_at'], 'required'],
[['status', 'created_at', 'updated_at'], 'integer'],
[['username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255],
[['auth_key'], 'string', 'max' => 32],
[['username'], 'unique'],
[['email'], 'unique'],
[['password_reset_token'], 'unique'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'Username',
'auth_key' => 'Auth Key',
'password_hash' => 'Password Hash',
'password_reset_token' => 'Password Reset Token',
'email' => 'Email',
'status' => 'Status',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
}
}
| {
"content_hash": "10732c8e5833f3bbd8e77165825a5675",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 105,
"avg_line_length": 24.841269841269842,
"alnum_prop": 0.5073482428115016,
"repo_name": "PhatTriNguyen/dekbet",
"id": "c55dbad537c43a79496e6a639d7c7c947f7b259b",
"size": "1565",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "frontend/models/User.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "290"
},
{
"name": "ApacheConf",
"bytes": "466"
},
{
"name": "Batchfile",
"bytes": "1541"
},
{
"name": "CSS",
"bytes": "2711780"
},
{
"name": "CoffeeScript",
"bytes": "83631"
},
{
"name": "HTML",
"bytes": "4682241"
},
{
"name": "JavaScript",
"bytes": "13086417"
},
{
"name": "PHP",
"bytes": "473671"
},
{
"name": "Shell",
"bytes": "444"
}
],
"symlink_target": ""
} |
package io.fabric8.kubernetes.examples.crds;
import io.fabric8.kubernetes.client.CustomResource;
/**
*/
public class Dummy extends CustomResource {
private DummySpec spec;
@Override
public String toString() {
return "Dummy{" +
"apiGroupVersion='" + getApiVersion() + '\'' +
", metadata=" + getMetadata() +
", spec=" + spec +
'}';
}
public DummySpec getSpec() {
return spec;
}
public void setSpec(DummySpec spec) {
this.spec = spec;
}
}
| {
"content_hash": "d03f1e9f6ee4a54e13db0d1a6feac3c2",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 54,
"avg_line_length": 18,
"alnum_prop": 0.6111111111111112,
"repo_name": "KurtStam/kubernetes-client",
"id": "b20764ad66c322f340e0997ccb426f23dcef73d0",
"size": "1109",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/crds/Dummy.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "990"
},
{
"name": "Dockerfile",
"bytes": "4109"
},
{
"name": "Go",
"bytes": "35988"
},
{
"name": "Groovy",
"bytes": "2396"
},
{
"name": "Java",
"bytes": "1878143"
},
{
"name": "Makefile",
"bytes": "957"
},
{
"name": "Shell",
"bytes": "21369"
}
],
"symlink_target": ""
} |
$(function(){
PorGlobals.IMAGES_PATH = "../../Images/";
$("#text").click(function(){
setTimeout('showText()',2000);
});
$("#textinput").click(function(){
setTimeout('showTextInput()',2000);
});
$("#button").click(function(){
setTimeout('showButton()',2000);
});
})
function showText(){
var _target = $("#target");
_target.html("text");
}
function showTextInput(){
var _target = $("#target");
_target.empty();
var _input = $("<input/>");
_input.val("input");
_target.append(_input);
}
function showButton(){
var _target = $("#target");
_target.empty();
var _input = $('<input type="button"/>');
_input.val("button");
_target.append(_input);
} | {
"content_hash": "35b33922651a90b5d945172fe48ab742",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 42,
"avg_line_length": 21.242424242424242,
"alnum_prop": 0.5677603423680456,
"repo_name": "stserp/erp1",
"id": "3bc2836b96c6c86e2444012075bed13fb86d4c63",
"size": "701",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/web/por2/demo/SeleniumDemo/SeleniumDemo.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "44086"
},
{
"name": "CSS",
"bytes": "305836"
},
{
"name": "ColdFusion",
"bytes": "126937"
},
{
"name": "HTML",
"bytes": "490616"
},
{
"name": "Java",
"bytes": "21647120"
},
{
"name": "JavaScript",
"bytes": "6599859"
},
{
"name": "Lasso",
"bytes": "18060"
},
{
"name": "PHP",
"bytes": "41541"
},
{
"name": "Perl",
"bytes": "20182"
},
{
"name": "Perl 6",
"bytes": "21700"
},
{
"name": "Python",
"bytes": "39177"
},
{
"name": "SourcePawn",
"bytes": "111"
},
{
"name": "XSLT",
"bytes": "3404"
}
],
"symlink_target": ""
} |
package sodium;
public class MemoryTest4
{
public static void main(String[] args)
{
new Thread() {
public void run()
{
try {
while (true) {
System.out.println("memory "+Runtime.getRuntime().totalMemory());
Thread.sleep(5000);
}
}
catch (InterruptedException e) {
System.out.println(e.toString());
}
}
}.start();
StreamSink<Integer> et = new StreamSink<Integer>();
StreamSink<Integer> eChange = new StreamSink<Integer>();
Cell<Stream<Integer>> oout = eChange.map(x -> (Stream<Integer>)et).hold((Stream<Integer>)et);
Stream<Integer> out = Cell.switchS(oout);
Listener l = out.listen(tt -> {
System.out.println(tt);
});
int i = 0;
while (i < 1000000000) {
eChange.send(i);
i++;
}
l.unlisten();
}
}
| {
"content_hash": "c0340a05d75b3c1f18c48253ba82cd22",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 101,
"avg_line_length": 29.13888888888889,
"alnum_prop": 0.45853193517635843,
"repo_name": "kevintvh/sodium",
"id": "61675401014cbc2dcbe562fdabf652805b5e9a6e",
"size": "1049",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/tests/java8/sodium/MemoryTest4.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "2180"
},
{
"name": "C#",
"bytes": "109536"
},
{
"name": "C++",
"bytes": "285807"
},
{
"name": "CMake",
"bytes": "1418"
},
{
"name": "Elm",
"bytes": "2183"
},
{
"name": "HTML",
"bytes": "17393"
},
{
"name": "Haskell",
"bytes": "154030"
},
{
"name": "Java",
"bytes": "318284"
},
{
"name": "JavaScript",
"bytes": "2531654"
},
{
"name": "Makefile",
"bytes": "2474"
},
{
"name": "Rust",
"bytes": "4139"
},
{
"name": "Scala",
"bytes": "46505"
},
{
"name": "Shell",
"bytes": "637"
}
],
"symlink_target": ""
} |
CKEDITOR.plugins.setLang( 'specialchar', 'sv', {
euro: 'Eurotecken',
lsquo: 'Enkelt vänster citattecken',
rsquo: 'Enkelt höger citattecken',
ldquo: 'Dubbelt vänster citattecken',
rdquo: 'Dubbelt höger citattecken',
ndash: 'Snedstreck',
mdash: 'Långt tankstreck',
iexcl: 'Inverterad utropstecken',
cent: 'Centtecken',
pound: 'Pundtecken',
curren: 'Valutatecken',
yen: 'Yentecken',
brvbar: 'Brutet lodrätt streck',
sect: 'Paragraftecken',
uml: 'Diaeresis',
copy: 'Upphovsrättstecken',
ordf: 'Feminit ordningstalsindikator',
laquo: 'Vänsterställt dubbelt vinkelcitationstecken',
not: 'Icke-tecken',
reg: 'Registrerad',
macr: 'Macron',
deg: 'Grader',
sup2: 'Upphöjt två',
sup3: 'Upphöjt tre',
acute: 'Akut accent',
micro: 'Mikrotecken',
para: 'Alinea',
middot: 'Centrerad prick',
cedil: 'Cedilj',
sup1: 'Upphöjt en',
ordm: 'Maskulina ordningsändelsen',
raquo: 'Högerställt dubbelt vinkelcitationstecken',
frac14: 'Bråktal - en kvart',
frac12: 'Bråktal - en halv',
frac34: 'Bråktal - tre fjärdedelar',
iquest: 'Inverterat frågetecken',
Agrave: 'Stort A med grav accent',
Aacute: 'Stort A med akutaccent',
Acirc: 'Stort A med circumflex',
Atilde: 'Stort A med tilde',
Auml: 'Stort A med diaresis',
Aring: 'Stort A med ring ovan',
AElig: 'Stort Æ',
Ccedil: 'Stort C med cedilj',
Egrave: 'Stort E med grav accent',
Eacute: 'Stort E med aktuaccent',
Ecirc: 'Stort E med circumflex',
Euml: 'Stort E med diaeresis',
Igrave: 'Stort I med grav accent',
Iacute: 'Stort I med akutaccent',
Icirc: 'Stort I med circumflex',
Iuml: 'Stort I med diaeresis',
ETH: 'Stort Eth',
Ntilde: 'Stort N med tilde',
Ograve: 'Stort O med grav accent',
Oacute: 'Stort O med aktuaccent',
Ocirc: 'Stort O med circumflex',
Otilde: 'Stort O med tilde',
Ouml: 'Stort O med diaeresis',
times: 'Multiplicera',
Oslash: 'Stor Ø',
Ugrave: 'Stort U med grav accent',
Uacute: 'Stort U med akutaccent',
Ucirc: 'Stort U med circumflex',
Uuml: 'Stort U med diaeresis',
Yacute: 'Stort Y med akutaccent',
THORN: 'Stort Thorn',
szlig: 'Litet dubbel-s/Eszett',
agrave: 'Litet a med grav accent',
aacute: 'Litet a med akutaccent',
acirc: 'Litet a med circumflex',
atilde: 'Litet a med tilde',
auml: 'Litet a med diaeresis',
aring: 'Litet a med ring ovan',
aelig: 'Bokstaven æ',
ccedil: 'Litet c med cedilj',
egrave: 'Litet e med grav accent',
eacute: 'Litet e med akutaccent',
ecirc: 'Litet e med circumflex',
euml: 'Litet e med diaeresis',
igrave: 'Litet i med grav accent',
iacute: 'Litet i med akutaccent',
icirc: 'LItet i med circumflex',
iuml: 'Litet i med didaeresis',
eth: 'Litet eth',
ntilde: 'Litet n med tilde',
ograve: 'LItet o med grav accent',
oacute: 'LItet o med akutaccent',
ocirc: 'Litet o med circumflex',
otilde: 'LItet o med tilde',
ouml: 'Litet o med diaeresis',
divide: 'Division',
oslash: 'ø',
ugrave: 'Litet u med grav accent',
uacute: 'Litet u med akutaccent',
ucirc: 'LItet u med circumflex',
uuml: 'Litet u med diaeresis',
yacute: 'Litet y med akutaccent',
thorn: 'Litet thorn',
yuml: 'Litet y med diaeresis',
OElig: 'Stor ligatur av OE',
oelig: 'Liten ligatur av oe',
'372': 'Stort W med circumflex',
'374': 'Stort Y med circumflex',
'373': 'Litet w med circumflex',
'375': 'Litet y med circumflex',
sbquo: 'Enkelt lågt 9-citationstecken',
'8219': 'Enkelt högt bakvänt 9-citationstecken',
bdquo: 'Dubbelt lågt 9-citationstecken',
hellip: 'Horisontellt uteslutningstecken',
trade: 'Varumärke',
'9658': 'Svart högervänd pekare',
bull: 'Listpunkt',
rarr: 'Högerpil',
rArr: 'Dubbel högerpil',
hArr: 'Dubbel vänsterpil',
diams: 'Svart ruter',
asymp: 'Ungefär lika med'
} );
| {
"content_hash": "e55dae867361e2149c619f052ff532f8",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 54,
"avg_line_length": 30.040983606557376,
"alnum_prop": 0.6963165075034107,
"repo_name": "Rudhie/simlab",
"id": "78baac37d1f5c4b8cb067735e2a34800b5937e20",
"size": "3862",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "assets/ckeditor/plugins/specialchar/dialogs/lang/sv.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "364"
},
{
"name": "CSS",
"bytes": "186843"
},
{
"name": "HTML",
"bytes": "427207"
},
{
"name": "JavaScript",
"bytes": "5743945"
},
{
"name": "PHP",
"bytes": "1987763"
}
],
"symlink_target": ""
} |
using System;
using System.Reactive.Linq;
using CookComputing.XmlRpc.Moles;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RosSharp.Master;
using RosSharp.Master.Moles;
namespace RosSharp.Tests.Master
{
[TestClass]
public class MasterClientTest
{
[TestMethod]
[HostType("Moles")]
public void RegisterService_Success()
{
var result = new object[3]
{
StatusCode.Success,
"Registered [/test] as provider of [/myservice]",
1
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginRegisterServiceStringStringStringStringAsyncCallbackObject = (t1, t2, t3, t4, t5, t6, t7) => { t6(null); return null; };
MMasterProxy.AllInstances.EndRegisterServiceIAsyncResult= (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
client.RegisterServiceAsync("/test", "/myservice", new Uri("http://192.168.11.2:11112"), new Uri("http://192.168.11.2:11111")).Wait();
}
[TestMethod]
[HostType("Moles")]
public void RegisterService_ParameterError()
{
var result = new object[3]
{
-1,
"ERROR: parameter [service_api] is not an XMLRPC URI",
0
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginRegisterServiceStringStringStringStringAsyncCallbackObject = (t1, t2, t3, t4, t5, t6, t7) => { t6(null); return null; };
MMasterProxy.AllInstances.EndRegisterServiceIAsyncResult= (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
var ex = AssertEx.Throws<AggregateException>(() => client.RegisterServiceAsync("/test", "/myservice", new Uri("http://localhost"), new Uri("http://localhost")).Wait());
ex.InnerException.Message.Is("ERROR: parameter [service_api] is not an XMLRPC URI");
}
[TestMethod]
[HostType("Moles")]
public void UnregisterService_Success()
{
var result = new object[3]
{
1,
"Unregistered [/test] as provider of [/myservice]",
1
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginUnregisterServiceStringStringStringAsyncCallbackObject = (t1, t2, t3, t4, t5, t6) => { t5(null); return null; };
MMasterProxy.AllInstances.EndUnregisterServiceIAsyncResult = (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
client.UnregisterServiceAsync("/test", "/myservice", new Uri("http://localhost")).Result.Is(1);
}
[TestMethod]
[HostType("Moles")]
public void UnregisterService_NotRegistered()
{
var result = new object[3]
{
1,
"[/test] is not a registered node",
0
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginUnregisterServiceStringStringStringAsyncCallbackObject = (t1, t2, t3, t4, t5, t6) => { t5(null); return null; };
MMasterProxy.AllInstances.EndUnregisterServiceIAsyncResult = (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
client.UnregisterServiceAsync("/test", "/myservice", new Uri("http://localhost")).Result.Is(0);
}
[TestMethod]
[HostType("Moles")]
public void UnregisterService_ParameterError()
{
var result = new object[3]
{
-1,
"ERROR: parameter [service] must be a non-empty string",
0
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginUnregisterServiceStringStringStringAsyncCallbackObject = (t1, t2, t3, t4, t5, t6) => { t5(null); return null; };
MMasterProxy.AllInstances.EndUnregisterServiceIAsyncResult = (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
var ex = AssertEx.Throws<AggregateException>(() => client.UnregisterServiceAsync("/test", "/myservice", new Uri("http://localhost")).Wait());
ex.InnerException.Message.Is("ERROR: parameter [service] must be a non-empty string");
}
[TestMethod]
[HostType("Moles")]
public void RegisterSubscriber_Success()
{
var result = new object[3]
{
1,
"Subscribed to [/topic1]",
new object[0]
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginRegisterSubscriberStringStringStringStringAsyncCallbackObject = (t1, t2, t3, t4, t5, t6, t7) => { t6(null); return null; };
MMasterProxy.AllInstances.EndRegisterSubscriberIAsyncResult = (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
client.RegisterSubscriberAsync("/test", "topic1", "std_msgs/String", new Uri("http://192.168.11.2:11112")).Wait();
}
[TestMethod]
[HostType("Moles")]
public void RegisterSubscriber_ParameterError()
{
var result = new object[3]
{
-1,
"ERROR: parameter [topic_type] is not a valid package resource name",
0
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginRegisterSubscriberStringStringStringStringAsyncCallbackObject = (t1, t2, t3, t4, t5, t6, t7) => { t6(null); return null; };
MMasterProxy.AllInstances.EndRegisterSubscriberIAsyncResult= (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
var ex = AssertEx.Throws<AggregateException>(() => client.RegisterSubscriberAsync("/test", "topic1", "topicType", new Uri("http://192.168.11.2:11112")).Wait());
ex.InnerException.Message.Is("ERROR: parameter [topic_type] is not a valid package resource name");
}
[TestMethod]
[HostType("Moles")]
public void RegisterPublisher_Success()
{
var result = new object[3]
{
1,
"Registered [/test] as publisher of [/topic1]",
new string[1]{"http://192.168.11.2:11112/"}
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginRegisterPublisherStringStringStringStringAsyncCallbackObject = (t1, t2, t3, t4, t5, t6, t7) => { t6(null); return null; };
MMasterProxy.AllInstances.EndRegisterPublisherIAsyncResult = (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
client.RegisterPublisherAsync("/test", "topic1", "std_msgs/String", new Uri("http://192.168.11.2:11113"))
.Result[0].Is(new Uri("http://192.168.11.2:11112/"));
}
[TestMethod]
[HostType("Moles")]
public void LookupNode_Success()
{
var result = new object[3]
{
1,
"node api",
"http://192.168.11.4:59511/"
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginLookupNodeStringStringAsyncCallbackObject = (t1, t2, t3, t4, t5) => { t4(null); return null; };
MMasterProxy.AllInstances.EndLookupNodeIAsyncResult = (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
client.LookupNodeAsync("/test", "/rosout").Result.Is(new Uri("http://192.168.11.4:59511/"));
}
[TestMethod]
[HostType("Moles")]
public void LookupNode_UnknownError()
{
var result = new object[3]
{
-1,
"unknown node [/hogehoge]",
""
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginLookupNodeStringStringAsyncCallbackObject = (t1, t2, t3, t4, t5) => { t4(null); return null; };
MMasterProxy.AllInstances.EndLookupNodeIAsyncResult = (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
var ex = AssertEx.Throws<AggregateException>(() => client.LookupNodeAsync("/test", "/hogehoge").Wait());
ex.InnerException.Message.Is("unknown node [/hogehoge]");
}
[TestMethod]
[HostType("Moles")]
public void LookupNode_ParameterError()
{
var result = new object[3]
{
-1,
"ERROR: parameter [node] must be a non-empty string",
""
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginLookupNodeStringStringAsyncCallbackObject = (t1, t2, t3, t4, t5) => { t4(null); return null; };
MMasterProxy.AllInstances.EndLookupNodeIAsyncResult= (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
var ex = AssertEx.Throws<AggregateException>(() => client.LookupNodeAsync("/test", null).Wait());
ex.InnerException.Message.Is("ERROR: parameter [node] must be a non-empty string");
}
[TestMethod]
[HostType("Moles")]
public void GetSystemState_Success()
{
var result = new object[3]
{
1,
"current system state",
new object[3][][]{
new object[3][]{
new object[2]{
"/chatter",
new string[1]{
"/rosjava_tutorial_pubsub/talker"
}
},
new object[2]{
"/rosout",
new string[2]{
"/rosjava_tutorial_pubsub/listener",
"/rosjava_tutorial_pubsub/talker"
}
},
new object[2]{
"/rosout_agg",
new string[1]{
"/rosout"
}
}
},
new object[2][]{
new object[2]{
"/chatter",
new string[1]{
"/rosjava_tutorial_pubsub/listener"
}
},
new object[2]{
"/rosout",
new string[1]{
"/rosout"
}
}
},
new object[2][]{
new object[2]{
"/rosout/set_logger_level",
new string[1]{
"/rosout"
}
},
new object[2]{
"/rosout/get_loggers",
new string[1]{
"/rosout"
}
}
}
}
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginGetSystemStateStringAsyncCallbackObject = (t1, t2, t3, t4) => { t3(null); return null; };
MMasterProxy.AllInstances.EndGetSystemStateIAsyncResult = (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
var ret = client.GetSystemStateAsync("/test").Result;
ret.Publishers.Count.Is(3);
ret.Subscribers.Count.Is(2);
ret.Services.Count.Is(2);
}
[TestMethod]
[HostType("Moles")]
public void GetSystemState_ParameterError()
{
var result = new object[3]
{
-1,
"caller_id must be a string",
new object[3] {new object[0], new object[0], new object[0]}
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginGetSystemStateStringAsyncCallbackObject = (t1, t2, t3, t4) => { t3(null); return null; };
MMasterProxy.AllInstances.EndGetSystemStateIAsyncResult = (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
var ex = AssertEx.Throws<AggregateException>(() => client.GetSystemStateAsync(null).Wait());
ex.InnerException.Message.Is("caller_id must be a string");
}
[TestMethod]
[HostType("Moles")]
public void GetUri_Success()
{
var result = new object[3]
{
1,
"",
"http://192.168.11.4:11311/"
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginGetUriStringAsyncCallbackObject = (t1, t2, t3, t4) => { t3(null); return null; };
MMasterProxy.AllInstances.EndGetUriIAsyncResult= (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
client.GetUriAsync("/test").Result.Is(new Uri("http://192.168.11.4:11311/"));
}
[TestMethod]
[HostType("Moles")]
public void GetUri_ParameterError()
{
var result = new object[3]
{
-1,
"caller_id must be a string",
""
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginGetUriStringAsyncCallbackObject = (t1, t2, t3, t4) => { t3(null); return null; };
MMasterProxy.AllInstances.EndGetUriIAsyncResult = (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
var ex = AssertEx.Throws<AggregateException>(() => client.GetUriAsync(null).Wait());
ex.InnerException.Message.Is("caller_id must be a string");
}
[TestMethod]
[HostType("Moles")]
public void LookupService_Success()
{
var result = new object[3]
{
1,
"rosrpc URI: [rosrpc://192.168.11.5:37171]",
"rosrpc://192.168.11.5:37171"
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginLookupServiceStringStringAsyncCallbackObject = (t1, t2, t3, t4, t5) => { t4(null); return null; };
MMasterProxy.AllInstances.EndLookupServiceIAsyncResult = (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
client.LookupServiceAsync("/test", "/service_test").Result.Is(new Uri("rosrpc://192.168.11.5:37171"));
}
[TestMethod]
[HostType("Moles")]
public void LookupService_NoProvider()
{
var result = new object[3]
{
-1,
"no provider",
""
};
MXmlRpcClientProtocol.AllInstances.UrlSetString = (t1, t2) => { };
MMasterProxy.AllInstances.BeginLookupServiceStringStringAsyncCallbackObject = (t1, t2, t3, t4, t5) => { t4(null); return null; };
MMasterProxy.AllInstances.EndLookupServiceIAsyncResult = (t1, t2) => result;
var client = new MasterClient(new Uri("http://localhost"));
var ex = AssertEx.Throws<AggregateException>(() => client.LookupServiceAsync("/test", "/service_test").Wait());
ex.InnerException.Message.Is("no provider");
}
}
}
| {
"content_hash": "5659e33835fdffee5e6e034332fc030e",
"timestamp": "",
"source": "github",
"line_count": 417,
"max_line_length": 180,
"avg_line_length": 41.20863309352518,
"alnum_prop": 0.5088454376163873,
"repo_name": "zoetrope/RosSharp",
"id": "47be84e4d6698e2023ad0a4a8b765c523a0873f1",
"size": "17186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Test/RosSharp.UnitTests/Master/MasterClientTest.cs",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "9917"
},
{
"name": "C#",
"bytes": "722378"
},
{
"name": "F#",
"bytes": "46626"
},
{
"name": "Makefile",
"bytes": "5581"
},
{
"name": "Python",
"bytes": "7734"
}
],
"symlink_target": ""
} |
package org.freud.analysed.javasource;
import org.freud.core.Creator;
import org.freud.core.iterator.FlattenedCollection;
public final class ClassDeclarationToMethodDeclarationsCreator implements Creator<ClassDeclaration, Iterable<MethodDeclaration>> {
@Override
public Iterable<MethodDeclaration> create(final ClassDeclaration source) {
return new FlattenedCollection<MethodDeclaration>(
source.getMethodDeclarationListByNameMap().values());
}
}
| {
"content_hash": "84ba76a661c9b0ba928ffe876d487592",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 130,
"avg_line_length": 34.785714285714285,
"alnum_prop": 0.784394250513347,
"repo_name": "LMAX-Exchange/freud",
"id": "2f5e96f0fb354c1de5c29e314c28085d8023e4a9",
"size": "1069",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java-source/src/main/java/org/freud/analysed/javasource/ClassDeclarationToMethodDeclarationsCreator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6955"
},
{
"name": "GAP",
"bytes": "44765"
},
{
"name": "Groovy",
"bytes": "130128"
},
{
"name": "Java",
"bytes": "2008358"
}
],
"symlink_target": ""
} |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Finkit.ManicTime.Server.SampleClient.Ui.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| {
"content_hash": "f217d4cbc91cb30df0fda939e29553bb",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 151,
"avg_line_length": 42.07692307692308,
"alnum_prop": 0.5886654478976234,
"repo_name": "manictime/manictime-server-sampleclient",
"id": "b50d62e47c72842d192915f2547c144e3c552615",
"size": "1096",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/SampleClient.Gui/Properties/Settings.Designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "78220"
}
],
"symlink_target": ""
} |
package bitbucketcloud
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"github.com/pkg/errors"
"github.com/rancher/norman/httperror"
"github.com/rancher/rancher/pkg/pipeline/remote/model"
"github.com/rancher/rancher/pkg/pipeline/utils"
"github.com/rancher/rancher/pkg/ref"
"github.com/rancher/rancher/pkg/settings"
v3 "github.com/rancher/types/apis/project.cattle.io/v3"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
)
const (
apiEndpoint = "https://api.bitbucket.org/2.0"
authURL = "https://bitbucket.org/site/oauth2/authorize"
tokenURL = "https://bitbucket.org/site/oauth2/access_token"
maxPerPage = "100"
cloneUserName = "x-token-auth"
)
type client struct {
ClientID string
ClientSecret string
RedirectURL string
}
func New(config *v3.BitbucketCloudPipelineConfig) (model.Remote, error) {
if config == nil {
return nil, errors.New("empty gitlab config")
}
glClient := &client{
ClientID: config.ClientID,
ClientSecret: config.ClientSecret,
RedirectURL: config.RedirectURL,
}
return glClient, nil
}
func (c *client) Type() string {
return model.BitbucketCloudType
}
func (c *client) Login(code string) (*v3.SourceCodeCredential, error) {
oauthConfig := &oauth2.Config{
ClientID: c.ClientID,
ClientSecret: c.ClientSecret,
RedirectURL: c.RedirectURL,
Endpoint: oauth2.Endpoint{
AuthURL: authURL,
TokenURL: tokenURL,
},
}
token, err := oauthConfig.Exchange(oauth2.NoContext, code)
if err != nil {
return nil, err
} else if token.TokenType != "bearer" || token.AccessToken == "" {
return nil, fmt.Errorf("Fail to get accesstoken with oauth config")
}
user, err := c.getUser(token.AccessToken)
if err != nil {
return nil, err
}
cred := convertUser(user)
cred.Spec.AccessToken = token.AccessToken
cred.Spec.RefreshToken = token.RefreshToken
cred.Spec.Expiry = token.Expiry.Format(time.RFC3339)
return cred, nil
}
func (c *client) Repos(account *v3.SourceCodeCredential) ([]v3.SourceCodeRepository, error) {
if account == nil {
return nil, fmt.Errorf("empty account")
}
nexturl := apiEndpoint + "/repositories?role=admin"
var repos []Repository
for nexturl != "" {
b, err := getFromBitbucket(nexturl, account.Spec.AccessToken)
if err != nil {
return nil, err
}
var pageRepos PaginatedRepositories
if err := json.Unmarshal(b, &pageRepos); err != nil {
return nil, err
}
nexturl = pageRepos.Next
repos = append(repos, pageRepos.Values...)
}
return convertRepos(repos), nil
}
func (c *client) CreateHook(pipeline *v3.Pipeline, accessToken string) (string, error) {
user, repo, err := getUserRepoFromURL(pipeline.Spec.RepositoryURL)
if err != nil {
return "", err
}
hookURL := fmt.Sprintf("%s/hooks?pipelineId=%s", settings.ServerURL.Get(), ref.Ref(pipeline))
hook := Hook{
Description: "Webhook created by Rancher Pipeline",
URL: hookURL,
Active: true,
SkipCertVerification: true,
Events: []string{
"repo:push",
"pullrequest:updated",
"pullrequest:created",
},
}
url := fmt.Sprintf("%s/repositories/%s/%s/hooks", apiEndpoint, user, repo)
b, err := json.Marshal(hook)
if err != nil {
return "", err
}
reader := bytes.NewReader(b)
resp, err := doRequestToBitbucket(http.MethodPost, url, accessToken, nil, reader)
if err != nil {
return "", err
}
err = json.Unmarshal(resp, &hook)
if err != nil {
return "", err
}
return hook.UUID, nil
}
func (c *client) DeleteHook(pipeline *v3.Pipeline, accessToken string) error {
user, repo, err := getUserRepoFromURL(pipeline.Spec.RepositoryURL)
if err != nil {
return err
}
hook, err := c.getHook(pipeline, accessToken)
if err != nil {
return err
}
if hook != nil {
url := fmt.Sprintf("%s/repositories/%s/%s/hooks/%v", apiEndpoint, user, repo, hook.UUID)
_, err := doRequestToBitbucket(http.MethodDelete, url, accessToken, nil, nil)
if err != nil {
return err
}
}
return nil
}
func (c *client) getHook(pipeline *v3.Pipeline, accessToken string) (*Hook, error) {
user, repo, err := getUserRepoFromURL(pipeline.Spec.RepositoryURL)
if err != nil {
return nil, err
}
var hooks PaginatedHooks
var result *Hook
url := fmt.Sprintf("%s/repositories/%s/%s/hooks", apiEndpoint, user, repo)
b, err := getFromBitbucket(url, accessToken)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &hooks); err != nil {
return nil, err
}
for _, hook := range hooks.Values {
if strings.HasSuffix(hook.URL, fmt.Sprintf("hooks?pipelineId=%s", ref.Ref(pipeline))) {
result = &hook
break
}
}
return result, nil
}
func (c *client) getFileFromRepo(filename string, owner string, repo string, branch string, accessToken string) ([]byte, error) {
url := fmt.Sprintf("%s/repositories/%s/%s/src/%s/%s", apiEndpoint, owner, repo, branch, filename)
return getFromBitbucket(url, accessToken)
}
func (c *client) GetPipelineFileInRepo(repoURL string, branch string, accessToken string) ([]byte, error) {
owner, repo, err := getUserRepoFromURL(repoURL)
if err != nil {
return nil, err
}
content, err := c.getFileFromRepo(utils.PipelineFileYaml, owner, repo, branch, accessToken)
if err != nil {
//look for both suffix
content, err = c.getFileFromRepo(utils.PipelineFileYml, owner, repo, branch, accessToken)
}
if err != nil {
logrus.Debugf("error GetPipelineFileInRepo - %v", err)
return nil, nil
}
return content, nil
}
func (c *client) SetPipelineFileInRepo(repoURL string, branch string, accessToken string, content []byte) error {
owner, repo, err := getUserRepoFromURL(repoURL)
if err != nil {
return err
}
currentContent, err := c.getFileFromRepo(utils.PipelineFileYml, owner, repo, branch, accessToken)
currentFileName := utils.PipelineFileYml
if err != nil {
if httpErr, ok := err.(*httperror.APIError); !ok || httpErr.Code.Status != http.StatusNotFound {
return err
}
//look for both suffix
currentContent, err = c.getFileFromRepo(utils.PipelineFileYaml, owner, repo, branch, accessToken)
if err != nil {
if httpErr, ok := err.(*httperror.APIError); !ok || httpErr.Code.Status != http.StatusNotFound {
return err
}
} else {
currentFileName = utils.PipelineFileYaml
}
}
apiurl := fmt.Sprintf("%s/repositories/%s/%s/src", apiEndpoint, owner, repo)
message := "Create .rancher-pipeline.yml file"
if currentContent != nil {
//update pipeline file
message = fmt.Sprintf("Update %s file", currentFileName)
}
data := url.Values{}
data.Set("message", message)
data.Set("branch", branch)
data.Set(currentFileName, string(content))
data.Encode()
reader := strings.NewReader(data.Encode())
header := map[string]string{"Content-Type": "application/x-www-form-urlencoded"}
_, err = doRequestToBitbucket(http.MethodPost, apiurl, accessToken, header, reader)
return err
}
func (c *client) GetBranches(repoURL string, accessToken string) ([]string, error) {
owner, repo, err := getUserRepoFromURL(repoURL)
if err != nil {
return nil, err
}
nexturl := fmt.Sprintf("%s/repositories/%s/%s/refs/branches", apiEndpoint, owner, repo)
var result []string
for nexturl != "" {
b, err := getFromBitbucket(nexturl, accessToken)
if err != nil {
return nil, err
}
var pageBranches PaginatedBranches
if err := json.Unmarshal(b, &pageBranches); err != nil {
return nil, err
}
for _, branch := range pageBranches.Values {
result = append(result, branch.Name)
}
nexturl = pageBranches.Next
}
return result, nil
}
func (c *client) GetHeadInfo(repoURL string, branch string, accessToken string) (*model.BuildInfo, error) {
owner, repo, err := getUserRepoFromURL(repoURL)
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s/repositories/%s/%s/refs/branches/%s", apiEndpoint, owner, repo, branch)
b, err := getFromBitbucket(url, accessToken)
if err != nil {
return nil, err
}
var branchObj Ref
if err := json.Unmarshal(b, &branchObj); err != nil {
return nil, err
}
info := &model.BuildInfo{}
info.Commit = branchObj.Target.Hash
info.Ref = branch
info.Branch = branch
info.Message = branchObj.Target.Message
info.HTMLLink = branchObj.Links.HTML.Href
info.AvatarURL = branchObj.Target.Author.User.Links.Avatar.Href
info.Author = branchObj.Target.Author.User.UserName
return info, nil
}
func convertUser(bitbucketUser *User) *v3.SourceCodeCredential {
if bitbucketUser == nil {
return nil
}
cred := &v3.SourceCodeCredential{}
cred.Spec.SourceCodeType = model.BitbucketCloudType
cred.Spec.AvatarURL = bitbucketUser.Links.Avatar.Href
cred.Spec.HTMLURL = bitbucketUser.Links.HTML.Href
cred.Spec.LoginName = bitbucketUser.UserName
cred.Spec.GitLoginName = cloneUserName
cred.Spec.DisplayName = bitbucketUser.DisplayName
return cred
}
func (c *client) getUser(accessToken string) (*User, error) {
url := apiEndpoint + "/user"
b, err := getFromBitbucket(url, accessToken)
if err != nil {
return nil, err
}
user := &User{}
if err := json.Unmarshal(b, user); err != nil {
return nil, err
}
return user, nil
}
func convertRepos(repos []Repository) []v3.SourceCodeRepository {
result := []v3.SourceCodeRepository{}
for _, repo := range repos {
if repo.Scm != "git" {
//skip mercurial repos
continue
}
r := v3.SourceCodeRepository{}
for _, link := range repo.Links.Clone {
if link.Name == "https" {
u, _ := url.Parse(link.Href)
if u != nil {
u.User = nil
r.Spec.URL = u.String()
}
break
}
}
r.Spec.DefaultBranch = repo.MainBranch.Name
r.Spec.Permissions.Admin = true
r.Spec.Permissions.Pull = true
r.Spec.Permissions.Push = true
result = append(result, r)
}
return result
}
func (c *client) Refresh(cred *v3.SourceCodeCredential) (bool, error) {
if cred == nil {
return false, errors.New("cannot refresh empty credentials")
}
config := &oauth2.Config{
ClientID: c.ClientID,
ClientSecret: c.ClientSecret,
RedirectURL: c.RedirectURL,
Endpoint: oauth2.Endpoint{
AuthURL: authURL,
TokenURL: tokenURL,
},
}
source := config.TokenSource(
oauth2.NoContext, &oauth2.Token{RefreshToken: cred.Spec.RefreshToken})
token, err := source.Token()
if err != nil || len(token.AccessToken) == 0 {
return false, err
}
cred.Spec.AccessToken = token.AccessToken
cred.Spec.RefreshToken = token.RefreshToken
cred.Spec.Expiry = token.Expiry.Format(time.RFC3339)
return true, nil
}
func getFromBitbucket(url string, accessToken string) ([]byte, error) {
return doRequestToBitbucket(http.MethodGet, url, accessToken, nil, nil)
}
func doRequestToBitbucket(method string, url string, accessToken string, header map[string]string, body io.Reader) ([]byte, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
client := &http.Client{
Timeout: 30 * time.Second,
}
q := req.URL.Query()
//set to max 100 per page to reduce query time
if method == http.MethodGet {
q.Set("pagelen", maxPerPage)
}
if accessToken != "" {
q.Set("access_token", accessToken)
}
req.URL.RawQuery = q.Encode()
req.Header.Add("Cache-control", "no-cache")
for k, v := range header {
req.Header.Set(k, v)
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Check the status code
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest {
var body bytes.Buffer
io.Copy(&body, resp.Body)
return nil, httperror.NewAPIErrorLong(resp.StatusCode, "", body.String())
}
r, err := ioutil.ReadAll(resp.Body)
return r, err
}
func getUserRepoFromURL(repoURL string) (string, string, error) {
reg := regexp.MustCompile(".*/([^/]*?)/([^/]*?).git")
match := reg.FindStringSubmatch(repoURL)
if len(match) != 3 {
return "", "", fmt.Errorf("error getting user/repo from gitrepoUrl:%v", repoURL)
}
return match[1], match[2], nil
}
| {
"content_hash": "221f246f6243966cb0cce9d1b9cd51b3",
"timestamp": "",
"source": "github",
"line_count": 442,
"max_line_length": 132,
"avg_line_length": 26.963800904977376,
"alnum_prop": 0.6904681993623091,
"repo_name": "cjellick/rancher",
"id": "63f8f6314e3e59c905fc80fda8a76602386c72c3",
"size": "11918",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/pipeline/remote/bitbucketcloud/client.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "728"
},
{
"name": "Dockerfile",
"bytes": "5649"
},
{
"name": "Go",
"bytes": "3099024"
},
{
"name": "Groovy",
"bytes": "56136"
},
{
"name": "Makefile",
"bytes": "411"
},
{
"name": "PowerShell",
"bytes": "78774"
},
{
"name": "Python",
"bytes": "728617"
},
{
"name": "Shell",
"bytes": "40881"
},
{
"name": "Smarty",
"bytes": "823"
}
],
"symlink_target": ""
} |
namespace Dike.Core.Specifications
{
using System;
using System.Linq.Expressions;
/// <summary>
/// Represents the combined specification which indicates that either of the given specification should be satisfied by the given object.
/// </summary>
/// <typeparam name="T">The type of the object to which the specification is applied.</typeparam>
public class OrSpecification<T>
: CompositeSpecification<T>
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="OrSpecification{T}"/> class.
/// </summary>
/// <param name="left">The left side of the specification.</param>
/// <param name="right">The right side of the specification.</param>
public OrSpecification(ISpecification<T> left, ISpecification<T> right)
: base(left, right)
{
}
#endregion Constructors
#region Methods
/// <summary>
/// Gets the LINQ expression which represents the current specification.
/// </summary>
/// <returns>The LINQ expression.</returns>
public override Expression<Func<T, bool>> ToExpression()
=> Left.ToExpression().Or(Right.ToExpression());
#endregion Methods
}
} | {
"content_hash": "87f8597d6d28ae730065d77e92456a23",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 141,
"avg_line_length": 34.05263157894737,
"alnum_prop": 0.6259659969088099,
"repo_name": "IngbertPalm/project.dike",
"id": "8ba783e206d0e856263c58442440241171f9f495",
"size": "1296",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Dike.Core/Specifications/OrSpecification.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "3735688"
},
{
"name": "CSS",
"bytes": "260971"
},
{
"name": "JavaScript",
"bytes": "7937"
},
{
"name": "TypeScript",
"bytes": "1181"
}
],
"symlink_target": ""
} |
//
// BaseViewController.m
// app
//
// Created by 吕浩轩 on 16/5/9.
// Copyright © 2016年 上海先致信息股份有限公司. All rights reserved.
//
#import "BaseViewController.h"
@interface BaseViewController ()
@end
@implementation BaseViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
-(void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
/**
* 收起键盘
*/
[self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
| {
"content_hash": "b50e0f1c7da26b24428bea595f1fcef0",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 102,
"avg_line_length": 21.533333333333335,
"alnum_prop": 0.7058823529411765,
"repo_name": "HaoXuan1988/ZhiYu",
"id": "bb704c3b49c32607599d37c351b7eff7090e215e",
"size": "1010",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ZhiYu/BaseClass/BaseViewController.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "944"
},
{
"name": "Objective-C",
"bytes": "338954"
},
{
"name": "Ruby",
"bytes": "556"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
NUB Generator [autonym]
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "840e4a81e965f458aad50402178ba660",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 23,
"avg_line_length": 9.076923076923077,
"alnum_prop": 0.6779661016949152,
"repo_name": "mdoering/backbone",
"id": "2101a5c4ffb8fc42cabd7652169988e7753c085e",
"size": "178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Apocynaceae/Ambelania/Ambelania tenuiflora/Ambelania tenuiflora tenuiflora/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
Begonian 36:83. 1969
#### Original name
null
### Remarks
null | {
"content_hash": "c51f198131913002f42e64db3e423f5f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 10.923076923076923,
"alnum_prop": 0.7112676056338029,
"repo_name": "mdoering/backbone",
"id": "2bca116d88008e3ff600bf59b49f28b5624137a0",
"size": "190",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Cucurbitales/Begoniaceae/Begonia/Begonia viscida/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>bignums: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.10.1 / bignums - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
bignums
<small>
8.6.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-05-26 23:20:04 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-26 23:20:04 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.10.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.07.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.07.1 Official release 4.07.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "pierre.letouzey@inria.fr"
homepage: "https://github.com/coq/bignums"
dev-repo: "git+https://github.com/coq/bignums.git"
bug-reports: "https://github.com/coq/bignums/issues"
authors: [
"Laurent Théry"
"Benjamin Grégoire"
"Arnaud Spiwack"
"Evgeny Makarov"
"Pierre Letouzey"
]
license: "LGPL-2.1-only"
build: [
[make "-j%{jobs}%" {ocaml:version >= "4.06"}]
]
install: [
[make "install"]
]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
]
tags: [
"keyword:integer numbers"
"keyword:rational numbers"
"keyword:arithmetic"
"keyword:arbitrary-precision"
"category:Miscellaneous/Coq Extensions"
"category:Mathematics/Arithmetic and Number Theory/Number theory"
"category:Mathematics/Arithmetic and Number Theory/Rational numbers"
"date:2017-06-15"
"logpath:Bignums"
]
synopsis: "Bignums, the Coq library of arbitrary large numbers"
description:
"Provides BigN, BigZ, BigQ that used to be part of Coq standard library < 8.7."
url {
src: "https://github.com/coq/bignums/archive/v8.6.0.tar.gz"
checksum: "md5=8200a64b50404a7f952e5ddd8047f646"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-bignums.8.6.0 coq.8.10.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.10.1).
The following dependencies couldn't be met:
- coq-bignums -> coq < 8.7~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-bignums.8.6.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "85af217503589a60c858fd576041d6dc",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 159,
"avg_line_length": 38.87709497206704,
"alnum_prop": 0.5434688892082196,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "78957758fc91bde4a2db9a5cdfba9f6de869d5b3",
"size": "6986",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.07.1-2.0.6/released/8.10.1/bignums/8.6.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package com.weather.android;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.weather.android.fragment.ChooseAreaFragment;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment fragment = Fragment.instantiate(this, ChooseAreaFragment.class.getName());
getSupportFragmentManager().beginTransaction().replace(R.id.fragment, fragment, null).commit();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
if (sp.getString("weather", null) != null) {
Intent intent = new Intent(this, WeatherActivity.class);
startActivity(intent);
finish();
}
}
} | {
"content_hash": "18487b92e47b8674c5b14d8e4a2a1727",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 103,
"avg_line_length": 37.592592592592595,
"alnum_prop": 0.7359605911330049,
"repo_name": "JohnZp/coolweather",
"id": "b81ab350c24406a3855dd3933c02134f1c56af0f",
"size": "1015",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/weather/android/MainActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "35456"
}
],
"symlink_target": ""
} |
@erase /s lang.inc > nul
@echo lang fix ru >lang.inc
fasm MSquare.asm MSquare
pause | {
"content_hash": "1bd0b5c82297da0731fee13897e81dad",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 27,
"avg_line_length": 20.75,
"alnum_prop": 0.7469879518072289,
"repo_name": "devlato/kolibrios-llvm",
"id": "37d9796d6b7b7febac5d1483d580d7eaa84d70f4",
"size": "83",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "programs/games/MSquare/trunk/build_ru.bat",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "15418643"
},
{
"name": "C",
"bytes": "126021466"
},
{
"name": "C++",
"bytes": "11476220"
},
{
"name": "CSS",
"bytes": "1230161"
},
{
"name": "JavaScript",
"bytes": "687"
},
{
"name": "Logos",
"bytes": "905"
},
{
"name": "Lua",
"bytes": "2055"
},
{
"name": "Objective-C",
"bytes": "482461"
},
{
"name": "Pascal",
"bytes": "6692"
},
{
"name": "Perl",
"bytes": "317449"
},
{
"name": "Puppet",
"bytes": "161697"
},
{
"name": "Python",
"bytes": "1036533"
},
{
"name": "Shell",
"bytes": "448869"
},
{
"name": "Verilog",
"bytes": "2829"
},
{
"name": "Visual Basic",
"bytes": "4346"
},
{
"name": "XSLT",
"bytes": "4325"
}
],
"symlink_target": ""
} |
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#include "utypeinfo.h" // for 'typeid' to work
#include "unicode/measunit.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/uenum.h"
#include "ustrenum.h"
#include "cstring.h"
#include "uassert.h"
U_NAMESPACE_BEGIN
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(MeasureUnit)
// All code between the "Start generated code" comment and
// the "End generated code" comment is auto generated code
// and must not be edited manually. For instructions on how to correctly
// update this code, refer to:
// http://site.icu-project.org/design/formatting/measureformat/updating-measure-unit
//
// Start generated code
static const int32_t gOffsets[] = {
0,
2,
7,
16,
20,
24,
285,
295,
306,
310,
316,
320,
340,
341,
352,
355,
361,
366,
370,
374,
399
};
static const int32_t gIndexes[] = {
0,
2,
7,
16,
20,
24,
24,
34,
45,
49,
55,
59,
79,
80,
91,
94,
100,
105,
109,
113,
138
};
// Must be sorted alphabetically.
static const char * const gTypes[] = {
"acceleration",
"angle",
"area",
"concentr",
"consumption",
"currency",
"digital",
"duration",
"electric",
"energy",
"frequency",
"length",
"light",
"mass",
"none",
"power",
"pressure",
"speed",
"temperature",
"volume"
};
// Must be grouped by type and sorted alphabetically within each type.
static const char * const gSubTypes[] = {
"g-force",
"meter-per-second-squared",
"arc-minute",
"arc-second",
"degree",
"radian",
"revolution",
"acre",
"hectare",
"square-centimeter",
"square-foot",
"square-inch",
"square-kilometer",
"square-meter",
"square-mile",
"square-yard",
"karat",
"milligram-per-deciliter",
"millimole-per-liter",
"part-per-million",
"liter-per-100kilometers",
"liter-per-kilometer",
"mile-per-gallon",
"mile-per-gallon-imperial",
"ADP",
"AED",
"AFA",
"AFN",
"ALL",
"AMD",
"ANG",
"AOA",
"AON",
"AOR",
"ARA",
"ARP",
"ARS",
"ATS",
"AUD",
"AWG",
"AYM",
"AZM",
"AZN",
"BAD",
"BAM",
"BBD",
"BDT",
"BEC",
"BEF",
"BEL",
"BGL",
"BGN",
"BHD",
"BIF",
"BMD",
"BND",
"BOB",
"BOV",
"BRC",
"BRE",
"BRL",
"BRN",
"BRR",
"BSD",
"BTN",
"BWP",
"BYB",
"BYN",
"BYR",
"BZD",
"CAD",
"CDF",
"CHC",
"CHE",
"CHF",
"CHW",
"CLF",
"CLP",
"CNY",
"COP",
"COU",
"CRC",
"CSD",
"CSK",
"CUC",
"CUP",
"CVE",
"CYP",
"CZK",
"DDM",
"DEM",
"DJF",
"DKK",
"DOP",
"DZD",
"ECS",
"ECV",
"EEK",
"EGP",
"ERN",
"ESA",
"ESB",
"ESP",
"ETB",
"EUR",
"FIM",
"FJD",
"FKP",
"FRF",
"GBP",
"GEK",
"GEL",
"GHC",
"GHP",
"GHS",
"GIP",
"GMD",
"GNF",
"GQE",
"GRD",
"GTQ",
"GWP",
"GYD",
"HKD",
"HNL",
"HRD",
"HRK",
"HTG",
"HUF",
"IDR",
"IEP",
"ILS",
"INR",
"IQD",
"IRR",
"ISK",
"ITL",
"JMD",
"JOD",
"JPY",
"KES",
"KGS",
"KHR",
"KMF",
"KPW",
"KRW",
"KWD",
"KYD",
"KZT",
"LAK",
"LBP",
"LKR",
"LRD",
"LSL",
"LTL",
"LTT",
"LUC",
"LUF",
"LUL",
"LVL",
"LVR",
"LYD",
"MAD",
"MDL",
"MGA",
"MGF",
"MKD",
"MLF",
"MMK",
"MNT",
"MOP",
"MRO",
"MTL",
"MUR",
"MVR",
"MWK",
"MXN",
"MXV",
"MYR",
"MZM",
"MZN",
"NAD",
"NGN",
"NIO",
"NLG",
"NOK",
"NPR",
"NZD",
"OMR",
"PAB",
"PEI",
"PEN",
"PES",
"PGK",
"PHP",
"PKR",
"PLN",
"PLZ",
"PTE",
"PYG",
"QAR",
"ROL",
"RON",
"RSD",
"RUB",
"RUR",
"RWF",
"SAR",
"SBD",
"SCR",
"SDD",
"SDG",
"SEK",
"SGD",
"SHP",
"SIT",
"SKK",
"SLL",
"SOS",
"SRD",
"SRG",
"SSP",
"STD",
"SVC",
"SYP",
"SZL",
"THB",
"TJR",
"TJS",
"TMM",
"TMT",
"TND",
"TOP",
"TPE",
"TRL",
"TRY",
"TTD",
"TWD",
"TZS",
"UAH",
"UAK",
"UGX",
"USD",
"USN",
"USS",
"UYI",
"UYU",
"UZS",
"VEB",
"VEF",
"VND",
"VUV",
"WST",
"XAF",
"XAG",
"XAU",
"XBA",
"XBB",
"XBC",
"XBD",
"XCD",
"XDR",
"XEU",
"XOF",
"XPD",
"XPF",
"XPT",
"XSU",
"XTS",
"XUA",
"XXX",
"YDD",
"YER",
"YUM",
"YUN",
"ZAL",
"ZAR",
"ZMK",
"ZMW",
"ZRN",
"ZRZ",
"ZWD",
"ZWL",
"ZWN",
"ZWR",
"bit",
"byte",
"gigabit",
"gigabyte",
"kilobit",
"kilobyte",
"megabit",
"megabyte",
"terabit",
"terabyte",
"century",
"day",
"hour",
"microsecond",
"millisecond",
"minute",
"month",
"nanosecond",
"second",
"week",
"year",
"ampere",
"milliampere",
"ohm",
"volt",
"calorie",
"foodcalorie",
"joule",
"kilocalorie",
"kilojoule",
"kilowatt-hour",
"gigahertz",
"hertz",
"kilohertz",
"megahertz",
"astronomical-unit",
"centimeter",
"decimeter",
"fathom",
"foot",
"furlong",
"inch",
"kilometer",
"light-year",
"meter",
"micrometer",
"mile",
"mile-scandinavian",
"millimeter",
"nanometer",
"nautical-mile",
"parsec",
"picometer",
"point",
"yard",
"lux",
"carat",
"gram",
"kilogram",
"metric-ton",
"microgram",
"milligram",
"ounce",
"ounce-troy",
"pound",
"stone",
"ton",
"base",
"percent",
"permille",
"gigawatt",
"horsepower",
"kilowatt",
"megawatt",
"milliwatt",
"watt",
"hectopascal",
"inch-hg",
"millibar",
"millimeter-of-mercury",
"pound-per-square-inch",
"kilometer-per-hour",
"knot",
"meter-per-second",
"mile-per-hour",
"celsius",
"fahrenheit",
"generic",
"kelvin",
"acre-foot",
"bushel",
"centiliter",
"cubic-centimeter",
"cubic-foot",
"cubic-inch",
"cubic-kilometer",
"cubic-meter",
"cubic-mile",
"cubic-yard",
"cup",
"cup-metric",
"deciliter",
"fluid-ounce",
"gallon",
"gallon-imperial",
"hectoliter",
"liter",
"megaliter",
"milliliter",
"pint",
"pint-metric",
"quart",
"tablespoon",
"teaspoon"
};
// Must be sorted by first value and then second value.
static int32_t unitPerUnitToSingleUnit[][4] = {
{327, 297, 17, 0},
{329, 303, 17, 2},
{331, 297, 17, 3},
{331, 388, 4, 2},
{331, 389, 4, 3},
{346, 386, 3, 1},
{349, 11, 16, 4},
{391, 327, 4, 1}
};
MeasureUnit *MeasureUnit::createGForce(UErrorCode &status) {
return MeasureUnit::create(0, 0, status);
}
MeasureUnit *MeasureUnit::createMeterPerSecondSquared(UErrorCode &status) {
return MeasureUnit::create(0, 1, status);
}
MeasureUnit *MeasureUnit::createArcMinute(UErrorCode &status) {
return MeasureUnit::create(1, 0, status);
}
MeasureUnit *MeasureUnit::createArcSecond(UErrorCode &status) {
return MeasureUnit::create(1, 1, status);
}
MeasureUnit *MeasureUnit::createDegree(UErrorCode &status) {
return MeasureUnit::create(1, 2, status);
}
MeasureUnit *MeasureUnit::createRadian(UErrorCode &status) {
return MeasureUnit::create(1, 3, status);
}
MeasureUnit *MeasureUnit::createRevolutionAngle(UErrorCode &status) {
return MeasureUnit::create(1, 4, status);
}
MeasureUnit *MeasureUnit::createAcre(UErrorCode &status) {
return MeasureUnit::create(2, 0, status);
}
MeasureUnit *MeasureUnit::createHectare(UErrorCode &status) {
return MeasureUnit::create(2, 1, status);
}
MeasureUnit *MeasureUnit::createSquareCentimeter(UErrorCode &status) {
return MeasureUnit::create(2, 2, status);
}
MeasureUnit *MeasureUnit::createSquareFoot(UErrorCode &status) {
return MeasureUnit::create(2, 3, status);
}
MeasureUnit *MeasureUnit::createSquareInch(UErrorCode &status) {
return MeasureUnit::create(2, 4, status);
}
MeasureUnit *MeasureUnit::createSquareKilometer(UErrorCode &status) {
return MeasureUnit::create(2, 5, status);
}
MeasureUnit *MeasureUnit::createSquareMeter(UErrorCode &status) {
return MeasureUnit::create(2, 6, status);
}
MeasureUnit *MeasureUnit::createSquareMile(UErrorCode &status) {
return MeasureUnit::create(2, 7, status);
}
MeasureUnit *MeasureUnit::createSquareYard(UErrorCode &status) {
return MeasureUnit::create(2, 8, status);
}
MeasureUnit *MeasureUnit::createKarat(UErrorCode &status) {
return MeasureUnit::create(3, 0, status);
}
MeasureUnit *MeasureUnit::createMilligramPerDeciliter(UErrorCode &status) {
return MeasureUnit::create(3, 1, status);
}
MeasureUnit *MeasureUnit::createMillimolePerLiter(UErrorCode &status) {
return MeasureUnit::create(3, 2, status);
}
MeasureUnit *MeasureUnit::createPartPerMillion(UErrorCode &status) {
return MeasureUnit::create(3, 3, status);
}
MeasureUnit *MeasureUnit::createLiterPer100Kilometers(UErrorCode &status) {
return MeasureUnit::create(4, 0, status);
}
MeasureUnit *MeasureUnit::createLiterPerKilometer(UErrorCode &status) {
return MeasureUnit::create(4, 1, status);
}
MeasureUnit *MeasureUnit::createMilePerGallon(UErrorCode &status) {
return MeasureUnit::create(4, 2, status);
}
MeasureUnit *MeasureUnit::createMilePerGallonImperial(UErrorCode &status) {
return MeasureUnit::create(4, 3, status);
}
MeasureUnit *MeasureUnit::createBit(UErrorCode &status) {
return MeasureUnit::create(6, 0, status);
}
MeasureUnit *MeasureUnit::createByte(UErrorCode &status) {
return MeasureUnit::create(6, 1, status);
}
MeasureUnit *MeasureUnit::createGigabit(UErrorCode &status) {
return MeasureUnit::create(6, 2, status);
}
MeasureUnit *MeasureUnit::createGigabyte(UErrorCode &status) {
return MeasureUnit::create(6, 3, status);
}
MeasureUnit *MeasureUnit::createKilobit(UErrorCode &status) {
return MeasureUnit::create(6, 4, status);
}
MeasureUnit *MeasureUnit::createKilobyte(UErrorCode &status) {
return MeasureUnit::create(6, 5, status);
}
MeasureUnit *MeasureUnit::createMegabit(UErrorCode &status) {
return MeasureUnit::create(6, 6, status);
}
MeasureUnit *MeasureUnit::createMegabyte(UErrorCode &status) {
return MeasureUnit::create(6, 7, status);
}
MeasureUnit *MeasureUnit::createTerabit(UErrorCode &status) {
return MeasureUnit::create(6, 8, status);
}
MeasureUnit *MeasureUnit::createTerabyte(UErrorCode &status) {
return MeasureUnit::create(6, 9, status);
}
MeasureUnit *MeasureUnit::createCentury(UErrorCode &status) {
return MeasureUnit::create(7, 0, status);
}
MeasureUnit *MeasureUnit::createDay(UErrorCode &status) {
return MeasureUnit::create(7, 1, status);
}
MeasureUnit *MeasureUnit::createHour(UErrorCode &status) {
return MeasureUnit::create(7, 2, status);
}
MeasureUnit *MeasureUnit::createMicrosecond(UErrorCode &status) {
return MeasureUnit::create(7, 3, status);
}
MeasureUnit *MeasureUnit::createMillisecond(UErrorCode &status) {
return MeasureUnit::create(7, 4, status);
}
MeasureUnit *MeasureUnit::createMinute(UErrorCode &status) {
return MeasureUnit::create(7, 5, status);
}
MeasureUnit *MeasureUnit::createMonth(UErrorCode &status) {
return MeasureUnit::create(7, 6, status);
}
MeasureUnit *MeasureUnit::createNanosecond(UErrorCode &status) {
return MeasureUnit::create(7, 7, status);
}
MeasureUnit *MeasureUnit::createSecond(UErrorCode &status) {
return MeasureUnit::create(7, 8, status);
}
MeasureUnit *MeasureUnit::createWeek(UErrorCode &status) {
return MeasureUnit::create(7, 9, status);
}
MeasureUnit *MeasureUnit::createYear(UErrorCode &status) {
return MeasureUnit::create(7, 10, status);
}
MeasureUnit *MeasureUnit::createAmpere(UErrorCode &status) {
return MeasureUnit::create(8, 0, status);
}
MeasureUnit *MeasureUnit::createMilliampere(UErrorCode &status) {
return MeasureUnit::create(8, 1, status);
}
MeasureUnit *MeasureUnit::createOhm(UErrorCode &status) {
return MeasureUnit::create(8, 2, status);
}
MeasureUnit *MeasureUnit::createVolt(UErrorCode &status) {
return MeasureUnit::create(8, 3, status);
}
MeasureUnit *MeasureUnit::createCalorie(UErrorCode &status) {
return MeasureUnit::create(9, 0, status);
}
MeasureUnit *MeasureUnit::createFoodcalorie(UErrorCode &status) {
return MeasureUnit::create(9, 1, status);
}
MeasureUnit *MeasureUnit::createJoule(UErrorCode &status) {
return MeasureUnit::create(9, 2, status);
}
MeasureUnit *MeasureUnit::createKilocalorie(UErrorCode &status) {
return MeasureUnit::create(9, 3, status);
}
MeasureUnit *MeasureUnit::createKilojoule(UErrorCode &status) {
return MeasureUnit::create(9, 4, status);
}
MeasureUnit *MeasureUnit::createKilowattHour(UErrorCode &status) {
return MeasureUnit::create(9, 5, status);
}
MeasureUnit *MeasureUnit::createGigahertz(UErrorCode &status) {
return MeasureUnit::create(10, 0, status);
}
MeasureUnit *MeasureUnit::createHertz(UErrorCode &status) {
return MeasureUnit::create(10, 1, status);
}
MeasureUnit *MeasureUnit::createKilohertz(UErrorCode &status) {
return MeasureUnit::create(10, 2, status);
}
MeasureUnit *MeasureUnit::createMegahertz(UErrorCode &status) {
return MeasureUnit::create(10, 3, status);
}
MeasureUnit *MeasureUnit::createAstronomicalUnit(UErrorCode &status) {
return MeasureUnit::create(11, 0, status);
}
MeasureUnit *MeasureUnit::createCentimeter(UErrorCode &status) {
return MeasureUnit::create(11, 1, status);
}
MeasureUnit *MeasureUnit::createDecimeter(UErrorCode &status) {
return MeasureUnit::create(11, 2, status);
}
MeasureUnit *MeasureUnit::createFathom(UErrorCode &status) {
return MeasureUnit::create(11, 3, status);
}
MeasureUnit *MeasureUnit::createFoot(UErrorCode &status) {
return MeasureUnit::create(11, 4, status);
}
MeasureUnit *MeasureUnit::createFurlong(UErrorCode &status) {
return MeasureUnit::create(11, 5, status);
}
MeasureUnit *MeasureUnit::createInch(UErrorCode &status) {
return MeasureUnit::create(11, 6, status);
}
MeasureUnit *MeasureUnit::createKilometer(UErrorCode &status) {
return MeasureUnit::create(11, 7, status);
}
MeasureUnit *MeasureUnit::createLightYear(UErrorCode &status) {
return MeasureUnit::create(11, 8, status);
}
MeasureUnit *MeasureUnit::createMeter(UErrorCode &status) {
return MeasureUnit::create(11, 9, status);
}
MeasureUnit *MeasureUnit::createMicrometer(UErrorCode &status) {
return MeasureUnit::create(11, 10, status);
}
MeasureUnit *MeasureUnit::createMile(UErrorCode &status) {
return MeasureUnit::create(11, 11, status);
}
MeasureUnit *MeasureUnit::createMileScandinavian(UErrorCode &status) {
return MeasureUnit::create(11, 12, status);
}
MeasureUnit *MeasureUnit::createMillimeter(UErrorCode &status) {
return MeasureUnit::create(11, 13, status);
}
MeasureUnit *MeasureUnit::createNanometer(UErrorCode &status) {
return MeasureUnit::create(11, 14, status);
}
MeasureUnit *MeasureUnit::createNauticalMile(UErrorCode &status) {
return MeasureUnit::create(11, 15, status);
}
MeasureUnit *MeasureUnit::createParsec(UErrorCode &status) {
return MeasureUnit::create(11, 16, status);
}
MeasureUnit *MeasureUnit::createPicometer(UErrorCode &status) {
return MeasureUnit::create(11, 17, status);
}
MeasureUnit *MeasureUnit::createPoint(UErrorCode &status) {
return MeasureUnit::create(11, 18, status);
}
MeasureUnit *MeasureUnit::createYard(UErrorCode &status) {
return MeasureUnit::create(11, 19, status);
}
MeasureUnit *MeasureUnit::createLux(UErrorCode &status) {
return MeasureUnit::create(12, 0, status);
}
MeasureUnit *MeasureUnit::createCarat(UErrorCode &status) {
return MeasureUnit::create(13, 0, status);
}
MeasureUnit *MeasureUnit::createGram(UErrorCode &status) {
return MeasureUnit::create(13, 1, status);
}
MeasureUnit *MeasureUnit::createKilogram(UErrorCode &status) {
return MeasureUnit::create(13, 2, status);
}
MeasureUnit *MeasureUnit::createMetricTon(UErrorCode &status) {
return MeasureUnit::create(13, 3, status);
}
MeasureUnit *MeasureUnit::createMicrogram(UErrorCode &status) {
return MeasureUnit::create(13, 4, status);
}
MeasureUnit *MeasureUnit::createMilligram(UErrorCode &status) {
return MeasureUnit::create(13, 5, status);
}
MeasureUnit *MeasureUnit::createOunce(UErrorCode &status) {
return MeasureUnit::create(13, 6, status);
}
MeasureUnit *MeasureUnit::createOunceTroy(UErrorCode &status) {
return MeasureUnit::create(13, 7, status);
}
MeasureUnit *MeasureUnit::createPound(UErrorCode &status) {
return MeasureUnit::create(13, 8, status);
}
MeasureUnit *MeasureUnit::createStone(UErrorCode &status) {
return MeasureUnit::create(13, 9, status);
}
MeasureUnit *MeasureUnit::createTon(UErrorCode &status) {
return MeasureUnit::create(13, 10, status);
}
MeasureUnit *MeasureUnit::createGigawatt(UErrorCode &status) {
return MeasureUnit::create(15, 0, status);
}
MeasureUnit *MeasureUnit::createHorsepower(UErrorCode &status) {
return MeasureUnit::create(15, 1, status);
}
MeasureUnit *MeasureUnit::createKilowatt(UErrorCode &status) {
return MeasureUnit::create(15, 2, status);
}
MeasureUnit *MeasureUnit::createMegawatt(UErrorCode &status) {
return MeasureUnit::create(15, 3, status);
}
MeasureUnit *MeasureUnit::createMilliwatt(UErrorCode &status) {
return MeasureUnit::create(15, 4, status);
}
MeasureUnit *MeasureUnit::createWatt(UErrorCode &status) {
return MeasureUnit::create(15, 5, status);
}
MeasureUnit *MeasureUnit::createHectopascal(UErrorCode &status) {
return MeasureUnit::create(16, 0, status);
}
MeasureUnit *MeasureUnit::createInchHg(UErrorCode &status) {
return MeasureUnit::create(16, 1, status);
}
MeasureUnit *MeasureUnit::createMillibar(UErrorCode &status) {
return MeasureUnit::create(16, 2, status);
}
MeasureUnit *MeasureUnit::createMillimeterOfMercury(UErrorCode &status) {
return MeasureUnit::create(16, 3, status);
}
MeasureUnit *MeasureUnit::createPoundPerSquareInch(UErrorCode &status) {
return MeasureUnit::create(16, 4, status);
}
MeasureUnit *MeasureUnit::createKilometerPerHour(UErrorCode &status) {
return MeasureUnit::create(17, 0, status);
}
MeasureUnit *MeasureUnit::createKnot(UErrorCode &status) {
return MeasureUnit::create(17, 1, status);
}
MeasureUnit *MeasureUnit::createMeterPerSecond(UErrorCode &status) {
return MeasureUnit::create(17, 2, status);
}
MeasureUnit *MeasureUnit::createMilePerHour(UErrorCode &status) {
return MeasureUnit::create(17, 3, status);
}
MeasureUnit *MeasureUnit::createCelsius(UErrorCode &status) {
return MeasureUnit::create(18, 0, status);
}
MeasureUnit *MeasureUnit::createFahrenheit(UErrorCode &status) {
return MeasureUnit::create(18, 1, status);
}
MeasureUnit *MeasureUnit::createGenericTemperature(UErrorCode &status) {
return MeasureUnit::create(18, 2, status);
}
MeasureUnit *MeasureUnit::createKelvin(UErrorCode &status) {
return MeasureUnit::create(18, 3, status);
}
MeasureUnit *MeasureUnit::createAcreFoot(UErrorCode &status) {
return MeasureUnit::create(19, 0, status);
}
MeasureUnit *MeasureUnit::createBushel(UErrorCode &status) {
return MeasureUnit::create(19, 1, status);
}
MeasureUnit *MeasureUnit::createCentiliter(UErrorCode &status) {
return MeasureUnit::create(19, 2, status);
}
MeasureUnit *MeasureUnit::createCubicCentimeter(UErrorCode &status) {
return MeasureUnit::create(19, 3, status);
}
MeasureUnit *MeasureUnit::createCubicFoot(UErrorCode &status) {
return MeasureUnit::create(19, 4, status);
}
MeasureUnit *MeasureUnit::createCubicInch(UErrorCode &status) {
return MeasureUnit::create(19, 5, status);
}
MeasureUnit *MeasureUnit::createCubicKilometer(UErrorCode &status) {
return MeasureUnit::create(19, 6, status);
}
MeasureUnit *MeasureUnit::createCubicMeter(UErrorCode &status) {
return MeasureUnit::create(19, 7, status);
}
MeasureUnit *MeasureUnit::createCubicMile(UErrorCode &status) {
return MeasureUnit::create(19, 8, status);
}
MeasureUnit *MeasureUnit::createCubicYard(UErrorCode &status) {
return MeasureUnit::create(19, 9, status);
}
MeasureUnit *MeasureUnit::createCup(UErrorCode &status) {
return MeasureUnit::create(19, 10, status);
}
MeasureUnit *MeasureUnit::createCupMetric(UErrorCode &status) {
return MeasureUnit::create(19, 11, status);
}
MeasureUnit *MeasureUnit::createDeciliter(UErrorCode &status) {
return MeasureUnit::create(19, 12, status);
}
MeasureUnit *MeasureUnit::createFluidOunce(UErrorCode &status) {
return MeasureUnit::create(19, 13, status);
}
MeasureUnit *MeasureUnit::createGallon(UErrorCode &status) {
return MeasureUnit::create(19, 14, status);
}
MeasureUnit *MeasureUnit::createGallonImperial(UErrorCode &status) {
return MeasureUnit::create(19, 15, status);
}
MeasureUnit *MeasureUnit::createHectoliter(UErrorCode &status) {
return MeasureUnit::create(19, 16, status);
}
MeasureUnit *MeasureUnit::createLiter(UErrorCode &status) {
return MeasureUnit::create(19, 17, status);
}
MeasureUnit *MeasureUnit::createMegaliter(UErrorCode &status) {
return MeasureUnit::create(19, 18, status);
}
MeasureUnit *MeasureUnit::createMilliliter(UErrorCode &status) {
return MeasureUnit::create(19, 19, status);
}
MeasureUnit *MeasureUnit::createPint(UErrorCode &status) {
return MeasureUnit::create(19, 20, status);
}
MeasureUnit *MeasureUnit::createPintMetric(UErrorCode &status) {
return MeasureUnit::create(19, 21, status);
}
MeasureUnit *MeasureUnit::createQuart(UErrorCode &status) {
return MeasureUnit::create(19, 22, status);
}
MeasureUnit *MeasureUnit::createTablespoon(UErrorCode &status) {
return MeasureUnit::create(19, 23, status);
}
MeasureUnit *MeasureUnit::createTeaspoon(UErrorCode &status) {
return MeasureUnit::create(19, 24, status);
}
// End generated code
static int32_t binarySearch(
const char * const * array, int32_t start, int32_t end, const char * key) {
while (start < end) {
int32_t mid = (start + end) / 2;
int32_t cmp = uprv_strcmp(array[mid], key);
if (cmp < 0) {
start = mid + 1;
continue;
}
if (cmp == 0) {
return mid;
}
end = mid;
}
return -1;
}
MeasureUnit::MeasureUnit() {
fCurrency[0] = 0;
initNoUnit("base");
}
MeasureUnit::MeasureUnit(const MeasureUnit &other)
: fTypeId(other.fTypeId), fSubTypeId(other.fSubTypeId) {
uprv_strcpy(fCurrency, other.fCurrency);
}
MeasureUnit &MeasureUnit::operator=(const MeasureUnit &other) {
if (this == &other) {
return *this;
}
fTypeId = other.fTypeId;
fSubTypeId = other.fSubTypeId;
uprv_strcpy(fCurrency, other.fCurrency);
return *this;
}
UObject *MeasureUnit::clone() const {
return new MeasureUnit(*this);
}
MeasureUnit::~MeasureUnit() {
}
const char *MeasureUnit::getType() const {
return gTypes[fTypeId];
}
const char *MeasureUnit::getSubtype() const {
return fCurrency[0] == 0 ? gSubTypes[getOffset()] : fCurrency;
}
UBool MeasureUnit::operator==(const UObject& other) const {
if (this == &other) { // Same object, equal
return TRUE;
}
if (typeid(*this) != typeid(other)) { // Different types, not equal
return FALSE;
}
const MeasureUnit &rhs = static_cast<const MeasureUnit&>(other);
return (
fTypeId == rhs.fTypeId
&& fSubTypeId == rhs.fSubTypeId
&& uprv_strcmp(fCurrency, rhs.fCurrency) == 0);
}
int32_t MeasureUnit::getIndex() const {
return gIndexes[fTypeId] + fSubTypeId;
}
int32_t MeasureUnit::getAvailable(
MeasureUnit *dest,
int32_t destCapacity,
UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) {
return 0;
}
if (destCapacity < UPRV_LENGTHOF(gSubTypes)) {
errorCode = U_BUFFER_OVERFLOW_ERROR;
return UPRV_LENGTHOF(gSubTypes);
}
int32_t idx = 0;
for (int32_t typeIdx = 0; typeIdx < UPRV_LENGTHOF(gTypes); ++typeIdx) {
int32_t len = gOffsets[typeIdx + 1] - gOffsets[typeIdx];
for (int32_t subTypeIdx = 0; subTypeIdx < len; ++subTypeIdx) {
dest[idx].setTo(typeIdx, subTypeIdx);
++idx;
}
}
U_ASSERT(idx == UPRV_LENGTHOF(gSubTypes));
return UPRV_LENGTHOF(gSubTypes);
}
int32_t MeasureUnit::getAvailable(
const char *type,
MeasureUnit *dest,
int32_t destCapacity,
UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) {
return 0;
}
int32_t typeIdx = binarySearch(gTypes, 0, UPRV_LENGTHOF(gTypes), type);
if (typeIdx == -1) {
return 0;
}
int32_t len = gOffsets[typeIdx + 1] - gOffsets[typeIdx];
if (destCapacity < len) {
errorCode = U_BUFFER_OVERFLOW_ERROR;
return len;
}
for (int subTypeIdx = 0; subTypeIdx < len; ++subTypeIdx) {
dest[subTypeIdx].setTo(typeIdx, subTypeIdx);
}
return len;
}
StringEnumeration* MeasureUnit::getAvailableTypes(UErrorCode &errorCode) {
UEnumeration *uenum = uenum_openCharStringsEnumeration(
gTypes, UPRV_LENGTHOF(gTypes), &errorCode);
if (U_FAILURE(errorCode)) {
uenum_close(uenum);
return NULL;
}
StringEnumeration *result = new UStringEnumeration(uenum);
if (result == NULL) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
uenum_close(uenum);
return NULL;
}
return result;
}
int32_t MeasureUnit::getIndexCount() {
return gIndexes[UPRV_LENGTHOF(gIndexes) - 1];
}
int32_t MeasureUnit::internalGetIndexForTypeAndSubtype(const char *type, const char *subtype) {
int32_t t = binarySearch(gTypes, 0, UPRV_LENGTHOF(gTypes), type);
if (t < 0) {
return t;
}
int32_t st = binarySearch(gSubTypes, gOffsets[t], gOffsets[t + 1], subtype);
if (st < 0) {
return st;
}
return gIndexes[t] + st - gOffsets[t];
}
MeasureUnit MeasureUnit::resolveUnitPerUnit(
const MeasureUnit &unit, const MeasureUnit &perUnit, bool* isResolved) {
int32_t unitOffset = unit.getOffset();
int32_t perUnitOffset = perUnit.getOffset();
// binary search for (unitOffset, perUnitOffset)
int32_t start = 0;
int32_t end = UPRV_LENGTHOF(unitPerUnitToSingleUnit);
while (start < end) {
int32_t mid = (start + end) / 2;
int32_t *midRow = unitPerUnitToSingleUnit[mid];
if (unitOffset < midRow[0]) {
end = mid;
} else if (unitOffset > midRow[0]) {
start = mid + 1;
} else if (perUnitOffset < midRow[1]) {
end = mid;
} else if (perUnitOffset > midRow[1]) {
start = mid + 1;
} else {
// We found a resolution for our unit / per-unit combo
// return it.
*isResolved = true;
return MeasureUnit(midRow[2], midRow[3]);
}
}
*isResolved = false;
return MeasureUnit();
}
MeasureUnit *MeasureUnit::create(int typeId, int subTypeId, UErrorCode &status) {
if (U_FAILURE(status)) {
return NULL;
}
MeasureUnit *result = new MeasureUnit(typeId, subTypeId);
if (result == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
}
return result;
}
void MeasureUnit::initTime(const char *timeId) {
int32_t result = binarySearch(gTypes, 0, UPRV_LENGTHOF(gTypes), "duration");
U_ASSERT(result != -1);
fTypeId = result;
result = binarySearch(gSubTypes, gOffsets[fTypeId], gOffsets[fTypeId + 1], timeId);
U_ASSERT(result != -1);
fSubTypeId = result - gOffsets[fTypeId];
}
void MeasureUnit::initCurrency(const char *isoCurrency) {
int32_t result = binarySearch(gTypes, 0, UPRV_LENGTHOF(gTypes), "currency");
U_ASSERT(result != -1);
fTypeId = result;
result = binarySearch(
gSubTypes, gOffsets[fTypeId], gOffsets[fTypeId + 1], isoCurrency);
if (result != -1) {
fSubTypeId = result - gOffsets[fTypeId];
} else {
uprv_strncpy(fCurrency, isoCurrency, UPRV_LENGTHOF(fCurrency));
fCurrency[3] = 0;
}
}
void MeasureUnit::initNoUnit(const char *subtype) {
int32_t result = binarySearch(gTypes, 0, UPRV_LENGTHOF(gTypes), "none");
U_ASSERT(result != -1);
fTypeId = result;
result = binarySearch(gSubTypes, gOffsets[fTypeId], gOffsets[fTypeId + 1], subtype);
U_ASSERT(result != -1);
fSubTypeId = result - gOffsets[fTypeId];
}
void MeasureUnit::setTo(int32_t typeId, int32_t subTypeId) {
fTypeId = typeId;
fSubTypeId = subTypeId;
fCurrency[0] = 0;
}
int32_t MeasureUnit::getOffset() const {
return gOffsets[fTypeId] + fSubTypeId;
}
U_NAMESPACE_END
#endif /* !UNCONFIG_NO_FORMATTING */
| {
"content_hash": "3ff1ea6bde6aa60b3a47c1f104145b3b",
"timestamp": "",
"source": "github",
"line_count": 1291,
"max_line_length": 95,
"avg_line_length": 22.779240898528272,
"alnum_prop": 0.6363914581066377,
"repo_name": "MTASZTAKI/ApertusVR",
"id": "e21afcba029e04fe555c2f56f72e7636f5bda89d",
"size": "29796",
"binary": false,
"copies": "1",
"ref": "refs/heads/0.9",
"path": "plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/deps/icu-small/source/i18n/measunit.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "7599"
},
{
"name": "C++",
"bytes": "1207412"
},
{
"name": "CMake",
"bytes": "165066"
},
{
"name": "CSS",
"bytes": "1816"
},
{
"name": "GLSL",
"bytes": "223507"
},
{
"name": "HLSL",
"bytes": "141879"
},
{
"name": "HTML",
"bytes": "34827"
},
{
"name": "JavaScript",
"bytes": "140550"
},
{
"name": "Python",
"bytes": "1370"
}
],
"symlink_target": ""
} |
package jtransc.bug;
public class JTranscBugWithStaticInits {
static public void main(String[] args) {
new A();
}
static class A extends B {
public A() {
System.out.println(this.test1());
System.out.println(super.test1());
}
@Override
public String test1() {
return "A";
}
}
static class B extends C {
public B() {
}
public String test1() {
return "B";
}
}
static class C {
public String test1() {
return "C";
}
}
}
| {
"content_hash": "3829a214c659e943fa8b64febbf1d606",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 41,
"avg_line_length": 13.794117647058824,
"alnum_prop": 0.605543710021322,
"repo_name": "jtransc/jtransc",
"id": "38e33cdfd08adb7163db24381511f2c57ef6cf82",
"size": "469",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "jtransc-gen-common-tests/src/jtransc/bug/JTranscBugWithStaticInits.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "19957"
},
{
"name": "AngelScript",
"bytes": "6459"
},
{
"name": "Batchfile",
"bytes": "745"
},
{
"name": "C#",
"bytes": "15716"
},
{
"name": "C++",
"bytes": "195369"
},
{
"name": "CMake",
"bytes": "1698"
},
{
"name": "D",
"bytes": "15707"
},
{
"name": "Dart",
"bytes": "45335"
},
{
"name": "HTML",
"bytes": "23453"
},
{
"name": "Haxe",
"bytes": "81907"
},
{
"name": "Java",
"bytes": "7367530"
},
{
"name": "JavaScript",
"bytes": "43492"
},
{
"name": "Kotlin",
"bytes": "1166258"
},
{
"name": "PHP",
"bytes": "32490"
},
{
"name": "Shell",
"bytes": "254"
}
],
"symlink_target": ""
} |
package filter;
import model.Product;
import java.util.List;
import java.util.function.*;
import static java.util.stream.Collectors.toList;
public class ProductFilter {
public List<Product> filter(List<Product> allProducts) {
return allProducts.stream()
.filter(product -> product.getPrice() < 10L)
.filter(product -> product.getWeight() < 100L)
.collect(toList());
}
public static <X> List<X> filterWithPredicate(
List<X> allProducts,
Predicate<X> pricePredicate,
Predicate<X> weightPredicate
) {
return allProducts.stream()
.filter(pricePredicate)
.filter(weightPredicate)
.collect(toList());
}
public static <X> List<X> filterWithVarargPredicates(
List<X> allProducts,
Predicate<X>... predicates
) {
for (Predicate<X> predicate : predicates) {
allProducts = allProducts.stream()
.filter(predicate)
.collect(toList());
}
return allProducts;
}
public static <X, Y> void filterWithFunction(
List<X> allProducts,
Predicate<X> pricePredicate,
Predicate<X> weightPredicate,
Function<X, Y> idMapper,
Consumer<Y> productConsumer
) {
allProducts.stream()
.filter(pricePredicate)
.filter(weightPredicate)
.map(idMapper)
.forEach(productConsumer::accept);
}
}
| {
"content_hash": "2f4ed17087582e92c9e15239b7974a08",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 60,
"avg_line_length": 27.2,
"alnum_prop": 0.5922459893048129,
"repo_name": "jadekler/git-misc-2",
"id": "6d877e69f70df6befe3c47df04a2e60e2f20d6d5",
"size": "1496",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java-filter-chaining/src/main/java/filter/ProductFilter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "35"
},
{
"name": "HTML",
"bytes": "889"
},
{
"name": "Java",
"bytes": "46887"
},
{
"name": "JavaScript",
"bytes": "5039"
},
{
"name": "Python",
"bytes": "254"
},
{
"name": "Ruby",
"bytes": "2843"
},
{
"name": "Shell",
"bytes": "1770"
}
],
"symlink_target": ""
} |
<div id="empty-layout"
ui-view></div> | {
"content_hash": "99cd68eb0345dbf1b71bbc8c659a45db",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 22,
"avg_line_length": 22.5,
"alnum_prop": 0.5555555555555556,
"repo_name": "GinesOrtiz/angularES6seed",
"id": "a49a936f47e80efd0ba23aaed8edac57286b8b16",
"size": "45",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/layouts/empty/empty.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4194"
},
{
"name": "HTML",
"bytes": "1708"
},
{
"name": "JavaScript",
"bytes": "19038"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN""http://www.w3.org/TR/REC-html40/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc on Fri Aug 22 03:44:08 EDT 2003 -->
<TITLE>
PageTag (Apache Struts API Documentation)
</TITLE>
<META NAME="keywords" CONTENT="org.apache.struts.taglib.bean.PageTag,PageTag class">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
</HEAD>
<SCRIPT>
function asd()
{
parent.document.title="PageTag (Apache Struts API Documentation)";
}
</SCRIPT>
<BODY BGCOLOR="white" onload="asd();">
<!-- ========== START OF NAVBAR ========== -->
<A NAME="navbar_top"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/PageTag.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/apache/struts/taglib/bean/MessageTag.html"><B>PREV CLASS</B></A>
<A HREF="../../../../../org/apache/struts/taglib/bean/PageTei.html"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="PageTag.html" TARGET="_top"><B>NO FRAMES</B></A>
<SCRIPT>
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html" TARGET=""><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html" TARGET=""><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<!-- =========== END OF NAVBAR =========== -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.apache.struts.taglib.bean</FONT>
<BR>
Class PageTag</H2>
<PRE>
java.lang.Object
|
+--javax.servlet.jsp.tagext.TagSupport
|
+--<B>org.apache.struts.taglib.bean.PageTag</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD>java.io.Serializable, javax.servlet.jsp.tagext.Tag</DD>
</DL>
<HR>
<DL>
<DT>public class <B>PageTag</B><DT>extends javax.servlet.jsp.tagext.TagSupport</DL>
<P>
Define a scripting variable that exposes the requested page context
item as a scripting variable and a page scope bean.
<P>
<P>
<DL>
<DT><B>Version:</B></DT>
<DD>$Revision: 1.1 $ $Date: 2003-08-22 17:34:00 +0900 (é, 22 8æ 2003) $</DD>
<DT><B>Author:</B></DT>
<DD>Craig R. McClanahan</DD>
<DT><B>See Also:</B><DD><A HREF="../../../../../serialized-form.html" TARGET="org.apache.struts.taglib.bean.PageTag">Serialized Form</A></DL>
<HR>
<P>
<!-- ======== NESTED CLASS SUMMARY ======== -->
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_summary"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Field Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/struts/taglib/bean/PageTag.html#id">id</A></B></CODE>
<BR>
The name of the scripting variable that will be exposed as a page
scope attribute.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected static <A HREF="../../../../../org/apache/struts/util/MessageResources.html">MessageResources</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/struts/taglib/bean/PageTag.html#messages">messages</A></B></CODE>
<BR>
The message resources for this package.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/struts/taglib/bean/PageTag.html#property">property</A></B></CODE>
<BR>
The name of the page context property to be retrieved.</TD>
</TR>
</TABLE>
<A NAME="fields_inherited_from_class_javax.servlet.jsp.tagext.TagSupport"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TD><B>Fields inherited from class javax.servlet.jsp.tagext.TagSupport</B></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>pageContext</CODE></TD>
</TR>
</TABLE>
<A NAME="fields_inherited_from_class_javax.servlet.jsp.tagext.Tag"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TD><B>Fields inherited from interface javax.servlet.jsp.tagext.Tag</B></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>EVAL_BODY_INCLUDE, EVAL_PAGE, SKIP_BODY, SKIP_PAGE</CODE></TD>
</TR>
</TABLE>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../org/apache/struts/taglib/bean/PageTag.html#PageTag()">PageTag</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Method Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/struts/taglib/bean/PageTag.html#doStartTag()">doStartTag</A></B>()</CODE>
<BR>
Retrieve the required configuration object and expose it as a
scripting variable.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/struts/taglib/bean/PageTag.html#getId()">getId</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/struts/taglib/bean/PageTag.html#getProperty()">getProperty</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/struts/taglib/bean/PageTag.html#release()">release</A></B>()</CODE>
<BR>
Release all allocated resources.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/struts/taglib/bean/PageTag.html#setId(java.lang.String)">setId</A></B>(java.lang.String id)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/struts/taglib/bean/PageTag.html#setProperty(java.lang.String)">setProperty</A></B>(java.lang.String property)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_javax.servlet.jsp.tagext.TagSupport"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TD><B>Methods inherited from class javax.servlet.jsp.tagext.TagSupport</B></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>doEndTag, findAncestorWithClass, getParent, getValue, getValues, removeValue, setPageContext, setParent, setValue</CODE></TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TD><B>Methods inherited from class java.lang.Object</B></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ FIELD DETAIL =========== -->
<A NAME="field_detail"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=1><FONT SIZE="+2">
<B>Field Detail</B></FONT></TD>
</TR>
</TABLE>
<A NAME="id"><!-- --></A><H3>
id</H3>
<PRE>
protected java.lang.String <B>id</B></PRE>
<DL>
<DD>The name of the scripting variable that will be exposed as a page
scope attribute.
<P>
<DL>
</DL>
</DL>
<HR>
<A NAME="messages"><!-- --></A><H3>
messages</H3>
<PRE>
protected static <A HREF="../../../../../org/apache/struts/util/MessageResources.html">MessageResources</A> <B>messages</B></PRE>
<DL>
<DD>The message resources for this package.
<P>
<DL>
</DL>
</DL>
<HR>
<A NAME="property"><!-- --></A><H3>
property</H3>
<PRE>
protected java.lang.String <B>property</B></PRE>
<DL>
<DD>The name of the page context property to be retrieved.
<P>
<DL>
</DL>
</DL>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=1><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TD>
</TR>
</TABLE>
<A NAME="PageTag()"><!-- --></A><H3>
PageTag</H3>
<PRE>
public <B>PageTag</B>()</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=1><FONT SIZE="+2">
<B>Method Detail</B></FONT></TD>
</TR>
</TABLE>
<A NAME="getId()"><!-- --></A><H3>
getId</H3>
<PRE>
public java.lang.String <B>getId</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE>getId</CODE> in class <CODE>javax.servlet.jsp.tagext.TagSupport</CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="setId(java.lang.String)"><!-- --></A><H3>
setId</H3>
<PRE>
public void <B>setId</B>(java.lang.String id)</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE>setId</CODE> in class <CODE>javax.servlet.jsp.tagext.TagSupport</CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getProperty()"><!-- --></A><H3>
getProperty</H3>
<PRE>
public java.lang.String <B>getProperty</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="setProperty(java.lang.String)"><!-- --></A><H3>
setProperty</H3>
<PRE>
public void <B>setProperty</B>(java.lang.String property)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="doStartTag()"><!-- --></A><H3>
doStartTag</H3>
<PRE>
public int <B>doStartTag</B>()
throws javax.servlet.jsp.JspException</PRE>
<DL>
<DD>Retrieve the required configuration object and expose it as a
scripting variable.
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE>doStartTag</CODE> in interface <CODE>javax.servlet.jsp.tagext.Tag</CODE><DT><B>Overrides:</B><DD><CODE>doStartTag</CODE> in class <CODE>javax.servlet.jsp.tagext.TagSupport</CODE></DL>
</DD>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>javax.servlet.jsp.JspException</CODE> - if a JSP exception has occurred</DL>
</DD>
</DL>
<HR>
<A NAME="release()"><!-- --></A><H3>
release</H3>
<PRE>
public void <B>release</B>()</PRE>
<DL>
<DD>Release all allocated resources.
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE>release</CODE> in interface <CODE>javax.servlet.jsp.tagext.Tag</CODE><DT><B>Overrides:</B><DD><CODE>release</CODE> in class <CODE>javax.servlet.jsp.tagext.TagSupport</CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ========== START OF NAVBAR ========== -->
<A NAME="navbar_bottom"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/PageTag.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/apache/struts/taglib/bean/MessageTag.html"><B>PREV CLASS</B></A>
<A HREF="../../../../../org/apache/struts/taglib/bean/PageTei.html"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="PageTag.html" TARGET="_top"><B>NO FRAMES</B></A>
<SCRIPT>
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html" TARGET=""><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html" TARGET=""><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<!-- =========== END OF NAVBAR =========== -->
<HR>
Copyright © 2000-2003 - Apache Software Foundation
</BODY>
</HTML>
| {
"content_hash": "7889bdb2c6c4f61ef8038ac1575a9798",
"timestamp": "",
"source": "github",
"line_count": 476,
"max_line_length": 217,
"avg_line_length": 36.37394957983193,
"alnum_prop": 0.6264872357629664,
"repo_name": "codelibs/cl-struts",
"id": "544fbc98874851c5992bbb4eb3ba9cf4d52d26a2",
"size": "17314",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "legacy/api-1.1/org/apache/struts/taglib/bean/PageTag.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "42594"
},
{
"name": "GAP",
"bytes": "7214"
},
{
"name": "HTML",
"bytes": "17088052"
},
{
"name": "Java",
"bytes": "6592773"
},
{
"name": "XSLT",
"bytes": "36989"
}
],
"symlink_target": ""
} |
<?php
return [
'title' => 'Aktiveringskontroll',
'name' => 'Aktiveringskontroll',
'description' => 'En säkerhetskontroll som garanterar att användare är aktiverade.'
];
| {
"content_hash": "5b3b523e0e4d6ec7145b110ddf9cae15",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 87,
"avg_line_length": 27.857142857142858,
"alnum_prop": 0.6307692307692307,
"repo_name": "anomalylabs/activation_security_check-extension",
"id": "635a11ab513a7632c7c6dd79bf26bc0535094279",
"size": "198",
"binary": false,
"copies": "1",
"ref": "refs/heads/1.0/master",
"path": "resources/lang/sv/addon.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "2810"
}
],
"symlink_target": ""
} |
package org.apache.jena.tdb.index.bplustree;
import org.apache.jena.tdb.base.page.Page ;
import org.apache.jena.tdb.base.record.Record ;
/** Abstraction of a B+Tree node - either an branch (BTreeNode) or leaf (BTreeLeaf - records)*/
abstract public class BPTreePage implements Page
{
// Does not use PageBase because BPTreeRecords does not need it.
protected final BPlusTree bpTree ;
protected final BPlusTreeParams params ;
protected BPTreePage(BPlusTree bpTree)
{
if ( bpTree == null )
System.err.println("NULL B+Tree") ;
this.bpTree = bpTree ;
this.params = bpTree.getParams() ;
}
public final BPlusTree getBPlusTree() { return bpTree ; }
public final BPlusTreeParams getParams() { return params ; }
// /** Return the page number */
// abstract int getId() ;
/** Split in two, return the new (upper) page.
* Split key is highest key of the old (lower) page.
* Does NOT put pages back to any underlying block manager
*/
abstract BPTreePage split() ;
/** Move the element from the high end of this to the low end of other,
* possible including the splitKey
* Return the new split point (highest record in left tree for records; moved element for nodes)
*/
abstract Record shiftRight(BPTreePage other, Record splitKey) ;
/** Move the element from the high end of other to the high end of this,
* possible including the splitKey
* Return the new split point (highest record in left tree; moved element for nodes)
*/
abstract Record shiftLeft(BPTreePage other, Record splitKey) ;
/** Merge this (left) and the page immediately to it's right other into a single block
*/
abstract BPTreePage merge(BPTreePage right, Record splitKey) ;
//* Return the new page (may be left or right)
/** Test whether this page is full (has no space for a new element) - used in "insert" */
abstract boolean isFull() ;
/** Test whether this page is of minimum size (removing a record would violate the packing limits) - used in "delete" */
abstract boolean isMinSize() ;
abstract int getCount() ;
abstract void setCount(int count) ;
abstract int getMaxSize() ;
/** Test whether this page has any keys */
abstract boolean hasAnyKeys() ;
/** Find a record; return null if not found */
abstract Record internalSearch(Record rec) ;
// /** Find the page for the record (bottom-most page) */
// abstract BPTreeRecords findPage(Record rec) ;
//
// /** Find the first page (supports iterators) */
// abstract BPTreeRecords findFirstPage() ;
/** Insert a record - return existing value if any, else null - put back modified blocks */
abstract Record internalInsert(Record record) ;
/** Delete a record - return the old value if there was one, else null - put back modified blocks */
abstract Record internalDelete(Record record) ;
/** Least in page */
abstract Record getLowRecord() ;
/** Greatest in page */
abstract Record getHighRecord() ;
/** Least in subtree */
abstract Record minRecord() ;
/** Greatest in subtree */
abstract Record maxRecord() ;
/** Write, or at least ensure wil be written */
abstract void write() ;
/** Turn a read page into a write page */
abstract void promote() ;
/** Mark as no longer needed */
abstract void release() ;
/** Discard with this block (for ever) */
abstract void free() ;
/** Check - just this level.*/
abstract void checkNode() ;
/** Check - here and below */
abstract void checkNodeDeep() ;
/** Return the split point for this record (need only be a key)*/
abstract Record getSplitKey() ;
}
| {
"content_hash": "1f47114eb6567437fec4f2fdbdac70ce",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 125,
"avg_line_length": 33.6,
"alnum_prop": 0.6454451345755694,
"repo_name": "apache/jena",
"id": "410a12b975a5a8528c10db532daeac1b934507dc",
"size": "4669",
"binary": false,
"copies": "5",
"ref": "refs/heads/main",
"path": "jena-tdb1/src/main/java/org/apache/jena/tdb/index/bplustree/BPTreePage.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "22246"
},
{
"name": "C++",
"bytes": "5877"
},
{
"name": "CSS",
"bytes": "3241"
},
{
"name": "Dockerfile",
"bytes": "3341"
},
{
"name": "Elixir",
"bytes": "2548"
},
{
"name": "HTML",
"bytes": "69029"
},
{
"name": "Haml",
"bytes": "30030"
},
{
"name": "Java",
"bytes": "35185092"
},
{
"name": "JavaScript",
"bytes": "72788"
},
{
"name": "Lex",
"bytes": "82672"
},
{
"name": "Makefile",
"bytes": "198"
},
{
"name": "Perl",
"bytes": "35662"
},
{
"name": "Python",
"bytes": "416"
},
{
"name": "Ruby",
"bytes": "216471"
},
{
"name": "SCSS",
"bytes": "4242"
},
{
"name": "Shell",
"bytes": "264124"
},
{
"name": "Thrift",
"bytes": "3755"
},
{
"name": "Vue",
"bytes": "104702"
},
{
"name": "XSLT",
"bytes": "65126"
}
],
"symlink_target": ""
} |
/* React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
@import '../variables.css';
.RegisterPage-container {
margin: 0 auto;
padding: 0 0 40px;
max-width: var(--max-content-width);
}
.centeredLoginForm {
text-align: center;
margin-bottom: 50px;
}
.chart {
text-align: center;
margin-top: 15px;
margin-bottom: 15px;
}
.helpIcon{
font-size: 20px;
}
.stepHeading {
text-align: left;
font-size: 1.75em;
margin-top: 10px;
margin-bottom: 10px;
}
.topMargin {
margin-top: 10px;
}
| {
"content_hash": "5c3dbb834c6ca77487803a9185502ebe",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 71,
"avg_line_length": 13.945945945945946,
"alnum_prop": 0.6666666666666666,
"repo_name": "JosephArcher/KappaKappaKapping",
"id": "8dba60ecbfa2d5cc845db04488c34b8e69c89f7f",
"size": "516",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/RegisterPage/RegisterPage.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "18532"
},
{
"name": "HTML",
"bytes": "8789"
},
{
"name": "JavaScript",
"bytes": "164307"
}
],
"symlink_target": ""
} |
SELECT a FROM t1 WHERE rowid >= 4294967296 ORDER BY a | {
"content_hash": "b667eb9f0b746dd645ba128c00267158",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 53,
"avg_line_length": 53,
"alnum_prop": 0.7735849056603774,
"repo_name": "bkiers/sqlite-parser",
"id": "6c49e424c0a78ce104ab3c75144f9b8764644517",
"size": "154",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/resources/boundary1.test_57.sql",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "20112"
},
{
"name": "Java",
"bytes": "6273"
},
{
"name": "PLpgSQL",
"bytes": "324108"
}
],
"symlink_target": ""
} |
package org.radargun.utils;
import java.util.Collection;
import java.util.List;
/**
* Simple class to allow fluent API on list
*
* @author Radim Vansa <rvansa@redhat.com>
*/
public class ListBuilder<T> {
private List<T> list;
public ListBuilder(List<T> list) {
this.list = list;
}
public ListBuilder<T> add(T element) {
list.add(element);
return this;
}
public ListBuilder<T> addAll(Collection<T> elements) {
list.addAll(elements);
return this;
}
public List<T> build() {
return list;
}
}
| {
"content_hash": "9e667e7d07bc9962017b2f90a449677c",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 58,
"avg_line_length": 19,
"alnum_prop": 0.6112054329371817,
"repo_name": "Danny-Hazelcast/radargun",
"id": "f865db21cd59cfe9b010600ebc6964af110103eb",
"size": "589",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/main/java/org/radargun/utils/ListBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1494472"
},
{
"name": "Protocol Buffer",
"bytes": "178"
},
{
"name": "Python",
"bytes": "625"
},
{
"name": "Shell",
"bytes": "30072"
}
],
"symlink_target": ""
} |
<?php
/**
* UserAgentTest.
*/
namespace Quark\Utils;
use PHPUnit\Framework\TestCase;
/**
* UserAgentTest class.
*
* @coversDefaultClass \Quark\Utils\UserAgent
*/
class UserAgentTest extends TestCase
{
/**
* @covers ::__construct
*/
public function testUserAgent()
{
$userAgentString = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36';
$userAgent = new UserAgent($userAgentString);
$this->assertInstanceOf(UserAgent::class, $userAgent);
return $userAgent;
}
/**
* @covers ::__construct
*/
public function testUserAgentBot()
{
$userAgentBotString = 'Googlebot/2.1 (+http://www.googlebot.com/bot.html)';
$userAgentBot = new UserAgent($userAgentBotString);
$this->assertInstanceOf(UserAgent::class, $userAgentBot);
return $userAgentBot;
}
/**
* @depends testUserAgent
* @covers ::getBrowser
*/
public function testBrowser(UserAgent $userAgent)
{
$browserInfos = $userAgent->getBrowser();
$this->assertArraySubset(['name' => 'chrome', 'channel' => null, 'stock' => false, 'mode' => null, 'version' => '57', 'old' => false], $browserInfos);
}
/**
* @depends testUserAgent
* @covers ::getEngine
*/
public function testEngine(UserAgent $userAgent)
{
$engineInfos = $userAgent->getEngine();
$this->assertArraySubset(['name' => 'blink', 'version' => null], $engineInfos);
}
/**
* @depends testUserAgent
* @covers ::getOperatingSystem
*/
public function testOperatingSystem(UserAgent $userAgent)
{
$operatingSystemInfos = $userAgent->getOperatingSystem();
$this->assertArraySubset(['name' => 'os x', 'version' => 'el capitan 10.11'], $operatingSystemInfos);
}
/**
* @depends testUserAgent
* @covers ::getDevice
*/
public function testDevice(UserAgent $userAgent)
{
$deviceInfos = $userAgent->getDevice();
$this->assertArraySubset(['type' => 'desktop', 'subtype' => null, 'identified' => true, 'manufacturer' => 'apple', 'model' => 'macintosh'], $deviceInfos);
}
/**
* @depends testUserAgentBot
* @covers ::getBot
*/
public function testBot(UserAgent $userAgent)
{
$bot = $userAgent->getBot();
$this->assertTrue($bot);
}
}
| {
"content_hash": "b58016de484501a8625051efde3d2f5a",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 158,
"avg_line_length": 24.64516129032258,
"alnum_prop": 0.6452879581151832,
"repo_name": "fm-ph/quark-server",
"id": "5bb4477d736bfdb48b069bbefae9114e5f100bff",
"size": "2292",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "tests/UserAgentTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "45843"
}
],
"symlink_target": ""
} |
package io.crate.integrationtests;
import org.apache.lucene.tests.util.TestUtil;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.test.IntegTestCase;
import org.junit.Test;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import static io.crate.testing.TestingHelpers.printedTable;
import static org.assertj.core.api.Assertions.assertThat;
@IntegTestCase.ClusterScope(numDataNodes = 0, numClientNodes = 0)
public class IndexUpgraderTest extends IntegTestCase {
/**
* {@link TablesNeedUpgradeSysCheckTest#startUpNodeWithDataDir(String)}
*/
private void startUpNodeWithDataDir(String dataPath) throws Exception {
Path indexDir = createTempDir();
try (InputStream stream = Files.newInputStream(getDataPath(dataPath))) {
TestUtil.unzip(stream, indexDir);
}
Settings.Builder builder = Settings.builder().put(Environment.PATH_DATA_SETTING.getKey(), indexDir.toAbsolutePath());
internalCluster().startNode(builder.build());
ensureGreen();
}
@Test
public void test_index_upgraders_fix_column_positions() throws Exception {
startUpNodeWithDataDir("/indices/data_home/cratedata-5.0-bebe506.zip"); // https://github.com/crate/crate/commit/bebe5065dc6f6d50537919559bf1f0cfd3992be9
/* Table 1) 'testing'
CREATE TABLE IF NOT EXISTS "doc"."testing" (
"p1" text, -- position 1
"nested" OBJECT(DYNAMIC) AS ( -- position 2
"sub1" OBJECT(DYNAMIC) AS ( -- position 3
"sub2" BIGINT, "sub3" bigint -- position 4, position 5
)
),
"nested2" OBJECT(DYNAMIC) AS ( -- position 4
"sub1" OBJECT(DYNAMIC) AS ( -- position 5
"sub2" BIGINT, "sub3" bigint -- position 6, position 7
)
),
"obj" object(dynamic), -- position 6
"obj2" object(dynamic) -- position 7
);
insert into testing (p1, obj) values (1, {a=1}); -- position 'null'
Table 2) 'partitioned'
CREATE TABLE IF NOT EXISTS "doc"."partitioned" (
"p1" text, -- position 1
"nested" OBJECT(DYNAMIC) AS ( -- position 2
"sub1" OBJECT(DYNAMIC) AS ( -- position 3
"sub2" BIGINT, "sub3" bigint -- position 4, position 5
)
),
"nested2" OBJECT(DYNAMIC) AS ( -- position 4
"sub1" OBJECT(DYNAMIC) AS ( -- position 5
"sub2" BIGINT, "sub3" bigint -- position 6, position 7
)
),
"obj" object(dynamic), -- position 6
"obj2" object(dynamic) -- position 7
) partitioned by (p1);
insert into partitioned (p1, obj) values (1, {a=1}); -- position 'null'
Notice the duplicates and 'null' columns.
The only difference in the two are that one is partitioned and the other is not.
The partitioned has template mapping and index mapping containing invalid column position whereas
the unpartitioned has only index mapping to take care of.
*/
// notice that duplicates and null positions are gone while keeping top-level positions (1, 2, 4, 6, 7)
String expected = """
nested| 2
nested2| 4
nested2['sub1']| 8
nested2['sub1']['sub2']| 10
nested2['sub1']['sub3']| 11
nested['sub1']| 3
nested['sub1']['sub2']| 12
nested['sub1']['sub3']| 5
obj| 6
obj2| 7
obj['a']| 9
p1| 1
""";
execute("select column_name, ordinal_position from information_schema.columns where table_name = 'partitioned' order by 1");
assertThat(printedTable(response.rows())).isEqualTo(expected);
execute("select column_name, ordinal_position from information_schema.columns where table_name = 'testing' order by 1");
assertThat(printedTable(response.rows())).isEqualTo(expected);
}
}
| {
"content_hash": "d0c5b5cff8d4d1a03312bab890dfec1b",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 161,
"avg_line_length": 43,
"alnum_prop": 0.574948192493668,
"repo_name": "crate/crate",
"id": "2162465b50d58293cca8f04a0e75ef280cde548f",
"size": "5356",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/src/test/java/io/crate/integrationtests/IndexUpgraderTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "41007"
},
{
"name": "Batchfile",
"bytes": "4449"
},
{
"name": "Java",
"bytes": "31937866"
},
{
"name": "Python",
"bytes": "71077"
},
{
"name": "Shell",
"bytes": "13572"
}
],
"symlink_target": ""
} |
package jjwu.xdeveloper.java.mybatise.core;
import java.io.UnsupportedEncodingException;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import org.apache.log4j.Logger;
/**
*
* @类名: LatinConverter
* @描述: 拉丁转换处理
*
* @作者: 吴君杰
* @邮箱: wujunjie@iwgame.com
* @日期: 2012-10-24下午03:11:33
* @版本: 1.0
*/
public class LatinConverter implements JsonValueProcessor {
private final static Logger logger = Logger.getLogger(LatinConverter.class);
public void sayHello(){
System.out.println("latin");
}
/**
* 中文转换拉丁
*
* @param params
* @return
*/
public static String tranferEncode_latin1(String params) {
byte[] b;
String result = "";
if (params != null) {
try {
// 字符转换成UTF-8
result = new String(params.getBytes(), "UTF-8");
b = result.getBytes("GBK");
result = new String(b, "iso-8859-1");
} catch (UnsupportedEncodingException e) {
LatinConverter.logger.error("字符 [ " + params + " ] 转码 \"iso-8859-1\" 错误!异常信息:", e);
}
}
return result;
}
/**
* 拉丁转换中文
*
* @param params
* @return
*/
public static String tranferEncode_zh(String params) {
byte[] b;
String result = "";
if (params != null) {
try {
result = new String(params.getBytes(), "UTF-8");
b = result.getBytes("iso-8859-1");
result = new String(b, "GBK");
} catch (UnsupportedEncodingException e) {
LatinConverter.logger.error("字符 [ " + params + " ] 转码 \"iso-8859-1\" 错误!异常信息:", e);
}
}
return result;
}
/*
* (non-Javadoc)
*
* @see
* net.sf.json.processors.JsonValueProcessor#processArrayValue(java.lang
* .Object, net.sf.json.JsonConfig)
*/
@Override
public Object processArrayValue(Object value, JsonConfig config) {
return process("", value);
}
/*
* (non-Javadoc)
*
* @see
* net.sf.json.processors.JsonValueProcessor#processObjectValue(java.lang
* .String, java.lang.Object, net.sf.json.JsonConfig)
*/
@Override
public Object processObjectValue(String key, Object value, JsonConfig config) {
return process(key, value);
}
/**
* 处理latin
*
* @param key
* @param value
* @return
*/
private Object process(String key, Object value) {
if ("name".equals(key)) {
return LatinConverter.tranferEncode_zh(value.toString());
}
return value;
}
public static void main(String[] args) {
// System.out.println(tranferEncode_latin1("╈嗳嘚☆伤"));
System.out.println(LatinConverter.tranferEncode_zh("¡«Ìì¡«µØ¡«»á¡«"));
System.out.println(LatinConverter.tranferEncode_zh("OoÌúѪvƮѩoO"));
}
}
| {
"content_hash": "c8ce9fdf27ea8cd0a9a8a9a69e7c4b24",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 87,
"avg_line_length": 22.074380165289256,
"alnum_prop": 0.6226132534631225,
"repo_name": "areskts/xdeveloper",
"id": "0d1e8a5efaa9b733199ace4171f8578e82edb52b",
"size": "3285",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xdeveloper-java-mybatise/src/main/java/jjwu/xdeveloper/java/mybatise/core/LatinConverter.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1036"
},
{
"name": "Java",
"bytes": "99012"
}
],
"symlink_target": ""
} |
// -*- c-basic-offset: 4 -*-
#ifndef CLICK_AGGREGATEPAINT_HH
#define CLICK_AGGREGATEPAINT_HH
#include <click/element.hh>
CLICK_DECLS
/*
=c
AggregatePaint([BITS, I<KEYWORDS>])
=s aggregates
sets aggregate annotation based on paint annotation
=d
AggregatePaint sets the aggregate annotation on every passing packet to a
portion of that packet's paint annotation. By default, it is simply set to
the paint annotation; but if you specify a number for BITS, then only the
low-order BITS bits of the annotation are used.
Keyword arguments are:
=over 8
=item INCREMENTAL
Boolean. If true, then incrementally update the aggregate annotation: given a
paint annotation with value V, and an old aggregate annotation of O, the new
aggregate annotation will equal (O * 2^LENGTH) + V. Default is false.
=back
=a
AggregateLength, AggregateIPFlows, AggregateCounter, AggregateIP
*/
class AggregatePaint : public Element { public:
AggregatePaint() CLICK_COLD;
~AggregatePaint() CLICK_COLD;
const char *class_name() const { return "AggregatePaint"; }
const char *port_count() const { return PORTS_1_1; }
int configure(Vector<String> &, ErrorHandler *) CLICK_COLD;
Packet *simple_action(Packet *);
private:
int _bits;
bool _incremental;
};
CLICK_ENDDECLS
#endif
| {
"content_hash": "38fecb236bd8aba69f035f16b73c71a9",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 78,
"avg_line_length": 21.360655737704917,
"alnum_prop": 0.7352264006139677,
"repo_name": "arkadeepsen/SDAP",
"id": "13b573c17ad8ec40f4bca148773cc7cf03d50932",
"size": "1303",
"binary": false,
"copies": "20",
"ref": "refs/heads/master",
"path": "click/elements/analysis/aggregatepaint.hh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "10775281"
},
{
"name": "C++",
"bytes": "7303920"
},
{
"name": "CSS",
"bytes": "362"
},
{
"name": "Click",
"bytes": "126715"
},
{
"name": "Groff",
"bytes": "59614"
},
{
"name": "HTML",
"bytes": "19036"
},
{
"name": "Hack",
"bytes": "271915"
},
{
"name": "Java",
"bytes": "2396580"
},
{
"name": "JavaScript",
"bytes": "458194"
},
{
"name": "M4",
"bytes": "5747"
},
{
"name": "Makefile",
"bytes": "266273"
},
{
"name": "Perl",
"bytes": "296894"
},
{
"name": "Python",
"bytes": "41286"
},
{
"name": "Shell",
"bytes": "258365"
},
{
"name": "TeX",
"bytes": "202681"
},
{
"name": "Thrift",
"bytes": "1610"
},
{
"name": "VimL",
"bytes": "21113"
},
{
"name": "XSLT",
"bytes": "4975"
},
{
"name": "Yacc",
"bytes": "3267"
}
],
"symlink_target": ""
} |
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderIniteece7d12cec1bbdb42308fcc7f5ed462::getLoader();
| {
"content_hash": "e3ce358a79182538581fef8a2816cbd4",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 75,
"avg_line_length": 26.142857142857142,
"alnum_prop": 0.7595628415300546,
"repo_name": "Andrel322/sysocial",
"id": "9b1203ed44a89657ae05cc3598e956e1d7e9fa0f",
"size": "183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/autoload.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "3605"
},
{
"name": "CSS",
"bytes": "1611"
},
{
"name": "HTML",
"bytes": "7873"
},
{
"name": "JavaScript",
"bytes": "484"
},
{
"name": "PHP",
"bytes": "83157"
}
],
"symlink_target": ""
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ImpaleScript : MonoBehaviour {
public GameObject ceiling;
float impaledCount;
public float speed;
public float ceilingTrigger;
float WARNING_TRIGGER = 0.137f;
GameObject lightSource;
GameObject room;
public AudioClip hurt;
public AudioClip spikeEngine;
AudioSource audioSource;
public GameObject fallenSpike;
// Use this for initialization
void Start () {
impaledCount = 0;
lightSource = GameObject.Find("Directional Light");
room = GameObject.Find("Room");
audioSource = room.GetComponent<AudioSource>();
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.name.Contains("Foot Cube"))
{
Debug.Log("OUCH");
audioSource.PlayOneShot(hurt);
//lightSource.GetComponent<Light>().color = Color.blue;
impaledCount += 1;
Debug.Log("ImpaledCount = " + impaledCount);
}
if (other.gameObject.name == ("HeadCollider"))
{
Debug.Log("DEAD HEAD");
SceneManager.LoadScene("Lobby");
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.name.Contains("Foot Cube"))
{
Debug.Log("OUCH");
lightSource.GetComponent<Light>().color = Color.red;
}
}
// Update is called once per frame
void Update () {
if (impaledCount > ceilingTrigger)
{
audioSource.PlayOneShot(spikeEngine);
ceiling.transform.Translate(Vector3.forward * speed * Time.deltaTime);
//StartCoroutine(WaitTillDeath(6));
}
float warning = Vector3.Distance(transform.position, GameObject.Find("Foot Cube").transform.position);
//Debug.Log("Warning Distance = " + warning + "and WARNING_TRIGGER IS " + WARNING_TRIGGER);
if (warning < WARNING_TRIGGER)
{
Debug.Log("WARNING, TOO CLOSE");
//fallenSpike.gameObject.AddComponent<Rigidbody>();
}
}
IEnumerator WaitTillDeath(float time)
{
yield return new WaitForSeconds(time);
SceneManager.LoadScene("Lobby");
}
}
| {
"content_hash": "74e9cb98af455c6e779cfbdab5a36db6",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 110,
"avg_line_length": 27.650602409638555,
"alnum_prop": 0.6143790849673203,
"repo_name": "denniscarr/VirtualFeet",
"id": "7a8cf8ec2e49e0773c36a5bf59fb67b49032b8f3",
"size": "2297",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/Scripts/ImpaleScript.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "118649"
},
{
"name": "C#",
"bytes": "1043551"
},
{
"name": "GLSL",
"bytes": "17350"
},
{
"name": "HLSL",
"bytes": "7611"
},
{
"name": "Mathematica",
"bytes": "129003"
},
{
"name": "ShaderLab",
"bytes": "48941"
}
],
"symlink_target": ""
} |
<?php
namespace FME\GoogleMapsStoreLocator\Controller\Adminhtml\Storelocator;
class NewAction extends \Magento\Backend\App\Action
{
/**
* Authorization level of a basic admin session
*
* @see _isAllowed()
*/
const ADMIN_RESOURCE = 'FME_GoogleMapsStoreLocator::save';
/**
* @var \Magento\Backend\Model\View\Result\Forward
*/
protected $resultForwardFactory;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory
) {
$this->resultForwardFactory = $resultForwardFactory;
parent::__construct($context);
}
/**
* Forward to edit
*
* @return \Magento\Backend\Model\View\Result\Forward
*/
public function execute()
{
/** @var \Magento\Backend\Model\View\Result\Forward $resultForward */
$resultForward = $this->resultForwardFactory->create();
return $resultForward->forward('edit');
}
}
| {
"content_hash": "9264c528ce4d45a2d84d96d51c4a8c42",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 85,
"avg_line_length": 28.285714285714285,
"alnum_prop": 0.6540404040404041,
"repo_name": "letunhatkong/teletronm2",
"id": "77a630948b746aa7ec10b8589fccbcdc99497015",
"size": "1289",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/code/FME/GoogleMapsStoreLocator/Controller/Adminhtml/Storelocator/NewAction.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "55818"
},
{
"name": "HTML",
"bytes": "196056"
},
{
"name": "JavaScript",
"bytes": "5636"
},
{
"name": "PHP",
"bytes": "729436"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-GB" xml:lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Statistics of Poss in UD_Czech-PDT</title>
<link rel="root" href=""/> <!-- for JS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
<link rel="stylesheet" type="text/css" href="../../css/hint.css"/>
<script type="text/javascript" src="../../lib/ext/head.load.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.2/anchor.min.js"></script>
<script>document.addEventListener("DOMContentLoaded", function(event) {anchors.add();});</script>
<!-- Set up this custom Google search at https://cse.google.com/cse/business/settings?cx=001145188882102106025:dl1mehhcgbo -->
<!-- DZ 2021-01-22: I am temporarily hiding the search field to find out whether it slows down loading of the title page.
<script>
(function() {
var cx = '001145188882102106025:dl1mehhcgbo';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script> -->
<!-- <link rel="shortcut icon" href="favicon.ico"/> -->
</head>
<body>
<div id="main" class="center">
<div id="hp-header">
<table width="100%"><tr><td width="50%">
<span class="header-text"><a href="http://universaldependencies.org/#language-">home</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/edit/pages-source/treebanks/cs_pdt/cs_pdt-feat-Poss.md" target="#">edit page</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/issues">issue tracker</a></span>
</td><td>
<gcse:search></gcse:search>
</td></tr></table>
</div>
<hr/>
<div class="v2complete">
This page pertains to UD version 2.
</div>
<div id="content">
<noscript>
<div id="noscript">
It appears that you have Javascript disabled.
Please consider enabling Javascript for this page to see the visualizations.
</div>
</noscript>
<!-- The content may include scripts and styles, hence we must load the shared libraries before the content. -->
<script type="text/javascript">
console.time('loading libraries');
var root = '../../'; // filled in by jekyll
head.js(
// External libraries
// DZ: Copied from embedding.html. I don't know which one is needed for what, so I'm currently keeping them all.
root + 'lib/ext/jquery.min.js',
root + 'lib/ext/jquery.svg.min.js',
root + 'lib/ext/jquery.svgdom.min.js',
root + 'lib/ext/jquery.timeago.js',
root + 'lib/ext/jquery-ui.min.js',
root + 'lib/ext/waypoints.min.js',
root + 'lib/ext/jquery.address.min.js'
);
</script>
<h2 id="treebank-statistics-ud_czech-pdt-features-poss">Treebank Statistics: UD_Czech-PDT: Features: <code class="language-plaintext highlighter-rouge">Poss</code></h2>
<p>This feature is universal.
It occurs with 1 different values: <code class="language-plaintext highlighter-rouge">Yes</code>.</p>
<p>17024 tokens (1%) have a non-empty value of <code class="language-plaintext highlighter-rouge">Poss</code>.
1973 types (2%) occur at least once with a non-empty value of <code class="language-plaintext highlighter-rouge">Poss</code>.
1146 lemmas (2%) occur at least once with a non-empty value of <code class="language-plaintext highlighter-rouge">Poss</code>.
The feature is used with 2 part-of-speech tags: <tt><a href="cs_pdt-pos-DET.html">DET</a></tt> (14317; 1% instances), <tt><a href="cs_pdt-pos-ADJ.html">ADJ</a></tt> (2707; 0% instances).</p>
<h3 id="det"><code class="language-plaintext highlighter-rouge">DET</code></h3>
<p>14317 <tt><a href="cs_pdt-pos-DET.html">DET</a></tt> tokens (25% of all <code class="language-plaintext highlighter-rouge">DET</code> tokens) have a non-empty value of <code class="language-plaintext highlighter-rouge">Poss</code>.</p>
<p>The most frequent other feature values with which <code class="language-plaintext highlighter-rouge">DET</code> and <code class="language-plaintext highlighter-rouge">Poss</code> co-occurred: <tt><a href="cs_pdt-feat-PronType.html">PronType</a></tt><tt>=Prs</tt> (13642; 95%), <tt><a href="cs_pdt-feat-Animacy.html">Animacy</a></tt><tt>=EMPTY</tt> (13350; 93%).</p>
<p><code class="language-plaintext highlighter-rouge">DET</code> tokens may have the following values of <code class="language-plaintext highlighter-rouge">Poss</code>:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">Yes</code> (14317; 100% of non-empty <code class="language-plaintext highlighter-rouge">Poss</code>): <em>jeho, jejich, své, její, svou, svého, svých, svůj, naše, svým</em></li>
<li><code class="language-plaintext highlighter-rouge">EMPTY</code> (41899): <em>to, které, který, která, tím, kteří, tom, této, tomu, tento</em></li>
</ul>
<p><code class="language-plaintext highlighter-rouge">Poss</code> seems to be <strong>lexical feature</strong> of <code class="language-plaintext highlighter-rouge">DET</code>. 100% lemmas (14) occur only with one value of <code class="language-plaintext highlighter-rouge">Poss</code>.</p>
<h3 id="adj"><code class="language-plaintext highlighter-rouge">ADJ</code></h3>
<p>2707 <tt><a href="cs_pdt-pos-ADJ.html">ADJ</a></tt> tokens (1% of all <code class="language-plaintext highlighter-rouge">ADJ</code> tokens) have a non-empty value of <code class="language-plaintext highlighter-rouge">Poss</code>.</p>
<p>The most frequent other feature values with which <code class="language-plaintext highlighter-rouge">ADJ</code> and <code class="language-plaintext highlighter-rouge">Poss</code> co-occurred: <tt><a href="cs_pdt-feat-Degree.html">Degree</a></tt><tt>=EMPTY</tt> (2707; 100%), <tt><a href="cs_pdt-feat-Polarity.html">Polarity</a></tt><tt>=EMPTY</tt> (2707; 100%), <tt><a href="cs_pdt-feat-VerbForm.html">VerbForm</a></tt><tt>=EMPTY</tt> (2707; 100%), <tt><a href="cs_pdt-feat-Voice.html">Voice</a></tt><tt>=EMPTY</tt> (2707; 100%), <tt><a href="cs_pdt-feat-Number.html">Number</a></tt><tt>=Sing</tt> (2189; 81%), <tt><a href="cs_pdt-feat-Animacy.html">Animacy</a></tt><tt>=EMPTY</tt> (1602; 59%).</p>
<p><code class="language-plaintext highlighter-rouge">ADJ</code> tokens may have the following values of <code class="language-plaintext highlighter-rouge">Poss</code>:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">Yes</code> (2707; 100% of non-empty <code class="language-plaintext highlighter-rouge">Poss</code>): <em>Karlovy, Karlových, Nobelovy, Milíčova, Masarykově, Karlova, Karlově, prezidentův, Benešových, Nobelovu</em></li>
<li><code class="language-plaintext highlighter-rouge">EMPTY</code> (186479): <em>první, další, české, nové, druhé, poslední, státní, dalších, možné, vlastní</em></li>
</ul>
<p><code class="language-plaintext highlighter-rouge">Poss</code> seems to be <strong>lexical feature</strong> of <code class="language-plaintext highlighter-rouge">ADJ</code>. 100% lemmas (1132) occur only with one value of <code class="language-plaintext highlighter-rouge">Poss</code>.</p>
<h2 id="relations-with-agreement-in-poss">Relations with Agreement in <code class="language-plaintext highlighter-rouge">Poss</code></h2>
<p>The 10 most frequent relations where parent and child node agree in <code class="language-plaintext highlighter-rouge">Poss</code>:
<tt>ADJ –[<tt><a href="cs_pdt-dep-conj.html">conj</a></tt>]–> ADJ</tt> (36; 75%),
<tt>DET –[<tt><a href="cs_pdt-dep-conj.html">conj</a></tt>]–> DET</tt> (26; 100%),
<tt>DET –[<tt><a href="cs_pdt-dep-dep.html">dep</a></tt>]–> DET</tt> (2; 67%).</p>
</div>
<!-- support for embedded visualizations -->
<script type="text/javascript">
var root = '../../'; // filled in by jekyll
head.js(
// We assume that external libraries such as jquery.min.js have already been loaded outside!
// (See _layouts/base.html.)
// brat helper modules
root + 'lib/brat/configuration.js',
root + 'lib/brat/util.js',
root + 'lib/brat/annotation_log.js',
root + 'lib/ext/webfont.js',
// brat modules
root + 'lib/brat/dispatcher.js',
root + 'lib/brat/url_monitor.js',
root + 'lib/brat/visualizer.js',
// embedding configuration
root + 'lib/local/config.js',
// project-specific collection data
root + 'lib/local/collections.js',
// Annodoc
root + 'lib/annodoc/annodoc.js',
// NOTE: non-local libraries
'https://spyysalo.github.io/conllu.js/conllu.js'
);
var webFontURLs = [
// root + 'static/fonts/Astloch-Bold.ttf',
root + 'static/fonts/PT_Sans-Caption-Web-Regular.ttf',
root + 'static/fonts/Liberation_Sans-Regular.ttf'
];
var setupTimeago = function() {
jQuery("time.timeago").timeago();
};
head.ready(function() {
setupTimeago();
// mark current collection (filled in by Jekyll)
Collections.listing['_current'] = '';
// perform all embedding and support functions
Annodoc.activate(Config.bratCollData, Collections.listing);
});
</script>
<!-- google analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-55233688-1', 'auto');
ga('send', 'pageview');
</script>
<div id="footer">
<p class="footer-text">© 2014–2021
<a href="http://universaldependencies.org/introduction.html#contributors" style="color:gray">Universal Dependencies contributors</a>.
Site powered by <a href="http://spyysalo.github.io/annodoc" style="color:gray">Annodoc</a> and <a href="http://brat.nlplab.org/" style="color:gray">brat</a></p>.
</div>
</div>
</body>
</html>
| {
"content_hash": "52e931ab83b482bb10767b4bb2a47e6c",
"timestamp": "",
"source": "github",
"line_count": 200,
"max_line_length": 701,
"avg_line_length": 54.825,
"alnum_prop": 0.6507979936160511,
"repo_name": "UniversalDependencies/universaldependencies.github.io",
"id": "4908c853404e593deb1a1528c3bbd113b124707c",
"size": "11016",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "treebanks/cs_pdt/cs_pdt-feat-Poss.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "64420"
},
{
"name": "HTML",
"bytes": "383191916"
},
{
"name": "JavaScript",
"bytes": "687350"
},
{
"name": "Perl",
"bytes": "7788"
},
{
"name": "Python",
"bytes": "21203"
},
{
"name": "Shell",
"bytes": "7253"
}
],
"symlink_target": ""
} |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.device.bluetooth;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothDevice;
import android.os.Build;
import android.os.ParcelUuid;
import org.chromium.base.CalledByNative;
import org.chromium.base.JNINamespace;
import org.chromium.base.Log;
import java.util.List;
/**
* Exposes android.bluetooth.BluetoothDevice as necessary for C++
* device::BluetoothDeviceAndroid.
*
* Lifetime is controlled by device::BluetoothDeviceAndroid.
*/
@JNINamespace("device")
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
final class ChromeBluetoothDevice {
private static final String TAG = "cr.Bluetooth";
private final Wrappers.BluetoothDeviceWrapper mDevice;
private List<ParcelUuid> mUuidsFromScan;
private ChromeBluetoothDevice(Wrappers.BluetoothDeviceWrapper deviceWrapper) {
mDevice = deviceWrapper;
Log.v(TAG, "ChromeBluetoothDevice created.");
}
// ---------------------------------------------------------------------------------------------
// BluetoothDeviceAndroid methods implemented in java:
// Implements BluetoothDeviceAndroid::Create.
// 'Object' type must be used because inner class Wrappers.BluetoothDeviceWrapper reference is
// not handled by jni_generator.py JavaToJni. http://crbug.com/505554
@CalledByNative
private static ChromeBluetoothDevice create(Object deviceWrapper) {
return new ChromeBluetoothDevice((Wrappers.BluetoothDeviceWrapper) deviceWrapper);
}
// Implements BluetoothDeviceAndroid::UpdateAdvertisedUUIDs.
@CalledByNative
private boolean updateAdvertisedUUIDs(List<ParcelUuid> uuidsFromScan) {
if ((mUuidsFromScan == null && uuidsFromScan == null)
|| (mUuidsFromScan != null && mUuidsFromScan.equals(uuidsFromScan))) {
return false;
}
mUuidsFromScan = uuidsFromScan;
return true;
}
// Implements BluetoothDeviceAndroid::GetBluetoothClass.
@CalledByNative
private int getBluetoothClass() {
return mDevice.getBluetoothClass_getDeviceClass();
}
// Implements BluetoothDeviceAndroid::GetAddress.
@CalledByNative
private String getAddress() {
return mDevice.getAddress();
}
// Implements BluetoothDeviceAndroid::IsPaired.
@CalledByNative
private boolean isPaired() {
return mDevice.getBondState() == BluetoothDevice.BOND_BONDED;
}
// Implements BluetoothDeviceAndroid::GetUUIDs.
@CalledByNative
private String[] getUuids() {
int uuidCount = (mUuidsFromScan != null) ? mUuidsFromScan.size() : 0;
String[] string_array = new String[uuidCount];
for (int i = 0; i < uuidCount; i++) {
string_array[i] = mUuidsFromScan.get(i).toString();
}
// TODO(scheib): return merged list of UUIDs from scan results and,
// after a device is connected, discoverServices. crbug.com/508648
return string_array;
}
// Implements BluetoothDeviceAndroid::GetDeviceName.
@CalledByNative
private String getDeviceName() {
return mDevice.getName();
}
}
| {
"content_hash": "63b15ecd725ebb115c9d535490d35724",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 100,
"avg_line_length": 34,
"alnum_prop": 0.6895087932080048,
"repo_name": "lihui7115/ChromiumGStreamerBackend",
"id": "cca60b0faa3ebaa679da7ea7027a7e73c4089da0",
"size": "3298",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "device/bluetooth/android/java/src/org/chromium/device/bluetooth/ChromeBluetoothDevice.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "37073"
},
{
"name": "Batchfile",
"bytes": "8451"
},
{
"name": "C",
"bytes": "9508834"
},
{
"name": "C++",
"bytes": "242598549"
},
{
"name": "CSS",
"bytes": "943747"
},
{
"name": "DM",
"bytes": "60"
},
{
"name": "Groff",
"bytes": "2494"
},
{
"name": "HTML",
"bytes": "27281878"
},
{
"name": "Java",
"bytes": "14561064"
},
{
"name": "JavaScript",
"bytes": "20540839"
},
{
"name": "Makefile",
"bytes": "70864"
},
{
"name": "Objective-C",
"bytes": "1745880"
},
{
"name": "Objective-C++",
"bytes": "10008668"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "PLpgSQL",
"bytes": "178732"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "482954"
},
{
"name": "Python",
"bytes": "8626890"
},
{
"name": "Shell",
"bytes": "481888"
},
{
"name": "Standard ML",
"bytes": "5106"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.