text
stringlengths 2
1.04M
| meta
dict |
---|---|
module Mongoid
module FieldInheritance
##
# Module which contains relation macro methods.
#
# @since 0.1.0
module Relations
extend ActiveSupport::Concern
included do
class << self
alias_method_chain :belongs_to, :inheritance
end
end
module ClassMethods
# Adds a relational association from the child Document to a Document in
# another database or collection.
#
# @example Define the relation.
#
# class Game
# include Mongoid::Document
# belongs_to :person
# end
#
# class Person
# include Mongoid::Document
# has_one :game
# end
#
# @param [Symbol] name The name of the relation.
# @param [Hash] options The relation options.
# @param [Proc] block Optional block for defining extensions.
def belongs_to_with_inheritance(name, options = {}, &block)
relation_opts = options.except(:inherit)
meta = belongs_to_without_inheritance(name, relation_opts, &block)
inherit(meta.foreign_key) if options.fetch(:inherit, false)
meta
end
end
end
end
end
| {
"content_hash": "abf80ecc53dde358fa067c920265b24d",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 80,
"avg_line_length": 28.477272727272727,
"alnum_prop": 0.5722266560255387,
"repo_name": "tlux/mongoid-field_inheritance",
"id": "d4aaeae02ab4bd873ed83f3586e43ea00a81848f",
"size": "1253",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/mongoid/field_inheritance/relations.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "67786"
}
],
"symlink_target": ""
} |
const expect = require('chai').expect
const Emitter = require('events').EventEmitter
const middleware = require('../../lib/middleware')
const noop = function () {}
suite('middleware#responseBody', function () {
var req, res
beforeEach(function () {
res = {
write: noop,
end: noop,
getHeader: function () { return 'application/json' }
}
})
beforeEach(function () {
req = new Emitter
})
function middlewareFn(req, res, next) {
var body = res.body.toString()
var newBody = body.split(' ').reverse().join(' ')
next(null, newBody, 'utf8')
}
function writeData() {
res.write(new Buffer('Ping '))
res.write(new Buffer('Pong'))
res.end()
}
test('transform', function (done) {
res.end = function () {
expect(res.body).to.be.equal('Pong Ping')
done()
}
middleware.responseBody
(middlewareFn)
(req, res, noop)
writeData()
})
test('filter', function (done) {
res.end = function () {
expect(res.body).to.be.equal('Pong Ping')
done()
}
function filter(res) {
return res.getHeader('content-type') === 'application/json'
}
middleware.responseBody
(middlewareFn, filter)
(req, res, noop)
writeData()
})
})
| {
"content_hash": "011eb1d8f2be107e4779b5603cc85548",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 65,
"avg_line_length": 20.64516129032258,
"alnum_prop": 0.58515625,
"repo_name": "carsonmcdonald/rocky",
"id": "410a050d2fafa4df301790b97d7b94069b035b60",
"size": "1280",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/middleware/response-body.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "84026"
},
{
"name": "Shell",
"bytes": "1458"
}
],
"symlink_target": ""
} |
clear all; close all; clc;
% this script does the cross validation i.e fix the hyper parameters of the
% model
% in our case the hyper parameters are
% i- the regularization term
% ii- the number of features that we need to extract
splitData_strong_weak_new; % load the data and make split it into
% Ytrain_new the training set
% Ytest_strong set (to test unseen users i.e that are not on the data base)
% Ytest_weak set
MAX_ITER=100;
Ytrain_norm=cleaning_data(Ytrain_new); %clean only the actual train set
% now make cross valication on this set Ytrain_norm
Nf= ceil(linspace (2,100,10));
lambda= logspace(-2,2,10);
K=10; % # of folds
subRMSE=zeros(2,K); % 1st line stores the train RMSE and 2nd stores the test RMSE
meanRMSE_Te=zeros(length(Nf),length(lambda));
meanRMSE_Tr=zeros(length(Nf),length(lambda));
for i=1:length(Nf)
for j=1: length(lambda)
for k=1:K
[YTr,YTe]=splitData_Tr_Te(Ytrain_norm);
%learn the model for these hyper params in this sub fold
[subRMSE(1,k),U,A,nu_i,na_j]=ALS_estimate(YTr,lambda(j),Nf(i),MAX_ITER);
%test the model for these hyper params in this sub fold
subRMSE(2,k)=cost_func(YTe,U,A,lambda(j),nu_i,na_j);
end
meanRMSE_Tr(i,j)=mean(subRMSE(1,:));
meanRMSE_Te(i,j)=mean(subRMSE(2,:));
fprintf('i=%d,j=%d lambda = %.2f Nf = %d TestRMSE %f \n',i,j,...
lambda(j),Nf(i),meanRMSE_Te(i,j));
end
end
[L_star,ind_star]=min(meanRMSE_Te(:));
[Nf_star,lambda_star]=ind2sub([length(Nf),length(lambda)],ind_star);
% now we have our estimate for the hyper params we can estimate the actual
% RMSE on the test data (weak and strong )
| {
"content_hash": "d7f2bb3e0e41748221e20c4c3874747e",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 84,
"avg_line_length": 37.21739130434783,
"alnum_prop": 0.6542056074766355,
"repo_name": "lwiss/MusicRecommender",
"id": "9c1612a5aa1bf5640ce695bee2e96528e4164240",
"size": "1712",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "learning/crossValidation.m",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Matlab",
"bytes": "36183"
}
],
"symlink_target": ""
} |
package com.pivotal.gemfirexd.internal.iapi.store.raw;
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.store.raw.log.LogInstant;
import java.io.InputStream;
public interface ScannedTransactionHandle
{
Loggable getNextRecord()
throws StandardException;
InputStream getOptionalData()
throws StandardException;
LogInstant getThisInstant()
throws StandardException;
LogInstant getLastInstant()
throws StandardException;
LogInstant getFirstInstant()
throws StandardException;
void close();
}
| {
"content_hash": "fa4583905b680aed471f114e47cd315f",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 68,
"avg_line_length": 21.285714285714285,
"alnum_prop": 0.7869127516778524,
"repo_name": "gemxd/gemfirexd-oss",
"id": "0f4410e0f97c31cbb6dabbf7debf2d8c24f4569c",
"size": "1483",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/iapi/store/raw/ScannedTransactionHandle.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AGS Script",
"bytes": "90653"
},
{
"name": "Assembly",
"bytes": "962433"
},
{
"name": "Batchfile",
"bytes": "30248"
},
{
"name": "C",
"bytes": "311620"
},
{
"name": "C#",
"bytes": "1352292"
},
{
"name": "C++",
"bytes": "2030283"
},
{
"name": "CSS",
"bytes": "54987"
},
{
"name": "Gnuplot",
"bytes": "3125"
},
{
"name": "HTML",
"bytes": "8609160"
},
{
"name": "Java",
"bytes": "118027963"
},
{
"name": "JavaScript",
"bytes": "33027"
},
{
"name": "Makefile",
"bytes": "18443"
},
{
"name": "Mathematica",
"bytes": "92588"
},
{
"name": "Objective-C",
"bytes": "1069"
},
{
"name": "PHP",
"bytes": "581417"
},
{
"name": "PLSQL",
"bytes": "86549"
},
{
"name": "PLpgSQL",
"bytes": "33847"
},
{
"name": "Pascal",
"bytes": "808"
},
{
"name": "Perl",
"bytes": "196843"
},
{
"name": "Python",
"bytes": "12796"
},
{
"name": "Ruby",
"bytes": "1380"
},
{
"name": "SQLPL",
"bytes": "219147"
},
{
"name": "Shell",
"bytes": "533575"
},
{
"name": "SourcePawn",
"bytes": "22351"
},
{
"name": "Thrift",
"bytes": "33033"
},
{
"name": "XSLT",
"bytes": "67112"
}
],
"symlink_target": ""
} |
namespace hyrise {
namespace hana = boost::hana;
enum class SegmentIndexType : uint8_t { Invalid, GroupKey, CompositeGroupKey, AdaptiveRadixTree, BTree };
class GroupKeyIndex;
class CompositeGroupKeyIndex;
class AdaptiveRadixTreeIndex;
class BTreeIndex;
namespace detail {
constexpr auto segment_index_map =
hana::make_map(hana::make_pair(hana::type_c<GroupKeyIndex>, SegmentIndexType::GroupKey),
hana::make_pair(hana::type_c<CompositeGroupKeyIndex>, SegmentIndexType::CompositeGroupKey),
hana::make_pair(hana::type_c<AdaptiveRadixTreeIndex>, SegmentIndexType::AdaptiveRadixTree),
hana::make_pair(hana::type_c<BTreeIndex>, SegmentIndexType::BTree));
} // namespace detail
template <typename IndexType>
SegmentIndexType get_index_type_of() {
return detail::segment_index_map[hana::type_c<IndexType>];
}
} // namespace hyrise
| {
"content_hash": "96a4dc6a3eb78b1339b6f00c14df30aa",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 110,
"avg_line_length": 33.22222222222222,
"alnum_prop": 0.7302118171683389,
"repo_name": "hyrise/hyrise",
"id": "303ac9e98cbfd2e3a90c8587d07c066ebed28ca4",
"size": "998",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/lib/storage/index/segment_index_type.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "5907952"
},
{
"name": "CMake",
"bytes": "76722"
},
{
"name": "Dockerfile",
"bytes": "1345"
},
{
"name": "PLpgSQL",
"bytes": "30508"
},
{
"name": "Python",
"bytes": "110241"
},
{
"name": "Shell",
"bytes": "30173"
}
],
"symlink_target": ""
} |
"""Settings used to establish valid credentials."""
# The service_account_name is the Email address created for the Service
# account from the API Console.
SERVICE_ACCOUNT_NAME = ('000000000000-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
'@developer.gserviceaccount.com')
SERVICE_SCOPES = [
# For directory.
'https://www.googleapis.com/auth/admin.directory.user.readonly',
# For IMAP mail API.
'https://mail.google.com/',
]
| {
"content_hash": "da87fcc7f931c1c138517fd5b337146e",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 71,
"avg_line_length": 35.38461538461539,
"alnum_prop": 0.691304347826087,
"repo_name": "yubbie/googleapps-message-recall",
"id": "55677c89a586c418e919c312146fe368b01ebb7a",
"size": "1058",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "message_recall/service_account.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "27490"
},
{
"name": "Python",
"bytes": "831541"
}
],
"symlink_target": ""
} |
include ../../p_rules.mak
include $(DIR_ROOT_BUILDUTIL)/libs.mak
| {
"content_hash": "b420e51355d9fe8908a41f8cf7c1b03c",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 38,
"avg_line_length": 32.5,
"alnum_prop": 0.7076923076923077,
"repo_name": "mike10004/nbis",
"id": "622b20c0ed3008341201b6e759109c634a94b6d2",
"size": "3009",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "nfseg/src/lib/Makefile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "5709396"
},
{
"name": "C++",
"bytes": "13394"
},
{
"name": "Objective-C",
"bytes": "2944"
},
{
"name": "Shell",
"bytes": "2955"
}
],
"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 (1.8.0_112) on Mon May 01 08:43:54 MST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.wildfly.swarm.mod_cluster Class Hierarchy (Public javadocs 2017.5.0 API)</title>
<meta name="date" content="2017-05-01">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.wildfly.swarm.mod_cluster Class Hierarchy (Public javadocs 2017.5.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.5.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/wildfly/swarm/messaging/detect/package-tree.html">Prev</a></li>
<li><a href="../../../../org/wildfly/swarm/monitor/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/wildfly/swarm/mod_cluster/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.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">
<h1 class="title">Hierarchy For Package org.wildfly.swarm.mod_cluster</h1>
<span class="packageHierarchyLabel">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a>
<ul>
<li type="circle">java.util.<a href="http://docs.oracle.com/javase/8/docs/api/java/util/AbstractMap.html?is-external=true" title="class or interface in java.util"><span class="typeNameLink">AbstractMap</span></a><K,V> (implements java.util.<a href="http://docs.oracle.com/javase/8/docs/api/java/util/Map.html?is-external=true" title="class or interface in java.util">Map</a><K,V>)
<ul>
<li type="circle">java.util.<a href="http://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html?is-external=true" title="class or interface in java.util"><span class="typeNameLink">HashMap</span></a><K,V> (implements java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Cloneable.html?is-external=true" title="class or interface in java.lang">Cloneable</a>, java.util.<a href="http://docs.oracle.com/javase/8/docs/api/java/util/Map.html?is-external=true" title="class or interface in java.util">Map</a><K,V>, java.io.<a href="http://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>)
<ul>
<li type="circle">org.wildfly.swarm.config.<a href="../../../../org/wildfly/swarm/config/Modcluster.html" title="class in org.wildfly.swarm.config"><span class="typeNameLink">Modcluster</span></a><T>
<ul>
<li type="circle">org.wildfly.swarm.mod_cluster.<a href="../../../../org/wildfly/swarm/mod_cluster/ModclusterFraction.html" title="class in org.wildfly.swarm.mod_cluster"><span class="typeNameLink">ModclusterFraction</span></a> (implements org.wildfly.swarm.spi.api.<a href="../../../../org/wildfly/swarm/spi/api/Fraction.html" title="interface in org.wildfly.swarm.spi.api">Fraction</a><T>)</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">org.wildfly.swarm.mod_cluster.<a href="../../../../org/wildfly/swarm/mod_cluster/ModclusterProperties.html" title="interface in org.wildfly.swarm.mod_cluster"><span class="typeNameLink">ModclusterProperties</span></a></li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.5.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/wildfly/swarm/messaging/detect/package-tree.html">Prev</a></li>
<li><a href="../../../../org/wildfly/swarm/monitor/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/wildfly/swarm/mod_cluster/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "5764c599b75b27e3fb5b43206a6d1251",
"timestamp": "",
"source": "github",
"line_count": 157,
"max_line_length": 700,
"avg_line_length": 45.0828025477707,
"alnum_prop": 0.6537157389092965,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "ce86907831774b03091bff52c161c2aaee8a6724",
"size": "7078",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2017.5.0/apidocs/org/wildfly/swarm/mod_cluster/package-tree.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<InitiateMultipartUploadResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Bucket>example-bucket</Bucket>
<Key>example-object</Key>
<UploadId>EXAMPLEJZ6e0YupT2h66iePQCc9IEbYbDUy4RTpMeoSMLPRp8Z5o1u8feSRonpvnWsKKG35tI2LB9VDPiCgTy.Gq2VxQLYjrue4Nq.NBdqI-</UploadId>
</InitiateMultipartUploadResult>
| {
"content_hash": "29e370f33f5b0299654552880d00120e",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 132,
"avg_line_length": 58.166666666666664,
"alnum_prop": 0.8051575931232091,
"repo_name": "CenterForOpenScience/waterbutler",
"id": "70938a78832195faee865f85fa4e6f09b274d368",
"size": "349",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "tests/providers/s3/fixtures/chunked_uploads/create_session_resp.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "922"
},
{
"name": "Python",
"bytes": "1673806"
}
],
"symlink_target": ""
} |
using System;
using Microsoft.VisualStudio.Language.Intellisense;
namespace GitHub.InlineReviews.Peek
{
class InlineCommentPeekRelationship : IPeekRelationship
{
static InlineCommentPeekRelationship instance;
private InlineCommentPeekRelationship()
{
}
public static InlineCommentPeekRelationship Instance
{
get
{
if (instance == null)
{
instance = new InlineCommentPeekRelationship();
}
return instance;
}
}
public string DisplayName => "GitHub Code Review";
public string Name => "GitHubCodeReview";
}
}
| {
"content_hash": "c04cfb02b6f662550cf4222a874deeac",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 67,
"avg_line_length": 23.866666666666667,
"alnum_prop": 0.5726256983240223,
"repo_name": "github/VisualStudio",
"id": "826b0002aa5e886afc65393a3392979dfe0c8d36",
"size": "718",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/GitHub.InlineReviews/Peek/InlineCommentPeekRelationship.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1227"
},
{
"name": "C",
"bytes": "953425"
},
{
"name": "C#",
"bytes": "3504607"
},
{
"name": "C++",
"bytes": "272062"
}
],
"symlink_target": ""
} |
<?php
/**
* Manage currency import services block
*
* @author Magento Core Team <[email protected]>
*/
namespace Magento\CurrencySymbol\Block\Adminhtml\System\Currency\Rate;
class Services extends \Magento\Backend\Block\Template
{
/**
* @var string
*/
protected $_template = 'system/currency/rate/services.phtml';
/**
* @var \Magento\Directory\Model\Currency\Import\Source\ServiceFactory
*/
protected $_srcCurrencyFactory;
/**
* @param \Magento\Backend\Block\Template\Context $context
* @param \Magento\Directory\Model\Currency\Import\Source\ServiceFactory $srcCurrencyFactory
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Directory\Model\Currency\Import\Source\ServiceFactory $srcCurrencyFactory,
array $data = []
) {
$this->_srcCurrencyFactory = $srcCurrencyFactory;
parent::__construct($context, $data);
}
/**
* Create import services form select element
*
* @return \Magento\Framework\View\Element\AbstractBlock
*/
protected function _prepareLayout()
{
$this->setChild(
'import_services',
$this->getLayout()->createBlock(
'Magento\Framework\View\Element\Html\Select'
)->setOptions(
$this->_srcCurrencyFactory->create()->toOptionArray()
)->setId(
'rate_services'
)->setClass(
'admin__control-select'
)->setName(
'rate_services'
)->setValue(
$this->_backendSession->getCurrencyRateService(true)
)->setTitle(
__('Import Service')
)
);
return parent::_prepareLayout();
}
}
| {
"content_hash": "d73f3d586d2f197ee0774e268b3adeae",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 96,
"avg_line_length": 28.50769230769231,
"alnum_prop": 0.5887749595250944,
"repo_name": "j-froehlich/magento2_wk",
"id": "9e2a71239adfe3e465ba4a70151feb36b539db64",
"size": "1961",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/magento/module-currency-symbol/Block/Adminhtml/System/Currency/Rate/Services.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "13636"
},
{
"name": "CSS",
"bytes": "2076720"
},
{
"name": "HTML",
"bytes": "6151072"
},
{
"name": "JavaScript",
"bytes": "2488727"
},
{
"name": "PHP",
"bytes": "12466046"
},
{
"name": "Shell",
"bytes": "6088"
},
{
"name": "XSLT",
"bytes": "19979"
}
],
"symlink_target": ""
} |
import {
createAction,
handleActions
} from 'redux-actions'
import request from 'superagent'
// ------------------------------------
// Constants
// ------------------------------------
export const REQUEST_POSTCARDS_DATA = 'REQUEST_POSTCARDS_DATA'
export const TOGGLE_BUTTOM_PLAYER = 'TOGGLE_BUTTOM_PLAYER'
// been set this value in component's local state : searchForm.js
// export const TOGGLE_SEARCHFORM = 'TOGGLE_SEARCHFORM'
export const SET_CATEGORY_VALUE = 'SET_CATEGORY_VALUE'
export const SET_LANGUAGE_VALUE = 'SET_LANGUAGE_VALUE'
export const SEARCH_NEWS = 'SEARCH_NEWS'
const INIT_INTERCOM_STATE = {
postCardsData: [],
isShowButtonPlayer: false,
isRenderSearchForm: false,
searchCategoryValue: '',
searchLanguageValue: ''
}
// ------------------------------------
// Actions
// ------------------------------------
const searchNews = createAction(SEARCH_NEWS)
const requestPostCardsdata = createAction(REQUEST_POSTCARDS_DATA)
const toggleButtomPlayerAction = createAction(TOGGLE_BUTTOM_PLAYER)
// const toggleSearchFormAction = createAction(TOGGLE_SEARCHFORM)
export const setSearchCategoryValue = createAction(SET_CATEGORY_VALUE)
export const setSearchLanguageValue = createAction(SET_LANGUAGE_VALUE)
export function toggleButtomPlayer () {
return (dispatch, getState) => {
dispatch(toggleButtomPlayerAction())
}
}
export function requestSearchNews (searchParams) {
return (dispatch, getState) => {
let fetching = progressFetchNews(searchParams)
fetching.then(result => {
if (result) {
const postCardsData = result.body.sources.map((p) => {
return ({
abstract: p.description,
title: p.name,
image: p.urlsToLogos.small,
autherName: p.url,
postCardTitle: p.category
})
})
dispatch(requestPostCardsdata(postCardsData))
}
})
}
}
function progressFetchNews (searchParams) {
return new Promise((resolve, reject) => {
const apiUrl = `https://newsapi.org/v1/sources?category=${searchParams.category}`
request.get(apiUrl).end((err, res) => {
if (res) {
resolve(res)
return
}
if (err) {
reject(err)
return
}
})
})
}
export function toggleSearchForm () {
return (dispatch, getState) => {
dispatch(toggleSearchFormAction())
}
}
export function requestPostCardsData () {
return (dispatch, getState) => {
let fetching = progressFetchPostCardsdata()
fetching.then(result => {
if (result) {
dispatch(requestPostCardsdata(result.body))
}
})
}
}
function progressFetchPostCardsdata () {
return new Promise((resolve, reject) => {
const apiUrl = 'http://localhost:4000/api/data'
request.get(apiUrl).end((err, res) => {
if (res) {
resolve(res)
return
}
if (err) {
reject(err)
return
}
})
})
}
// ------------------------------------
// Reducer
// ------------------------------------
const intercomReducer = handleActions({
REQUEST_POSTCARDS_DATA: (state, action) => Object.assign({}, state, {
postCardsData: action.payload
}),
TOGGLE_BUTTOM_PLAYER: (state, action) => Object.assign({}, state, {
isShowButtonPlayer: !state.isShowButtonPlayer
}),
// TOGGLE_SEARCHFORM: (state, action) => Object.assign({}, state, {
// isRenderSearchForm: !state.isRenderSearchForm
// }),
SET_CATEGORY_VALUE: (state, action) => Object.assign({}, state, {
searchCategoryValue: action.payload
}),
SET_LANGUAGE_VALUE: (state, action) => Object.assign({}, state, {
searchLanguageValue: action.payload
})
}, INIT_INTERCOM_STATE)
export default intercomReducer
| {
"content_hash": "65a062cceeb37d55fc74a5862b81c176",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 85,
"avg_line_length": 28.6,
"alnum_prop": 0.6237224314147392,
"repo_name": "Donnzh/intercomBlog",
"id": "b22a5312e5e85624243c20544d7be972dcba2786",
"size": "3718",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/redux/modules/intercom.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6292"
},
{
"name": "HTML",
"bytes": "356"
},
{
"name": "JavaScript",
"bytes": "48641"
},
{
"name": "Vim script",
"bytes": "18831"
}
],
"symlink_target": ""
} |
div.dataTables_wrapper {
margin-bottom: 1.25em;
}
div.dataTables_length label,
div.dataTables_filter label,
div.dataTables_info {
color: #999;
font-weight: normal;
}
div.dataTables_length label {
float: left;
text-align: left;
margin-bottom: 0;
}
div.dataTables_length select {
width: 75px;
margin-bottom: 0;
}
div.dataTables_filter label {
float: right;
margin-bottom: 0;
}
div.dataTables_filter input {
display: inline-block !important;
width: auto !important;
margin-bottom: 0;
}
div.dataTables_info {
padding-top: 2px;
font-size: 0.875em;
}
div.dataTables_paginate {
float: right;
margin: 0;
}
table.dataTable {
clear: both;
margin: 0.5em 0 !important;
max-width: none !important;
width: 100%;
}
table.dataTable thead .sorting,
table.dataTable thead .sorting_asc,
table.dataTable thead .sorting_desc,
table.dataTable thead .sorting_asc_disabled,
table.dataTable thead .sorting_desc_disabled {
cursor: pointer;
*cursor: hand;
}
table.dataTable thead .sorting { background: url('images/sort_both.png') no-repeat center right; }
table.dataTable thead .sorting_asc { background: url('images/sort_asc.png') no-repeat center right; }
table.dataTable thead .sorting_desc { background: url('images/sort_desc.png') no-repeat center right; }
table.dataTable thead .sorting_asc_disabled { background: url('images/sort_asc_disabled.png') no-repeat center right; }
table.dataTable thead .sorting_desc_disabled { background: url('images/sort_desc_disabled.png') no-repeat center right; }
table.dataTable th:active {
outline: none;
}
/* Scrolling */
div.dataTables_scrollHead table {
margin-bottom: 0 !important;
}
div.dataTables_scrollBody table {
border-top: none;
margin-top: 0 !important;
margin-bottom: 0 !important;
}
div.dataTables_scrollBody tbody tr:first-child th,
div.dataTables_scrollBody tbody tr:first-child td {
border-top: none;
}
div.dataTables_scrollFoot table {
margin-top: 0 !important;
border-top: none;
}
/*
* TableTools styles
*/
.table tbody tr.active td,
.table tbody tr.active th {
background-color: #08C;
color: white;
}
.table tbody tr.active:hover td,
.table tbody tr.active:hover th {
background-color: #0075b0 !important;
}
.table-striped tbody tr.active:nth-child(odd) td,
.table-striped tbody tr.active:nth-child(odd) th {
background-color: #017ebc;
}
table.DTTT_selectable tbody tr {
cursor: pointer;
*cursor: hand;
}
div.DTTT {
float: left;
margin-bottom: 0;
}
div.DTTT .button:hover {
text-decoration: none !important;
}
ul.DTTT_dropdown.dropdown-menu li {
position: relative;
}
ul.DTTT_dropdown.dropdown-menu li:hover a {
background-color: #0088cc;
color: white !important;
}
/* TableTools information display */
.DTTT_print_info {
position: fixed;
top: 50%;
left: 50%;
width: 400px;
height: 150px;
margin-left: -200px;
margin-top: -75px;
text-align: center;
color: #333;
padding: 10px 30px;
background: #ffffff; /* Old browsers */
background: -webkit-linear-gradient(top, #ffffff 0%,#f3f3f3 89%,#f9f9f9 100%); /* Chrome10+,Safari5.1+ */
background: -moz-linear-gradient(top, #ffffff 0%,#f3f3f3 89%,#f9f9f9 100%); /* FF3.6+ */
background: -ms-linear-gradient(top, #ffffff 0%,#f3f3f3 89%,#f9f9f9 100%); /* IE10+ */
background: -o-linear-gradient(top, #ffffff 0%,#f3f3f3 89%,#f9f9f9 100%); /* Opera 11.10+ */
background: linear-gradient(top, #ffffff 0%,#f3f3f3 89%,#f9f9f9 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#f9f9f9',GradientType=0 ); /* IE6-9 */
opacity: 0.95;
border: 1px solid black;
border: 1px solid rgba(0, 0, 0, 0.5);
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
-ms-border-radius: 6px;
-o-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.5);
-moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.5);
-ms-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.5);
-o-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.5);
box-shadow: 0 3px 7px rgba(0, 0, 0, 0.5);
}
div.DTTT_print_info h6 {
font-weight: normal;
font-size: 28px;
line-height: 28px;
margin: 1em;
}
div.DTTT_print_info p {
font-size: 14px;
line-height: 20px;
}
/*
* FixedColumns styles
*/
div.DTFC_LeftHeadWrapper table,
div.DTFC_LeftFootWrapper table,
table.DTFC_Cloned tr.even {
background-color: white;
}
div.DTFC_LeftHeadWrapper table {
margin-bottom: 0 !important;
}
div.DTFC_LeftBodyWrapper table {
border-top: none;
margin-bottom: 0 !important;
}
div.DTFC_LeftBodyWrapper tbody tr:first-child th,
div.DTFC_LeftBodyWrapper tbody tr:first-child td {
border-top: none;
}
div.DTFC_LeftFootWrapper table {
border-top: none;
}
| {
"content_hash": "504c5aab4c8a06e3b3c5fc6adb854b5a",
"timestamp": "",
"source": "github",
"line_count": 218,
"max_line_length": 129,
"avg_line_length": 21.541284403669724,
"alnum_prop": 0.6978279386712095,
"repo_name": "usv-public/nubomedia-paas",
"id": "dead364d1d716593e6c0ab124e9a09fe44fbb341",
"size": "5304",
"binary": false,
"copies": "2",
"ref": "refs/heads/design",
"path": "src/main/resources/static/bower_components/datatables-plugins/integration/foundation/dataTables.foundation.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "92626"
},
{
"name": "HTML",
"bytes": "112235"
},
{
"name": "Java",
"bytes": "367053"
},
{
"name": "JavaScript",
"bytes": "2443226"
},
{
"name": "Shell",
"bytes": "12900"
}
],
"symlink_target": ""
} |
package com.facebook.buck.apple;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.shell.ShellStep;
import com.facebook.buck.step.ExecutionContext;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.nio.file.Path;
import java.util.List;
/**
* {@link ShellStep} implementation which invokes Apple's {@code ibtool} utility to compile {@code
* XIB} files to {@code NIB} files.
*/
class IbtoolStep extends ShellStep {
private final ProjectFilesystem filesystem;
private final ImmutableMap<String, String> environment;
private final ImmutableList<String> ibtoolCommand;
private final Path input;
private final Path output;
private final ImmutableList<String> additionalParams;
public IbtoolStep(
ProjectFilesystem filesystem,
ImmutableMap<String, String> environment,
List<String> ibtoolCommand,
List<String> additionalParams,
Path input,
Path output) {
super(filesystem.getRootPath());
this.filesystem = filesystem;
this.environment = environment;
this.ibtoolCommand = ImmutableList.copyOf(ibtoolCommand);
this.input = input;
this.output = output;
this.additionalParams = ImmutableList.copyOf(additionalParams);
}
@Override
protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
ImmutableList.Builder<String> commandBuilder = ImmutableList.builder();
commandBuilder.addAll(ibtoolCommand);
commandBuilder.add(
"--output-format", "human-readable-text", "--notices", "--warnings", "--errors");
commandBuilder.addAll(additionalParams);
commandBuilder.add(filesystem.resolve(output).toString(), filesystem.resolve(input).toString());
return commandBuilder.build();
}
@Override
public ImmutableMap<String, String> getEnvironmentVariables(ExecutionContext context) {
return environment;
}
@Override
public String getShortName() {
return "ibtool";
}
}
| {
"content_hash": "ce28c0fb3789e09404dac17d2fd70d5d",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 100,
"avg_line_length": 31.40625,
"alnum_prop": 0.7477611940298508,
"repo_name": "shybovycha/buck",
"id": "86a3660711be708da791c46f5e43e1685b8b967e",
"size": "2615",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/facebook/buck/apple/IbtoolStep.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "793"
},
{
"name": "Batchfile",
"bytes": "2215"
},
{
"name": "C",
"bytes": "257571"
},
{
"name": "C#",
"bytes": "237"
},
{
"name": "C++",
"bytes": "11922"
},
{
"name": "CSS",
"bytes": "54863"
},
{
"name": "D",
"bytes": "1017"
},
{
"name": "Go",
"bytes": "17354"
},
{
"name": "Groovy",
"bytes": "3362"
},
{
"name": "HTML",
"bytes": "9625"
},
{
"name": "Haskell",
"bytes": "971"
},
{
"name": "IDL",
"bytes": "385"
},
{
"name": "Java",
"bytes": "22166807"
},
{
"name": "JavaScript",
"bytes": "935614"
},
{
"name": "Kotlin",
"bytes": "19145"
},
{
"name": "Lex",
"bytes": "2731"
},
{
"name": "Limbo",
"bytes": "28"
},
{
"name": "Makefile",
"bytes": "1816"
},
{
"name": "Matlab",
"bytes": "47"
},
{
"name": "OCaml",
"bytes": "4384"
},
{
"name": "Objective-C",
"bytes": "146597"
},
{
"name": "Objective-C++",
"bytes": "34"
},
{
"name": "PowerShell",
"bytes": "244"
},
{
"name": "Prolog",
"bytes": "858"
},
{
"name": "Python",
"bytes": "1824359"
},
{
"name": "Roff",
"bytes": "1207"
},
{
"name": "Rust",
"bytes": "3618"
},
{
"name": "Scala",
"bytes": "5046"
},
{
"name": "Shell",
"bytes": "55323"
},
{
"name": "Smalltalk",
"bytes": "3296"
},
{
"name": "Standard ML",
"bytes": "15"
},
{
"name": "Swift",
"bytes": "9021"
},
{
"name": "Thrift",
"bytes": "32873"
},
{
"name": "Yacc",
"bytes": "323"
}
],
"symlink_target": ""
} |
package org.debezium.function;
@FunctionalInterface
public interface Callable {
void call();
} | {
"content_hash": "6af6eba76c0a45101967d5036cd658bf",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 30,
"avg_line_length": 14.285714285714286,
"alnum_prop": 0.76,
"repo_name": "rhauch/debezium-proto",
"id": "2d10fd5eabad49559f4f858a63dfb54314c82325",
"size": "279",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "debezium/src/main/java/org/debezium/function/Callable.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1226401"
},
{
"name": "Shell",
"bytes": "26743"
}
],
"symlink_target": ""
} |
#include <compiler.h>
#include <stdint.h>
/*
* Make a nice 8 byte aligned stack to run on before the threading system is up.
* Put it in the .bss.prebss.* section to make sure it doesn't get wiped
* when bss is cleared a little ways into boot.
*/
static uint8_t initial_stack[1024] __SECTION(".bss.prebss.initial_stack") __ALIGNED(8);
extern void _start(void);
extern void _nmi(void);
extern void _hardfault(void);
extern void _memmanage(void);
extern void _busfault(void);
extern void _usagefault(void);
extern void _svc(void);
extern void _debugmonitor(void);
extern void _pendsv(void);
extern void _systick(void);
#if defined(WITH_DEBUGGER_INFO)
extern struct __debugger_info__ _debugger_info;
#endif
const void * const __SECTION(".text.boot.vectab1") vectab[] = {
/* arm exceptions */
initial_stack + sizeof(initial_stack),
_start,
_nmi, // nmi
_hardfault, // hard fault
_memmanage, // mem manage
_busfault, // bus fault
_usagefault, // usage fault
0, // reserved
#if defined(WITH_DEBUGGER_INFO)
(void*) 0x52474244,
&_debugger_info,
#else
0, // reserved
0, // reserved
#endif
0, // reserved
_svc, // svcall
_debugmonitor, // debug monitor
0, // reserved
_pendsv, // pendsv
_systick, // systick
};
| {
"content_hash": "6d9640d26b844b26ceec13dbdc1c0a7c",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 87,
"avg_line_length": 23.245283018867923,
"alnum_prop": 0.6915584415584416,
"repo_name": "nvll/lk",
"id": "8c90cbe577cf41895e8df0c5b5c39b05ac98c68b",
"size": "2358",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "arch/arm/arm-m/vectab.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "140524"
},
{
"name": "C",
"bytes": "33314343"
},
{
"name": "C++",
"bytes": "2294446"
},
{
"name": "HTML",
"bytes": "235236"
},
{
"name": "Makefile",
"bytes": "105204"
},
{
"name": "Objective-C",
"bytes": "29412"
},
{
"name": "Python",
"bytes": "3907"
},
{
"name": "Shell",
"bytes": "4594"
},
{
"name": "Tcl",
"bytes": "288"
}
],
"symlink_target": ""
} |
// ----------------------------------------------------------------------------
// Copyright 2007-2011, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Description:
// Device Communication Server configuration (central registry for port usage)
// ----------------------------------------------------------------------------
// Change History:
// 2009/04/02 Martin D. Flynn
// -Initial release
// 2009/07/01 Martin D. Flynn
// -Added support for sending commands to the appropriate DCS.
// 2009/08/23 Martin D. Flynn
// -Added several additional common runtime property methods.
// 2009/09/23 Martin D. Flynn
// -Changed 'getSimulateDigitalInputs' to return a mask
// 2011/05/13 Martin D. Flynn
// -Added "getMinimumHDOP"
// 2011/08/21 Martin D. Flynn
// -Added "getIgnoreDeviceOdometer()"
// ----------------------------------------------------------------------------
package org.opengts.db;
import java.lang.*;
import java.util.*;
import java.io.*;
import java.net.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
import org.opengts.db.tables.*;
public class DCServerConfig
implements Comparable
{
// ------------------------------------------------------------------------
// flags
// default property group id
public static final String DEFAULT_PROP_GROUP_ID = "default";
// Boolean Properties
public static final String P_NONE = "none";
public static final String P_HAS_INPUTS = "hasInputs";
public static final String P_HAS_OUTPUTS = "hasOutputs";
public static final String P_COMMAND_SMS = "commandSms";
public static final String P_COMMAND_UDP = "commandUdp";
public static final String P_COMMAND_TCP = "commandTcp";
public static final String P_XMIT_TCP = "transmitTcp";
public static final String P_XMIT_UDP = "transmitUdp";
public static final String P_XMIT_SMS = "transmitSms";
public static final String P_XMIT_SAT = "transmitSat";
public static final String P_JAR_OPTIONAL = "jarOptional";
public static final long F_NONE = 0x00000000L;
public static final long F_HAS_INPUTS = 0x00000002L; // hasInputs
public static final long F_HAS_OUTPUTS = 0x00000004L; // hasOutputs
public static final long F_COMMAND_TCP = 0x00000100L; // commandTcp
public static final long F_COMMAND_UDP = 0x00000200L; // commandUdp
public static final long F_COMMAND_SMS = 0x00000400L; // commandSms
public static final long F_XMIT_TCP = 0x00001000L; // transmitTcp
public static final long F_XMIT_UDP = 0x00002000L; // transmitUdp
public static final long F_XMIT_SMS = 0x00004000L; // transmitSms
public static final long F_XMIT_SAT = 0x00008000L; // transmitSat
public static final long F_JAR_OPTIONAL = 0x00010000L; // jarOptional
public static final long F_STD_VEHICLE = F_HAS_INPUTS | F_HAS_OUTPUTS | F_XMIT_TCP | F_XMIT_UDP;
public static final long F_STD_PERSONAL = F_XMIT_TCP | F_XMIT_UDP;
public static long GetAttributeFlags(RTProperties rtp)
{
long flags = 0L;
if (rtp.getBoolean(P_HAS_INPUTS ,false)) { flags |= F_HAS_INPUTS ; }
if (rtp.getBoolean(P_HAS_OUTPUTS ,false)) { flags |= F_HAS_OUTPUTS ; }
if (rtp.getBoolean(P_COMMAND_SMS ,false)) { flags |= F_COMMAND_SMS ; }
if (rtp.getBoolean(P_COMMAND_UDP ,false)) { flags |= F_COMMAND_UDP ; }
if (rtp.getBoolean(P_COMMAND_TCP ,false)) { flags |= F_COMMAND_TCP ; }
if (rtp.getBoolean(P_XMIT_TCP ,false)) { flags |= F_XMIT_TCP ; }
if (rtp.getBoolean(P_XMIT_UDP ,false)) { flags |= F_XMIT_UDP ; }
if (rtp.getBoolean(P_XMIT_SMS ,false)) { flags |= F_XMIT_SMS ; }
if (rtp.getBoolean(P_XMIT_SAT ,false)) { flags |= F_XMIT_SAT ; }
if (rtp.getBoolean(P_JAR_OPTIONAL,false)) { flags |= F_JAR_OPTIONAL; }
return flags;
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
public enum CommandProtocol implements EnumTools.IsDefault, EnumTools.IntValue {
UDP(0,"udp"),
TCP(1,"tcp"),
SMS(2,"sms");
// ---
private int vv = 0;
private String ss = "";
CommandProtocol(int v, String s) { vv = v; ss = s; }
public int getIntValue() { return vv; }
public String toString() { return ss; }
public boolean isDefault() { return this.equals(UDP); }
public boolean isSMS() { return this.equals(SMS); }
};
/* get the CommandProtocol Enum valud, based on the value of the specified String */
public static CommandProtocol getCommandProtocol(String v)
{
// returns 'null' if protocol value is invalid
return EnumTools.getValueOf(CommandProtocol.class, v);
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Device event code to status code translation
**/
public static class EventCode
{
private int oldCode = 0;
private int statusCode = StatusCodes.STATUS_NONE;
private String dataString = null;
private long dataLong = Long.MIN_VALUE;
public EventCode(int oldCode, int statusCode, String data) {
this.oldCode = oldCode;
this.statusCode = statusCode;
this.dataString = data;
this.dataLong = StringTools.parseLong(data, Long.MIN_VALUE);
}
public int getCode() {
return this.oldCode;
}
public int getStatusCode() {
return this.statusCode;
}
public String getDataString(String dft) {
return !StringTools.isBlank(this.dataString)? this.dataString : dft;
}
public long getDataLong(long dft) {
return (this.dataLong != Long.MIN_VALUE)? this.dataLong : dft;
}
public String toString() {
return StringTools.toHexString(this.getCode(),16) + " ==> 0x" + StringTools.toHexString(this.getStatusCode(),16);
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/* Perl 'psjava' command (relative to GTS_HOME) */
private static final String PSJAVA_PERL = File.separator + "bin" + File.separator + "psjava";
/**
*** Returns the "psjava" command relative to GTS_HOME
*** @return The "psjava" command relative to GTS_HOME
**/
public static String getPSJavaCommand()
{
File psjava = FileTools.toFile(DBConfig.get_GTS_HOME(), new String[] {"bin","psjava"});
if (psjava != null) {
return psjava.toString();
} else {
return null;
}
}
/**
*** Returns the "psjava" command relative to GTS_HOME, and returning the
*** specified information for the named jar file
*** @param name The DCServerConfig name
*** @param display The type of information to return ("pid", "name", "user")
*** @return The returned 'display' information for the specified DCServerConfig
**/
public static String getPSJavaCommand_jar(String name, String display)
{
String psjava = DCServerConfig.getPSJavaCommand();
if (!StringTools.isBlank(psjava)) {
StringBuffer sb = new StringBuffer();
sb.append(psjava);
if (OSTools.isWindows()) {
sb.append(" \"-jar=").append(name).append(".jar\"");
if (!StringTools.isBlank(display)) {
sb.append(" \"-display="+display+"\"");
}
} else {
sb.append(" -jar=").append(name).append(".jar");
if (!StringTools.isBlank(display)) {
sb.append(" -display="+display+"");
}
}
return sb.toString();
} else {
return null;
}
}
/**
*** Returns the file path for the named running DCServerConfig jar files.<br>
*** This method will return 'null' if no DCServerConfig jar files with the specified
*** name are currently running.<br>
*** All matching running DCServerConfig entries will be returned.
*** @param name The DCServerConfig name
*** @return The matching running jar file paths, or null if no matching server enteries are running.
**/
public static File[] getRunningJarPath(String name)
{
if (OSTools.isLinux() || OSTools.isMacOS()) {
try {
String cmd = DCServerConfig.getPSJavaCommand_jar(name,"name");
Process process = (cmd != null)? Runtime.getRuntime().exec(cmd) : null;
if (process != null) {
BufferedReader procReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuffer sb = new StringBuffer();
for (;;) {
String line = procReader.readLine();
if (line == null) { break; }
sb.append(StringTools.trim(line));
}
process.waitFor();
procReader.close();
int exitVal = process.exitValue();
if (exitVal == 0) {
String jpath[] = StringTools.split(sb.toString(), '\n');
java.util.List<File> jpl = new Vector<File>();
for (int i = 0; i < jpath.length; i++) {
if (StringTools.isBlank(jpath[i])) { continue; }
File jarPath = new File(sb.toString());
try {
jpl.add(jarPath.getCanonicalFile());
} catch (Throwable th) {
jpl.add(jarPath);
}
}
if (!ListTools.isEmpty(jpl)) {
return jpl.toArray(new File[jpl.size()]);
}
}
} else {
if (StringTools.isBlank(cmd)) {
Print.logWarn("Unable to create 'psjava' command for '"+name+"'");
} else {
Print.logError("Unable to execute command: " + cmd);
}
}
} catch (Throwable th) {
Print.logException("Unable to determine if Tomcat is running:", th);
}
return null;
} else {
// not supported on Windows
return null;
}
}
/**
*** Return log file paths from jar file paths
**/
public static File getLogFilePath(File jarPath)
{
if (jarPath != null) {
// "/usr/local/GTS_1.2.3/build/lib/enfora.jar"
String jarName = jarPath.getName();
if (jarName.endsWith(".jar")) {
String name = jarName.substring(0,jarName.length()-4);
File logDir = new File(jarPath.getParentFile().getParentFile().getParentFile(), "logs");
if (logDir.isDirectory()) {
return new File(logDir, name + ".log");
}
}
}
return null;
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
public static class EventDataAnalogField
{
private int index = 0;
private double gain = 1.0 / (double)(1L << 10); // default 10-bit analog
private double offset = 0.0;
private DBField dbField = null;
public EventDataAnalogField(int ndx, double gain, double offset) {
this(ndx, gain, offset, null);
}
public EventDataAnalogField(int ndx, double gain, double offset, String fieldN) {
this.index = ndx;
this.gain = gain;
this.offset = offset;
this.setFieldName(fieldN);
Print.logInfo("New AnalogField["+this.index+"]: " + this);
}
public EventDataAnalogField(int ndx, String gof, double dftGain, double dftOffset) {
this.index = ndx;
String v[] = StringTools.split(gof,',');
this.gain = (v.length >= 1)? StringTools.parseDouble(v[0],dftGain ) : dftGain;
this.offset = (v.length >= 2)? StringTools.parseDouble(v[1],dftOffset) : dftOffset;
this.setFieldName((v.length >= 3)? StringTools.blankDefault(v[2],null) : null);
Print.logInfo("New AnalogField["+this.index+"]: " + this);
}
public int getIndex() {
return this.index;
}
public void setGain(double gain) {
this.gain = gain;
}
public double getGain() {
return this.gain;
}
public void setOffset(double offset) {
this.offset = offset;
}
public double getOffset() {
return this.offset;
}
public double convert(long value) {
return this.convert((double)value);
}
public double convert(double value) {
return (value * this.gain) + this.offset;
}
public void setFieldName(String fieldN) {
this.dbField = null;
if (!StringTools.isBlank(fieldN)) {
DBField dbf = EventData.getFactory().getField(fieldN);
if (dbf == null) {
Print.logError("**** EventData analog field does not exist: " + fieldN);
} else {
this.dbField = dbf;
Object val = this.getValueObject(0.0);
if (val == null) {
Print.logError("**** EventData field type not supported: " + fieldN);
this.dbField = null;
}
}
}
}
public DBField getDBField() {
return this.dbField;
}
public String getFieldName() {
return (this.dbField != null)? this.dbField.getName() : null;
}
public Object getValueObject(double value) {
// DBField
DBField dbf = this.getDBField();
if (dbf == null) {
return null;
}
// convert to type
Class dbfc = dbf.getTypeClass();
if (dbfc == String.class) {
return String.valueOf(value);
} else
if ((dbfc == Integer.class) || (dbfc == Integer.TYPE)) {
return new Integer((int)value);
} else
if ((dbfc == Long.class) || (dbfc == Long.TYPE )) {
return new Long((long)value);
} else
if ((dbfc == Float.class) || (dbfc == Float.TYPE )) {
return new Float((float)value);
} else
if ((dbfc == Double.class) || (dbfc == Double.TYPE )) {
return new Double(value);
} else
if ((dbfc == Boolean.class) || (dbfc == Boolean.TYPE)) {
return new Boolean(value != 0.0);
}
return null;
}
public boolean saveEventDataFieldValue(EventData evdb, double value) {
if (evdb != null) {
Object objVal = this.getValueObject(value); // null if no dbField
if (objVal != null) {
String fn = this.getFieldName();
boolean ok = evdb.setFieldValue(fn, objVal);
Print.logInfo("Set AnalogField["+this.getIndex()+"]: "+fn+" ==> " + (ok?evdb.getFieldValue(fn):"n/a"));
return ok;
}
}
return false;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("index=" ).append(this.getIndex());
sb.append(" gain=" ).append(this.getGain());
sb.append(" offset=").append(this.getOffset());
sb.append(" field=" ).append(this.getFieldName());
return sb.toString();
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
public static final String COMMAND_CONFIG = "config"; // arg=deviceCommandString
public static final String COMMAND_PING = "ping"; // arg=commandID
//public static final String COMMAND_OUTPUT = "output"; // arg=gpioOutputState
public static final String COMMAND_GEOZONE = "geozone"; // arg=""
public static final String DEFAULT_ARG_NAME = "arg";
public class Command
{
private String name = null;
private String desc = null;
private String types[] = null;
private String aclName = "";
private AclEntry.AccessLevel aclDft = AclEntry.AccessLevel.WRITE;
private String cmdStr = "";
private boolean hasArgs = false;
private String cmdProto = null;
private String protoHandlr = null;
private boolean expectAck = false;
private int cmdStCode = StatusCodes.STATUS_NONE;
private OrderedMap<String,CommandArg> argMap = null;
public Command(
String name, String desc,
String types[], String aclName, AclEntry.AccessLevel aclDft,
String cmdStr, boolean hasArgs, Collection<CommandArg> cmdArgs,
String cmdProtoH, boolean expectAck,
int cmdStCode) {
this.name = StringTools.trim(name);
this.desc = StringTools.trim(desc);
this.types = (types != null)? types : new String[0];
this.aclName = StringTools.trim(aclName);
this.aclDft = (aclDft != null)? aclDft : AclEntry.AccessLevel.WRITE;
this.cmdStr = (cmdStr != null)? cmdStr : "";
this.hasArgs = hasArgs || (this.cmdStr.indexOf("${") >= 0);
cmdProtoH = StringTools.trim(cmdProtoH);
if (cmdProtoH.indexOf(":") >= 0) {
int p = cmdProtoH.indexOf(":");
this.cmdProto = StringTools.trim(cmdProtoH.substring(0,p));
this.protoHandlr = StringTools.trim(cmdProtoH.substring(p+1));
} else {
this.cmdProto = cmdProtoH;
this.protoHandlr = null;
}
this.expectAck = expectAck;
this.cmdStCode = (cmdStCode > 0)? cmdStCode : StatusCodes.STATUS_NONE;
if (!ListTools.isEmpty(cmdArgs) && this.hasArgs) {
this.argMap = new OrderedMap<String,CommandArg>();
for (CommandArg arg : cmdArgs) {
arg.setCommand(this);
this.argMap.put(arg.getName(),arg);
}
}
}
public DCServerConfig getDCServerConfig() {
return DCServerConfig.this;
}
public String getName() {
return this.name; // not null
}
public String getDescription() {
return this.desc; // not null
}
public String[] getTypes() {
return this.types;
}
public boolean isType(String type) {
return ListTools.contains(this.types, type);
}
public String getAclName() {
return this.aclName; // not null
}
public AclEntry.AccessLevel getAclAccessLevelDefault() {
return this.aclDft; // not null
}
public String getCommandString() {
return this.cmdStr; // not null
}
public String getCommandString(String cmdArgs[]) {
String cs = this.getCommandString();
if (this.hasCommandArgs()) {
final String args[] = (cmdArgs != null)? cmdArgs : new String[0];
return StringTools.replaceKeys(cs, new StringTools.KeyValueMap() {
public String getKeyValue(String key, String notUsed, String dft) {
int argNdx = (Command.this.argMap != null)? Command.this.argMap.indexOfKey(key) : -1;
if ((argNdx >= 0) && (argNdx < args.length)) {
return (args[argNdx] != null)? args[argNdx] : dft;
} else
if (key.equals(DEFAULT_ARG_NAME)) {
return ((args.length > 0) && (args[0] != null))? args[0] : dft;
} else {
for (int i = 0; i < args.length; i++) {
if (key.equals(DEFAULT_ARG_NAME+i)) { // "arg0", "arg1", ...
return (args[i] != null)? args[i] : dft;
}
}
return dft;
}
}
});
}
return cs;
}
public boolean hasCommandArgs() {
//return (this.cmdStr != null)? (this.cmdStr.indexOf("${arg") >= 0) : false;
return this.hasArgs;
}
public int getArgCount() {
if (!this.hasArgs) {
return 0;
} else
if (this.argMap != null) {
return this.argMap.size();
} else {
return 1;
}
}
public CommandArg getCommandArg(int argNdx) {
if (this.hasArgs && (this.argMap != null)) {
return this.argMap.getValue(argNdx);
} else {
return null;
}
}
public CommandProtocol getCommandProtocol() {
return this.getCommandProtocol(null);
}
public CommandProtocol getCommandProtocol(CommandProtocol dftProto) {
if (!StringTools.isBlank(this.cmdProto)) {
// may return null if cmdProto is not one of the valid values
return DCServerConfig.getCommandProtocol(this.cmdProto);
} else {
return dftProto;
}
}
public boolean isCommandProtocolSMS() {
CommandProtocol proto = this.getCommandProtocol(null);
return ((proto != null) && proto.isSMS());
}
public String getCommandProtocolHandler() {
return this.protoHandlr; // may be null
}
public boolean getExpectAck() {
return this.expectAck;
}
public int getStatusCode() {
return this.cmdStCode;
}
}
public static class CommandArg
{ // static because the 'Args' are initialized before the 'Command' is
private Command command = null; // The command that owns this arg
private String name = null; // This argument name
private String desc = null; // This argument description
private boolean readOnly = false;
private String resKey = null;
private String dftVal = "";
private int lenDisp = 70;
private int lenMax = 500;
public CommandArg(String name, String desc, boolean readOnly, String resKey, String dftVal) {
this.name = StringTools.trim(name);
this.desc = StringTools.trim(desc);
this.readOnly = readOnly;
this.resKey = !StringTools.isBlank(resKey)? resKey : null;
this.dftVal = StringTools.trim(dftVal);
}
public String getName() {
return this.name;
}
public String getDescription() {
return this.desc;
}
public boolean isReadOnly() {
return this.readOnly;
}
public void setCommand(Command cmd) {
this.command = cmd;
}
public Command getCommand() {
return this.command;
}
public String getResourceName() {
return this.resKey;
// ie. "DCServerConfig.enfora.DriverMessage.arg"
/*
StringBuffer sb = new StringBuffer();
sb.append("DCServerConfig.");
sb.append(cmd.getDCServerConfig().getName());
sb.append(".");
sb.append(cmd.getName());
sb.append(".");
sb.append(this.getName());
return sb.toString();
*/
}
public String getDefaultValue() {
return this.dftVal;
}
public void setLength(int dispLen, int maxLen) {
this.lenDisp = (dispLen > 0)? dispLen : 70;
this.lenMax = (maxLen > 0)? maxLen : (this.lenDisp * 2);
}
public int getDisplayLength() {
return this.lenDisp;
}
public int getMaximumLength() {
return this.lenMax;
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** FuelLevelProfile class
**/
public static class FuelLevelProfile
{
// 0,0|1,1
private double evtLevel = 0.0;
private double actLevel = 0.0;
public FuelLevelProfile(String lvl) {
if (!StringTools.isBlank(lvl)) {
String L[] = StringTools.split(lvl,',');
if (ListTools.size(L) >= 2) {
this.evtLevel = StringTools.parseDouble(L[0],-1.0);
this.actLevel = StringTools.parseDouble(L[1],-1.0);
if ((this.evtLevel < 0.0) || (this.evtLevel > 1.0) ||
(this.actLevel < 0.0) || (this.actLevel > 1.0) ) {
Print.logError("Invalid FuelLevelProfile value: " + lvl);
this.evtLevel = 0.0;
this.actLevel = 0.0;
}
}
}
}
public FuelLevelProfile(double evLvl, double acLvl) {
this.evtLevel = evLvl;
this.actLevel = acLvl;
}
public double getEventLevel() {
return this.evtLevel;
}
public double getActualLevel() {
return this.actLevel;
}
}
/**
*** Parse the FuelLevelProfile String
*** @param profile The string containing the fuel-level profile
*** @return An array of FuelLevelProfile entries
**/
public static FuelLevelProfile[] ParseFuelLevelProfile(String profile)
{
String p[] = StringTools.split(profile,'|');
FuelLevelProfile flp[] = new FuelLevelProfile[p.length];
for (int i = 0; i < p.length; i++) {
flp[i] = new FuelLevelProfile(p[i]);
}
return flp;
}
/**
*** Adjust the event fuel-level based on the specified profile
*** @param fuelLevel The event fuel-level to adjust
*** @param flp The FuelLevelProfile array used to adjust the fuel-level
*** @return The adjusted fuel-level
**/
public static double adjustFuelLevelProfile(double fuelLevel, FuelLevelProfile flp[])
{
double FL = fuelLevel;
if (!ListTools.isEmpty(flp)) {
FuelLevelProfile hi = null;
FuelLevelProfile lo = null;
for (int i = 0; i < flp.length; i++) {
if (flp[i].getEventLevel() == FL) {
hi = flp[i];
lo = flp[i];
break;
} else
if (flp[i].getEventLevel() >= FL) {
hi = flp[i];
lo = (i > 0)? flp[i - 1] : null;
break;
}
}
if ((hi != null) && (lo != null)) {
double evHi = hi.getEventLevel();
double evLo = lo.getEventLevel();
double evD = (FL - evLo) / (evHi - evLo);
double acHi = hi.getActualLevel();
double acLo = lo.getActualLevel();
FL = acLo + (evD * (acHi - acLo));
}
}
return FL;
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
private String dcName = "";
private String dcDesc = "";
private String uniquePrefix[] = null;
private boolean useSSL = false;
private OrderedMap<Integer,InetAddress> tcpPortMap = null;
private OrderedMap<Integer,InetAddress> udpPortMap = null;
private boolean customCodeEnabled = true;
private Map<Object,EventCode> customCodeMap = new HashMap<Object,EventCode>();
private String commandHost = null;
private int commandPort = 0;
private CommandProtocol commandProtocol = null;
private long attrFlags = F_NONE;
private Map<String,RTProperties> rtPropsMap = new OrderedMap<String,RTProperties>();
private String commandsAclName = null;
private AclEntry.AccessLevel commandsAccessLevelDft = null;
private OrderedMap<String,Command> commandMap = null;
/**
*** Blank Constructor
**/
public DCServerConfig()
{
this.getDefaultProperties();
this.setName("unregistered");
this.setDescription("Unregistered DCS");
this.setAttributeFlags(F_NONE);
this.setUseSSL(false);
this.setTcpPorts(null, null, false);
this.setUdpPorts(null, null, false);
this.setCommandDispatcherPort(0);
this.setUniquePrefix(null);
this._postInit();
}
/**
*** Constructor
**/
public DCServerConfig(String name, String desc, int tcpPorts[], int udpPorts[], int commandPort, long flags, String... uniqPfx)
{
this.getDefaultProperties();
this.setName(name);
this.setDescription(desc);
this.setAttributeFlags(flags);
this.setUseSSL(false);
this.setTcpPorts(null, tcpPorts, true);
this.setUdpPorts(null, udpPorts, true);
this.setCommandDispatcherPort(commandPort, true);
this.setUniquePrefix(uniqPfx);
this._postInit();
}
private void _postInit()
{
// etc.
}
// ------------------------------------------------------------------------
/**
*** Sets the server name/id
**/
protected void setName(String n)
{
this.dcName = StringTools.trim(n);
}
/**
*** Gets the server name/id
**/
public String getName()
{
return this.dcName;
}
// ------------------------------------------------------------------------
/**
*** Sets the server description
**/
public void setDescription(String d)
{
this.dcDesc = StringTools.trim(d);
}
/**
*** Gets the server description
**/
public String getDescription()
{
return this.dcDesc;
}
// ------------------------------------------------------------------------
/**
*** Sets the server attribute flags
**/
public void setAttributeFlags(long f)
{
this.attrFlags = f;
}
/**
*** Gets the server attribute flags
**/
public long getAttributeFlags()
{
return this.attrFlags;
}
/**
*** Returns true if the indicate mask is non-zero
**/
public boolean isAttributeFlag(long mask)
{
return ((this.getAttributeFlags() & mask) != 0L);
}
// ------------------------------------------------------------------------
/**
*** Gets an array of server ports from the specified runtime keys.
*** (first check command-line, then config file, then default)
*** @param name The server name
*** @param rtPropKey The runtime key names
*** @param dft The default array of server ports if not defined otherwise
*** @return The array of server ports
**/
private int[] _getServerPorts(
String cmdLineKey[],
String rtPropKey[],
int dft[])
{
String portStr[] = null;
/* check command-line override */
RTProperties cmdLineProps = RTConfig.getCommandLineProperties();
if ((cmdLineProps != null) && cmdLineProps.hasProperty(cmdLineKey)) {
portStr = cmdLineProps.getStringArray(cmdLineKey, null);
}
/* check runtime config override */
if (ListTools.isEmpty(portStr)) {
String ak[] = this.normalizeKeys(rtPropKey); // "tcpPort" ==> "enfora.tcpPort"
if (!this.hasProperty(ak,false)) { // exclude 'defaults'
// no override defined
return dft;
}
portStr = this.getStringArrayProperty(ak, null);
if (ListTools.isEmpty(portStr)) {
// ports explicitly removed
//Print.logInfo(name + ": Returning 'null' ports");
return null;
}
}
/* parse/return port numbers */
int p = 0;
int srvPorts[] = new int[portStr.length];
for (int i = 0; i < portStr.length; i++) {
int port = StringTools.parseInt(portStr[i], 0);
if (ServerSocketThread.isValidPort(port)) {
srvPorts[p++] = port;
}
}
if (p < srvPorts.length) {
// list contains invalid port numbers
int newPorts[] = new int[p];
System.arraycopy(srvPorts, 0, newPorts, 0, p);
srvPorts = newPorts;
}
if (!ListTools.isEmpty(srvPorts)) {
//Print.logInfo(name + ": Returning server ports: " + StringTools.join(srvPorts,","));
return srvPorts;
} else {
//Print.logInfo(name + ": Returning 'null' ports");
return null;
}
}
// ------------------------------------------------------------------------
/**
*** Sets whether to use SSL on TCP connections
**/
public void setUseSSL(boolean useSSL)
{
this.useSSL = useSSL;
}
/**
*** Gets whether to use SSL on TCP connections
**/
public boolean getUseSSL()
{
return this.useSSL;
}
// ------------------------------------------------------------------------
/**
*** Sets the default TCP port for this server
**/
public void setTcpPorts(InetAddress bindAddr, int tcp[], boolean checkRTP)
{
if (checkRTP) {
tcp = this._getServerPorts(
DCServerFactory.ARG_tcpPort,
DCServerFactory.CONFIG_tcpPort(this.getName()),
tcp);
}
if (!ListTools.isEmpty(tcp)) {
if (this.tcpPortMap == null) { this.tcpPortMap = new OrderedMap<Integer,InetAddress>(); }
for (int i = 0; i < tcp.length; i++) {
Integer p = new Integer(tcp[i]);
if (this.tcpPortMap.containsKey(p)) {
Print.logWarn("TCP port already defined ["+this.getName()+"]: " + p);
}
this.tcpPortMap.put(p, bindAddr);
}
}
}
/**
*** Get TCP Port bind address
**/
public InetAddress getTcpPortBindAddress(int port)
{
InetAddress bind = (this.tcpPortMap != null)? this.tcpPortMap.get(new Integer(port)) : null;
return (bind != null)? bind : ServerSocketThread.getDefaultBindAddress();
}
/**
*** Gets the default TCP port for this server
**/
public int[] getTcpPorts()
{
if (ListTools.isEmpty(this.tcpPortMap)) {
return null;
} else {
int ports[] = new int[this.tcpPortMap.size()];
for (int i = 0; i < ports.length; i++) {
ports[i] = this.tcpPortMap.getKey(i).intValue();
}
return ports;
}
}
/**
*** Create TCP ServerSocketThread
**/
public ServerSocketThread createServerSocketThread_TCP(int port)
throws SocketException, IOException
{
boolean useSSL = this.getUseSSL();
return this.createServerSocketThread_TCP(port, useSSL);
}
/**
*** Create TCP ServerSocketThread
**/
public ServerSocketThread createServerSocketThread_TCP(int port, boolean useSSL)
throws SocketException, IOException
{
InetAddress bindAddr = this.getTcpPortBindAddress(port);
return new ServerSocketThread(bindAddr, port, useSSL);
}
// ------------------------------------------------------------------------
/**
*** Sets the default UDP port for this server
**/
public void setUdpPorts(InetAddress bindAddr, int udp[], boolean checkRTP)
{
if (checkRTP) {
udp = this._getServerPorts(
DCServerFactory.ARG_udpPort,
DCServerFactory.CONFIG_udpPort(this.getName()),
udp);
}
if (!ListTools.isEmpty(udp)) {
if (this.udpPortMap == null) { this.udpPortMap = new OrderedMap<Integer,InetAddress>(); }
for (int i = 0; i < udp.length; i++) {
Integer p = new Integer(udp[i]);
if (this.udpPortMap.containsKey(p)) {
Print.logWarn("UDP port already defined ["+this.getName()+"]: " + p);
}
this.udpPortMap.put(p, bindAddr);
//Print.logInfo("Setting UDP listener at " + StringTools.blankDefault(bindAddr,"<ALL>") + " : " + p);
}
}
}
/**
*** Get UDP Port bind address
**/
public InetAddress getUdpPortBindAddress(int port)
{
InetAddress bind = (this.udpPortMap != null)? this.udpPortMap.get(new Integer(port)) : null;
return (bind != null)? bind : ServerSocketThread.getDefaultBindAddress();
}
/**
*** Gets the default UDP port for this server
**/
public int[] getUdpPorts()
{
if (ListTools.isEmpty(this.udpPortMap)) {
return null;
} else {
int ports[] = new int[this.udpPortMap.size()];
for (int i = 0; i < ports.length; i++) {
ports[i] = this.udpPortMap.getKey(i).intValue();
}
return ports;
}
}
/**
*** Create UDP ServerSocketThread
**/
public ServerSocketThread createServerSocketThread_UDP(int port)
throws SocketException, IOException
{
InetAddress bindAddr = this.getUdpPortBindAddress(port);
return new ServerSocketThread(ServerSocketThread.createDatagramSocket(bindAddr, port));
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Start Command Listener
*** @param port The listen port
*** @param handler The command handler class
**/
public static ServerSocketThread startCommandHandler(int port, Class handler)
throws Throwable
{
ServerSocketThread sst = null;
/* create server socket */
try {
sst = new ServerSocketThread(port);
} catch (Throwable t) { // trap any server exception
Print.logException("ServerSocket error", t);
throw t;
}
/* initialize */
sst.setTextPackets(true);
sst.setBackspaceChar(null); // no backspaces allowed
sst.setLineTerminatorChar(new int[] { '\r', '\n' });
sst.setIgnoreChar(null);
sst.setMaximumPacketLength(1024); // safety net
sst.setMinimumPacketLength(1);
sst.setIdleTimeout(1000L); // time between packets
sst.setPacketTimeout(1000L); // time from start of packet to packet completion
sst.setSessionTimeout(5000L); // time for entire session
sst.setLingerTimeoutSec(5);
sst.setTerminateOnTimeout(true);
sst.setClientPacketHandlerClass(handler);
/* start thread */
DCServerConfig.startServerSocketThread(sst,"Command");
return sst;
}
/**
*** Start ServerSocketThread
*** @param sst The ServerSocketThread to start
*** @param type The short 'type' name of the socket listener
**/
public static void startServerSocketThread(ServerSocketThread sst, String type)
{
if (sst != null) {
String m = StringTools.trim(type);
int port = sst.getLocalPort();
String bindAddr = StringTools.blankDefault(sst.getBindAddress(), "(ALL)");
if (bindAddr.startsWith("/")) { bindAddr = bindAddr.substring(1); }
if (sst.getServerSocket() != null) {
// TCP
long tmo = sst.getSessionTimeout();
Print.logInfo("Starting "+m+" Listener (TCP) - " +port+ " [" +bindAddr+ "] timeout="+tmo+"ms ...");
} else
if (sst.getDatagramSocket() != null) {
// UDP
Print.logInfo("Starting "+m+" Listener (UDP) - " +port+ " [" +bindAddr+ "] ...");
} else {
Print.logStackTrace("ServerSocketThread is invalid!");
}
sst.start();
} else {
Print.logStackTrace("ServerSocketThread is null!");
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Returns an array of all TCP/UDP 'listen' ports
*** @return An array of all TCP/UDP 'listen' ports
**/
public int[] getListenPorts()
{
if (ListTools.isEmpty(this.tcpPortMap)) {
return this.getUdpPorts(); // may still be null/empty
} else
if (ListTools.isEmpty(this.udpPortMap)) {
return this.getTcpPorts(); // may still be null/empty
} else {
java.util.List<Integer> portList = new Vector<Integer>();
int tcpPorts[] = this.getTcpPorts();
for (int t = 0; t < tcpPorts.length; t++) {
Integer tcp = new Integer(tcpPorts[t]);
portList.add(tcp);
}
int udpPorts[] = this.getUdpPorts();
for (int u = 0; u < udpPorts.length; u++) {
Integer udp = new Integer(udpPorts[u]);
if (!portList.contains(udp)) {
portList.add(udp);
}
}
int ports[] = new int[portList.size()];
for (int p = 0; p < portList.size(); p++) {
ports[p] = portList.get(p).intValue();
}
return ports;
}
}
// ------------------------------------------------------------------------
/**
*** Load device record from unique-id (not yet used/tested)
*** @param modemID The unique modem ID (IMEI, ESN, etc)
*** @return The Device record
**/
public Device loadDeviceUniqueID(String modemID)
{
return DCServerFactory.loadDeviceByPrefixedModemID(this.getUniquePrefix(), modemID);
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Returns true if the named server is defined
**/
public boolean serverJarExists()
{
return DCServerFactory.serverJarExists(this.getName());
}
/**
*** Returns true if this DCS requires a Jar file
**/
public boolean isJarOptional()
{
return this.isAttributeFlag(F_JAR_OPTIONAL);
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Sets the command protocol to use when communicating with remote devices
*** @param proto The CommandProtocol
**/
public void setCommandProtocol(String proto)
{
this.commandProtocol = DCServerConfig.getCommandProtocol(proto);
}
/**
*** Sets the command protocol to use when communicating with remote devices
*** @param proto The CommandProtocol
**/
public void setCommandProtocol(CommandProtocol proto)
{
this.commandProtocol = proto;
}
/**
*** Gets the command protocol to use when communicating with remote devices
*** @return The Command Protocol
**/
public CommandProtocol getCommandProtocol()
{
return (this.commandProtocol != null)? this.commandProtocol : CommandProtocol.UDP;
}
/**
*** Gets the "Client Command Port"
*** @param dft The default Client Command Port
*** @return The Client Command Port
**/
public int getClientCommandPort_udp(int dft)
{
return this.getIntProperty(DCServerFactory.CONFIG_clientCommandPort_udp(this.getName()), dft);
}
/**
*** Gets the "Client Command Port"
*** @param dft The default Client Command Port
*** @return The Client Command Port
**/
public int getClientCommandPort_tcp(int dft)
{
return this.getIntProperty(DCServerFactory.CONFIG_clientCommandPort_tcp(this.getName()), dft);
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Gets the "ACK Response Port"
*** @param dft The ACK response port
*** @return The ack response port
**/
public int getAckResponsePort(int dft)
{
return this.getIntProperty(DCServerFactory.CONFIG_ackResponsePort(this.getName()), dft);
}
/**
*** Gets the "ACK Response Port"
*** @param dcss The DCServerConfig instance
*** @param dft The ACK response port
*** @return The ack response port
**/
public static int getAckResponsePort(DCServerConfig dcsc, int dft)
{
return (dcsc != null)? dcsc.getAckResponsePort(dft) : dft;
}
// ------------------------------------------------------------------------
/**
*** Gets the "TCP idle timeout"
*** @param dft The default timeout value
*** @return The default timeout value
**/
public long getTcpIdleTimeoutMS(long dft)
{
return this.getLongProperty(DCServerFactory.CONFIG_tcpIdleTimeoutMS(this.getName()), dft);
}
/**
*** Gets the "TCP packet timeout"
*** @param dft The default timeout value
*** @return The default timeout value
**/
public long getTcpPacketTimeoutMS(long dft)
{
return this.getLongProperty(DCServerFactory.CONFIG_tcpPacketTimeoutMS(this.getName()), dft);
}
/**
*** Gets the "TCP session timeout"
*** @param dft The default timeout value
*** @return The default timeout value
**/
public long getTcpSessionTimeoutMS(long dft)
{
return this.getLongProperty(DCServerFactory.CONFIG_tcpSessionTimeoutMS(this.getName()), dft);
}
// ------------------------------------------------------------------------
/**
*** Gets the "UDP idle timeout"
*** @param dft The default timeout value
*** @return The default timeout value
**/
public long getUdpIdleTimeoutMS(long dft)
{
return this.getLongProperty(DCServerFactory.CONFIG_udpIdleTimeoutMS(this.getName()), dft);
}
/**
*** Gets the "UDP packet timeout"
*** @param dft The default timeout value
*** @return The default timeout value
**/
public long getUdpPacketTimeoutMS(long dft)
{
return this.getLongProperty(DCServerFactory.CONFIG_udpPacketTimeoutMS(this.getName()), dft);
}
/**
*** Gets the "UDP session timeout"
*** @param dft The default timeout value
*** @return The default timeout value
**/
public long getUdpSessionTimeoutMS(long dft)
{
return this.getLongProperty(DCServerFactory.CONFIG_udpSessionTimeoutMS(this.getName()), dft);
}
// ------------------------------------------------------------------------
/**
*** Gets the array of allowed UniqueID prefixes
*** @param dftPfx The default list of prefixes
*** @return The array of allowed UniqueID prefixes
**/
public String[] getUniquePrefix(String dftPfx[])
{
if (ListTools.isEmpty(this.uniquePrefix)) {
// set non-empty default
this.uniquePrefix = !ListTools.isEmpty(dftPfx)? dftPfx : new String[] { "" };
}
return this.uniquePrefix;
}
/**
*** Gets the array of allowed UniqueID prefixes
*** @return The array of allowed UniqueID prefixes
**/
public String[] getUniquePrefix()
{
return this.getUniquePrefix(null);
}
/**
*** Sets the array of allowed UniqueID prefixes
*** @param pfx The default UniqueID prefixes
**/
public void setUniquePrefix(String pfx[])
{
if (!ListTools.isEmpty(pfx)) {
for (int i = 0; i < pfx.length; i++) {
String p = pfx[i].trim();
if (p.equals("<blank>") || p.equals("*")) {
p = "";
} else
if (p.endsWith("*")) {
p = p.substring(0, p.length() - 1);
}
pfx[i] = p;
}
this.uniquePrefix = pfx;
} else {
this.uniquePrefix = new String[] { "" };;
}
}
// ------------------------------------------------------------------------
/**
*** Gets the "Minimum Moved Meters"
*** @param dft The default minimum distance
*** @return The Minimum Moved Meters
**/
public double getMinimumMovedMeters(double dft)
{
return this.getDoubleProperty(DCServerFactory.CONFIG_minimumMovedMeters(this.getName()), dft);
}
/**
*** Gets the "Minimum Moved Meters"
*** @param dcsc The DCServerConfig instance
*** @param dft The default minimum distance
*** @return The Minimum Moved Meters
**/
public static double getMinimumMovedMeters(DCServerConfig dcsc, double dft)
{
return (dcsc != null)? dcsc.getMinimumMovedMeters(dft) : dft;
}
// ------------------------------------------------------------------------
/**
*** Gets the "Minimum Speed KPH"
*** @param dft The default minimum speed
*** @return The Minimum Speed KPH
**/
public double getMinimumSpeedKPH(double dft)
{
return this.getDoubleProperty(DCServerFactory.CONFIG_minimumSpeedKPH(this.getName()), dft);
}
/**
*** Gets the "Minimum Speed KPH"
*** @param dcsc The DCServerConfig instance
*** @param dft The default minimum speed
*** @return The Minimum Speed KPH
**/
public static double getMinimumSpeedKPH(DCServerConfig dcsc, double dft)
{
return (dcsc != null)? dcsc.getMinimumSpeedKPH(dft) : dft;
}
// ------------------------------------------------------------------------
/**
*** Gets the "Estimate Odometer" flag
*** @param dft The default estimate odometer flag
*** @return The Estimate Odometer flag
**/
public boolean getEstimateOdometer(boolean dft)
{
return this.getBooleanProperty(DCServerFactory.CONFIG_estimateOdometer(this.getName()), dft);
}
/**
*** Gets the "Estimate Odometer" flag
*** @param dcsc The DCServerConfig instance
*** @param dft The default estimate odometer flag
*** @return The Estimate Odometer flag
**/
public static boolean getEstimateOdometer(DCServerConfig dcsc, boolean dft)
{
return (dcsc != null)? dcsc.getEstimateOdometer(dft) : dft;
}
// ------------------------------------------------------------------------
/**
*** Gets the "Ignore Device Odometer" flag
*** @param dft The default ignore device odometer flag
*** @return The Ignore Device Odometer flag
**/
public boolean getIgnoreDeviceOdometer(boolean dft)
{
return this.getBooleanProperty(DCServerFactory.CONFIG_ignoreDeviceOdometer(this.getName()), dft);
}
/**
*** Gets the "Ignore Device Odometer" flag
*** @param dcsc The DCServerConfig instance
*** @param dft The default ignore device odometer flag
*** @return The ignore device Odometer flag
**/
public static boolean getIgnoreDeviceOdometer(DCServerConfig dcsc, boolean dft)
{
return (dcsc != null)? dcsc.getIgnoreDeviceOdometer(dft) : dft;
}
// ------------------------------------------------------------------------
/**
*** Gets the "Simulate Geozones"
*** @param dft The default Simulate Geozones state
*** @return The Simulate Geozones
**/
public boolean getSimulateGeozones(boolean dft)
{
return this.getBooleanProperty(DCServerFactory.CONFIG_simulateGeozones(this.getName()), dft);
}
/**
*** Gets the "Simulate Geozones"
*** @param dcsc The DCServerConfig instance
*** @param dft The default Simulate Geozones state
*** @return The Simulate Geozones
**/
public static boolean getSimulateGeozones(DCServerConfig dcsc, boolean dft)
{
return (dcsc != null)? dcsc.getSimulateGeozones(dft) : dft;
}
// ------------------------------------------------------------------------
/**
*** Gets the "Maximum HDOP"
*** @param dft The default maximum HDOP
*** @return The Maximum HDOP
**/
public double getMaximumHDOP(double dft)
{
return this.getDoubleProperty(DCServerFactory.CONFIG_maximumHDOP(this.getName()), dft);
}
/**
*** Gets the "Maximum HDOP"
*** @param dcsc The DCServerConfig instance
*** @param dft The default maximum HDOP
*** @return The Maximum HDOP
**/
public static double getMaximumHDOP(DCServerConfig dcsc, double dft)
{
return (dcsc != null)? dcsc.getMaximumHDOP(dft) : dft;
}
// ------------------------------------------------------------------------
/**
*** Gets the "Save Raw Data Packet" config
*** @param dft The default "Save Raw Data Packet" state
*** @return The "Save Raw Data Packet" state
**/
public boolean getSaveRawDataPackets(boolean dft)
{
return this.getBooleanProperty(DCServerFactory.CONFIG_saveRawDataPackets(this.getName()), dft);
}
/**
*** Gets the "Save Raw Data Packet" config
*** @param dcsc The DCServerConfig instance
*** @param dft The default "Save Raw Data Packet" state
*** @return The "Save Raw Data Packet" state
**/
public static boolean getSaveRawDataPackets(DCServerConfig dcsc, boolean dft)
{
return (dcsc != null)? dcsc.getSaveRawDataPackets(dft) : dft;
}
// ------------------------------------------------------------------------
/**
*** Gets the "Start/Stop StatusCode supported" config
*** @param dft The default "Start/Stop StatusCode supported" state
*** @return The "Start/Stop StatusCode supported" state
**/
public boolean getStartStopSupported(boolean dft)
{
String n = this.getName();
if (n.equals(DCServerFactory.OPENDMTP_NAME)) {
return true;
} else {
return this.getBooleanProperty(DCServerFactory.CONFIG_startStopSupported(this.getName()), dft);
}
}
/**
*** Gets the "Start/Stop StatusCode supported" config
*** @param dcsc The DCServerConfig instance
*** @param dft The default "Start/Stop StatusCode supported" state
*** @return The "Start/Stop StatusCode supported" state
**/
public static boolean getStartStopSupported(DCServerConfig dcsc, boolean dft)
{
return (dcsc != null)? dcsc.getStartStopSupported(dft) : dft;
}
// ------------------------------------------------------------------------
/**
*** Gets the "Status Location/InMotion Translation" config
*** @param dft The default "Status Location/InMotion Translation" state
*** @return The "Status Location/InMotion Translation" state
**/
public boolean getStatusLocationInMotion(boolean dft)
{
return this.getBooleanProperty(DCServerFactory.CONFIG_statusLocationInMotion(this.getName()), dft);
}
/**
*** Gets the "Status Location/InMotion Translation" config
*** @param dcsc The DCServerConfig instance
*** @param dft The default "Status Location/InMotion Translation" state
*** @return The "Status Location/InMotion Translation" state
**/
public static boolean getStatusLocationInMotion(DCServerConfig dcsc, boolean dft)
{
return (dcsc != null)? dcsc.getStatusLocationInMotion(dft) : dft;
}
// ------------------------------------------------------------------------
/**
*** Gets the "Ignore Invalid GPS Location Flag" config
*** @param dft The default "Ignore Invalid GPS Location Flag" state
*** @return The "Ignore Invalid GPS Location Flag" state
**/
public boolean getIgnoreInvalidGPSFlag(boolean dft)
{
return this.getBooleanProperty(DCServerFactory.CONFIG_ignoreInvalidGPSFlag(this.getName()), dft);
}
/**
*** Gets the "Ignore Invalid GPS Location Flag" config
*** @param dcsc The DCServerConfig instance
*** @param dft The default "Ignore Invalid GPS Location Flag" state
*** @return The "Ignore Invalid GPS Location Flag" state
**/
public static boolean getIgnoreInvalidGPSFlag(DCServerConfig dcsc, boolean dft)
{
return (dcsc != null)? dcsc.getIgnoreInvalidGPSFlag(dft) : dft;
}
// ------------------------------------------------------------------------
/**
*** Gets the "Use Last Valid GPS Location" config
*** @param dft The default "Use Last Valid GPS Location" state
*** @return The "Use Last Valid GPS Location" state
**/
public boolean getUseLastValidGPSLocation(boolean dft)
{
return this.getBooleanProperty(DCServerFactory.CONFIG_useLastValidGPSLocation(this.getName()), dft);
}
/**
*** Gets the "Use Last Valid GPS Location" config
*** @param dcsc The DCServerConfig instance
*** @param dft The default "Use Last Valid GPS Location" state
*** @return The "Use Last Valid GPS Location" state
**/
public static boolean getUseLastValidGPSLocation(DCServerConfig dcsc, boolean dft)
{
return (dcsc != null)? dcsc.getUseLastValidGPSLocation(dft) : dft;
}
// ------------------------------------------------------------------------
/**
*** Gets the "Save Session Statistics" config
*** @param dft The default "Save Session Statistics" state
*** @return The "Save Session Statistics" state
**/
public boolean getSaveSessionStatistics(boolean dft)
{
return this.getBooleanProperty(DCServerFactory.CONFIG_saveSessionStatistics(this.getName()), dft);
}
/**
*** Gets the "Save Session Statistics" config
*** @param dcsc The DCServerConfig instance
*** @param dft The default "Save Session Statistics" state
*** @return The "Save Session Statistics" state
**/
public static boolean getSaveSessionStatistics(DCServerConfig dcsc, boolean dft)
{
return (dcsc != null)? dcsc.getSaveSessionStatistics(dft) : dft;
}
// ------------------------------------------------------------------------
/**
*** Gets the "Battery Level Range" config
*** @param dft The default "Battery Level Range" min/max values
*** @return The "Battery Level Range" min/max values
**/
public double[] getBatteryLevelRange(double dft[])
{
String propKeys[] = DCServerFactory.CONFIG_batteryLevelRange(this.getName());
/* get property string */
String blrS = this.getStringProperty(propKeys, null);
if (StringTools.isBlank(blrS)) {
return dft;
}
/* parse */
double blr[] = StringTools.parseDouble(StringTools.split(blrS,','),0.0);
double min = 0.0;
double max = 0.0;
if (ListTools.size(blr) <= 0) {
min = (ListTools.size(dft) > 0)? dft[0] : 11.4;
max = (ListTools.size(dft) > 1)? dft[1] : 12.8;
} else
if (ListTools.size(blr) == 1) {
// <Property key="...">12.0</Property>
min = blr[0];
max = blr[0];
} else {
min = blr[0];
max = blr[1];
}
/* adjust */
if (min < 0.0) { min = 0.0; }
if (max < 0.0) { max = 0.0; }
if (max <= min) {
// <Property>12.8,11.4</Property>
double tmp = max;
max = min;
min = tmp;
}
/* return */
return new double[] { min, max };
}
/**
*** Gets the "Battery Level Range" config
*** @param dcsc The DCServerConfig instance
*** @param dft The default "Battery Level Range" min/max values
*** @return The "Battery Level Range" min/max values
**/
public static double[] getBatteryLevelRange(DCServerConfig dcsc, double dft[])
{
return (dcsc != null)? dcsc.getBatteryLevelRange(dft) : dft;
}
/**
*** Calculates/returns the battery level based on the specified voltage range
*** @param voltage The current battery voltage
*** @param range The allowed voltage range
*** @return The battery level percent
**/
public static double CalculateBatteryLevel(double voltage, double range[])
{
/* no specified voltage? */
if (voltage <= 0.0) {
return 0.0;
}
/* no specified range? */
int rangeSize = ListTools.size(range);
if ((rangeSize < 1) || (voltage <= range[0])) {
return 0.0;
} else
if ((rangeSize < 2) || (voltage >= range[1])) {
return 1.0;
}
/* get percent */
// Note: the above filters out (range[1] == range[0])
double percent = (voltage - range[0]) / (range[1] - range[0]);
if (percent < 0.0) {
return 0.0;
} else
if (percent > 1.0) {
return 1.0;
} else {
return percent;
}
}
// ------------------------------------------------------------------------
/**
*** Gets the "Simulate Geozones" mask
*** @param dft The default Simulate Geozones mask
*** @return The Simulate Geozones mask
**/
public long getSimulateDigitalInputs(long dft)
{
String maskStr = this.getStringProperty(DCServerFactory.CONFIG_simulateDigitalInputs(this.getName()), null);
if (StringTools.isBlank(maskStr)) {
// not specified (or blank)
return dft;
} else
if (maskStr.equalsIgnoreCase("default")) {
// explicit "default"
return dft;
} else
if (maskStr.equalsIgnoreCase("true")) {
// explicit "true"
return 0xFFFFFFFFL;
} else
if (maskStr.equalsIgnoreCase("false")) {
// explicit "false"
return 0x00000000L;
} else {
// mask specified
long mask = StringTools.parseLong(maskStr, -1L);
return (mask >= 0L)? mask : dft;
}
}
/**
*** Gets the "Simulate Geozones" mask
*** @param dcsc The DCServerConfig instance
*** @param dft The default Simulate Geozones mask
*** @return The Simulate Geozones mask
**/
public static long getSimulateDigitalInputs(DCServerConfig dcsc, long dft)
{
return (dcsc != null)? dcsc.getSimulateDigitalInputs(dft) : dft;
}
/**
*** Returns true if this device supports digital inputs
*** @return True if this device supports digital inputs
**/
public boolean hasDigitalInputs()
{
return this.isAttributeFlag(F_HAS_INPUTS);
}
/**
*** Returns true if this device supports digital outputs
*** @return True if this device supports digital outputs
**/
public boolean hasDigitalOutputs()
{
return this.isAttributeFlag(F_HAS_OUTPUTS);
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Convenience for converting the initial/final packet to a byte array.
*** If the string begins with "0x" the the remain string is assumed to be hex
*** @return The byte array
**/
public static byte[] convertToBytes(String s)
{
if (s == null) {
return null;
} else
if (s.startsWith("0x")) {
byte b[] = StringTools.parseHex(s,null);
if (b != null) {
return b;
} else {
return null;
}
} else {
return StringTools.getBytes(s);
}
}
/**
*** Gets the "Initial Packet" byte array
*** @param dft The default "Initial Packet" byte array
*** @return The "Initial Packet" byte array
**/
public byte[] getInitialPacket(byte[] dft)
{
String s = this.getStringProperty(DCServerFactory.CONFIG_initialPacket(this.getName()), null);
if (s == null) {
return dft;
} else
if (s.startsWith("0x")) {
return StringTools.parseHex(s,dft);
} else {
return s.getBytes();
}
}
/**
*** Gets the "Final Packet" byte array
*** @param dft The default "Final Packet" byte array
*** @return The "Final Packet" byte array
**/
public byte[] getFinalPacket(byte[] dft)
{
String s = this.getStringProperty(DCServerFactory.CONFIG_finalPacket(this.getName()), null);
if (s == null) {
return dft;
} else
if (s.startsWith("0x")) {
return StringTools.parseHex(s,dft);
} else {
return s.getBytes();
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Sets the "Event Code Map Enable" config
*** @param enabled The "Event Code Map Enable" state
**/
public void setEventCodeEnabled(boolean enabled)
{
this.customCodeEnabled = enabled;
//Print.logDebug("[" + this.getName() + "] EventCode translation enabled=" + this.customCodeEnabled);
}
/**
*** Gets the "Event Code Map Enable" config
*** @return The "Event Code Map Enable" state
**/
public boolean getEventCodeEnabled()
{
return this.customCodeEnabled;
}
/**
**/
public void setEventCodeMap(Map<Object,EventCode> codeMap)
{
this.customCodeMap = (codeMap != null)? codeMap : new HashMap<Object,EventCode>();
}
/**
*** Returns the EventCode instance for the specified code
*** @param code The code
*** @return The EventCode
**/
public EventCode getEventCode(int code)
{
if (!this.customCodeEnabled) {
return null;
} else {
Object keyObj = new Integer(code);
return this.customCodeMap.get(keyObj);
}
}
/**
*** Returns the EventCode instance for the specified code
*** @param code The code
*** @return The EventCode
**/
public EventCode getEventCode(long code)
{
if (!this.customCodeEnabled) {
return null;
} else {
Object keyObj = new Integer((int)code);
return this.customCodeMap.get(keyObj);
}
}
/**
*** Returns the EventCode instance for the specified code
*** @param code The code
*** @return The EventCode
**/
public EventCode getEventCode(String code)
{
if (!this.customCodeEnabled || (code == null)) {
return null;
} else {
Object keyObj = StringTools.trim(code).toLowerCase();
return this.customCodeMap.get(keyObj);
}
}
/**
*** Translates the specified device status code into a GTS status code
*** @param code The code to translate
*** @param dftStatusCode The default code returned if no translation is defined
*** @return The translated GTS status code
**/
public int translateStatusCode(int code, int dftStatusCode)
{
EventCode sci = this.getEventCode(code);
return (sci != null)? sci.getStatusCode() : dftStatusCode;
}
/**
*** Translates the specified device status code into a GTS status code
*** @param code The code to translate
*** @param dftStatusCode The default code returned if no translation is defined
*** @return The translated GTS status code
**/
public int translateStatusCode(String code, int dftStatusCode)
{
EventCode sci = this.getEventCode(code);
return (sci != null)? sci.getStatusCode() : dftStatusCode;
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Sets the device command listen host (may be null to use default bind-address)
*** @param cmdHost The device command listen host
**/
public void setCommandDispatcherHost(String cmdHost)
{
this.commandHost = cmdHost;
}
/**
*** Gets the device command listen host
*** @return The device command listen host
**/
public String getCommandDispatcherHost()
{
if (!StringTools.isBlank(this.commandHost)) {
return this.commandHost;
} else
if (!StringTools.isBlank(DCServerFactory.BIND_ADDRESS)) {
return DCServerFactory.BIND_ADDRESS;
} else {
// DCServer.DCSNAME.bindAddress
String bindKey = DCServerFactory.PROP_DCServer_ + this.getName() + "." + DCServerFactory.ATTR_bindAddress;
String bindAddr = this.getStringProperty(bindKey, null);
return !StringTools.isBlank(bindAddr)? bindAddr : "localhost";
}
}
/**
*** Sets the device command listen port
*** @param cmdPort The device command listen port
*** @param checkRTP True to allow the RTConfig propertiesto override this value
**/
public void setCommandDispatcherPort(int cmdPort, boolean checkRTP)
{
if (checkRTP) {
int port = 0;
// First try command-line override
RTProperties cmdLineProps = RTConfig.getCommandLineProperties();
if ((cmdLineProps != null) && cmdLineProps.hasProperty(DCServerFactory.ARG_commandPort)) {
port = cmdLineProps.getInt(DCServerFactory.ARG_commandPort, 0);
}
// then try standard runtime config override
if (port <= 0) {
port = this.getIntProperty(DCServerFactory.CONFIG_commandPort(this.getName()), 0);
}
// change port if overridden
if (port > 0) {
cmdPort = port;
}
}
this.commandPort = cmdPort;
}
/**
*** Sets the device command listen port
*** @param cmdPort The device command listen port
**/
public void setCommandDispatcherPort(int cmdPort)
{
this.setCommandDispatcherPort(cmdPort,false);
}
/**
*** Gets the device command listen port (returns '0' if not supported)
*** @return The device command listen port
**/
public int getCommandDispatcherPort()
{
return this.commandPort;
}
// ------------------------------------------------------------------------
/**
*** Sets the Commands Acl name
*** @param aclName The Commands Acl name
**/
public void setCommandsAclName(String aclName, AclEntry.AccessLevel dft)
{
this.commandsAclName = StringTools.trim(aclName);
this.commandsAccessLevelDft = dft;
}
/**
*** Gets the Commands Acl name
*** @return The Commands Acl name
**/
public String getCommandsAclName()
{
return this.commandsAclName;
}
/**
*** Gets the Commands Acl AccessLevel default
*** @return The Commands Acl AccessLevel default
**/
public AclEntry.AccessLevel getCommandsAccessLevelDefault()
{
return this.commandsAccessLevelDft;
}
/**
*** Returns True if the specified user has access to the named command
**/
public boolean userHasAccessToCommand(BasicPrivateLabel privLabel, User user, String commandName)
{
/* BasicPrivateLabel must be specified */
if (privLabel == null) {
return false;
}
/* get command */
Command command = this.getCommand(commandName);
if (command == null) {
return false;
}
/* has access to commands */
if (privLabel.hasWriteAccess(user, this.getCommandsAclName())) {
return false;
}
/* has access to specific command? */
if (privLabel.hasWriteAccess(user, command.getAclName())) {
return false;
}
/* access granted */
return true;
}
// ------------------------------------------------------------------------
public void addCommand(
String cmdName, String cmdDesc,
String cmdTypes[],
String cmdAclName, AclEntry.AccessLevel cmdAclDft,
String cmdString, boolean hasArgs, Collection<DCServerConfig.CommandArg> cmdArgList,
String cmdProto, boolean expectAck,
int cmdSCode)
{
if (StringTools.isBlank(cmdName)) {
Print.logError("Ignoreing blank command name");
} else
if ((this.commandMap != null) && this.commandMap.containsKey(cmdName)) {
Print.logError("Command already defined: " + cmdName);
} else {
Command cmd = new Command(
cmdName, cmdDesc,
cmdTypes,
cmdAclName, cmdAclDft,
cmdString, hasArgs, cmdArgList,
cmdProto, expectAck,
cmdSCode);
if (this.commandMap == null) {
this.commandMap = new OrderedMap<String,Command>();
}
this.commandMap.put(cmdName, cmd);
}
}
public Command getCommand(String name)
{
return (this.commandMap != null)? this.commandMap.get(name) : null;
}
/**
*** Gets the "Command List"
*** @return The "Command List"
**/
public String[] getCommandList()
{
if (ListTools.isEmpty(this.commandMap)) {
return null;
} else {
return this.commandMap.keyArray(String.class);
}
}
/**
*** Gets the "Command Description" for the specified command
*** @param dft The default "Command Description"
*** @return The "Command Description" for the specified command
**/
public String getCommandDescription(String cmdName, String dft)
{
Command cmd = this.getCommand(cmdName);
return (cmd != null)? cmd.getDescription() : dft;
}
/**
*** Gets the "Command String" for the specified command
*** @param dft The default "Command String"
*** @return The "Command String" for the specified command
**/
public String getCommandString(String cmdName, String dft)
{
Command cmd = this.getCommand(cmdName);
return (cmd != null)? cmd.getCommandString() : dft;
}
/**
*** Gets the status-code for the specified command. An event with this
*** status code will be inserted into the EventData table when this command
*** is sent to the device.
*** @param code The default status-code
*** @return The status-code for the specified command
**/
public int getCommandStatusCode(String cmdName, int code)
{
Command cmd = this.getCommand(cmdName);
return (cmd != null)? cmd.getStatusCode() : code;
}
/**
*** Gets the command's (name,description) map
*** @param type The description type
*** @return The command's (name,description) map
**/
public Map<String,Command> getCommandMap(BasicPrivateLabel privLabel, User user, String type)
{
boolean inclReplCmds = true; // for now, include all commands
String cmdList[] = this.getCommandList();
if (!ListTools.isEmpty(cmdList)) {
Map<String,Command> cmdMap = new OrderedMap<String,Command>();
for (Command cmd : this.commandMap.values()) {
if (!DCServerFactory.isCommandTypeAll(type) && !cmd.isType(type)) {
// ignore this command
//Print.logInfo("Command '%s' is not property type '%s'", cmd.getName(), type);
} else
if ((privLabel != null) && !privLabel.hasWriteAccess(user,cmd.getAclName())) {
// user does not have access to this command
//Print.logInfo("User does not have access to command '%s'", cmd.getName());
} else {
String key = cmd.getName();
String desc = cmd.getDescription();
String cstr = cmd.getCommandString();
if (StringTools.isBlank(desc) && StringTools.isBlank(cstr)) {
// skip commands with blank description and commands
Print.logInfo("Command does not have a descripton, or command is blank");
continue;
} else
if (!inclReplCmds) {
if (cstr.indexOf("${") >= 0) { //}
// should not occur ('type' should not include commands that require parameters)
// found "${text}"
continue;
}
}
cmdMap.put(key,cmd);
}
}
return cmdMap;
} else {
//Print.logInfo("Command list is empty: " + this.getName());
return null;
}
}
/**
*** Gets the command's (name,description) map
*** @param type The description type
*** @return The command's (name,description) map
**/
public Map<String,String> getCommandDescriptionMap(BasicPrivateLabel privLabel, User user, String type)
{
Map<String,Command> cmdMap = this.getCommandMap(privLabel, user, type);
if (!ListTools.isEmpty(cmdMap)) {
Map<String,String> cmdDescMap = new OrderedMap<String,String>();
for (Command cmd : cmdMap.values()) {
String key = cmd.getName();
String desc = cmd.getDescription();
cmdDescMap.put(key,desc); // Commands are pre-qualified
}
return cmdDescMap;
} else {
return null;
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
public RTProperties getDefaultProperties()
{
RTProperties rtp = this.rtPropsMap.get(DEFAULT_PROP_GROUP_ID);
if (rtp == null) {
rtp = new RTProperties();
this.rtPropsMap.put(DEFAULT_PROP_GROUP_ID, rtp);
}
return rtp;
}
public Set<String> getPropertyGroupNames()
{
this.getDefaultProperties(); // make sure the detault properties are cached
return this.rtPropsMap.keySet();
}
public RTProperties getProperties(String propID)
{
return this.getProperties(propID, false);
}
public RTProperties getProperties(String propID, boolean createNewGroup)
{
if (StringTools.isBlank(propID) || propID.equalsIgnoreCase(DEFAULT_PROP_GROUP_ID)) {
// blank group, return default
return this.getDefaultProperties();
} else {
RTProperties rtp = this.rtPropsMap.get(propID);
if (rtp != null) {
// found, return properties group
return rtp;
} else
if (createNewGroup) {
// not found, create
rtp = new RTProperties();
this.rtPropsMap.put(propID, rtp);
return rtp;
} else {
// do not create, return default
return this.getDefaultProperties();
}
}
}
// ------------------------------------------------------------------------
/**
*** Prepend DCS name to key
**/
public String normalizeKey(String key)
{
if (StringTools.isBlank(key)) {
return "";
} else
if (key.indexOf(this.getName() + ".") >= 0) {
// "enfora.tcpPort"
// "DCServer.enfora.tcpPort"
return key;
} else {
// "tcpPort" ==> "enfora.tcpPort"
return this.getName() + "." + key;
}
}
/**
*** Prepend DCS name to keys
**/
public String[] normalizeKeys(String key[])
{
if (!ListTools.isEmpty(key)) {
for (int i = 0; i < key.length; i++) {
key[i] = this.normalizeKey(key[i]);
}
}
return key;
}
// ------------------------------------------------------------------------
public boolean hasProperty(String key[], boolean inclDft)
{
RTProperties rtp = this.getDefaultProperties();
if (rtp.hasProperty(key)) {
return true;
} else {
String k[] = this.normalizeKeys(key);
if (rtp.hasProperty(k)) {
return true;
} else {
return RTConfig.hasProperty(k, inclDft);
}
}
}
public Set<String> getPropertyKeys(String prefix)
{
RTProperties rtp = this.getDefaultProperties();
Set<String> propKeys = new HashSet<String>();
/* regualr keys */
propKeys.addAll(rtp.getPropertyKeys(prefix));
propKeys.addAll(RTConfig.getPropertyKeys(prefix));
/* normalized keys */
String pfx = this.normalizeKey(prefix);
propKeys.addAll(rtp.getPropertyKeys(pfx));
propKeys.addAll(RTConfig.getPropertyKeys(pfx));
return propKeys;
}
// ------------------------------------------------------------------------
public String[] getStringArrayProperty(String key, String dft[])
{
RTProperties rtp = this.getDefaultProperties();
if (rtp.hasProperty(key)) {
return rtp.getStringArray(key, dft);
} else {
String k = this.normalizeKey(key);
if (rtp.hasProperty(k)) {
return rtp.getStringArray(k, dft);
} else {
return RTConfig.getStringArray(k, dft);
}
}
}
public String[] getStringArrayProperty(String key[], String dft[])
{
RTProperties rtp = this.getDefaultProperties();
if (rtp.hasProperty(key)) {
return rtp.getStringArray(key, dft);
} else {
String k[] = this.normalizeKeys(key);
if (rtp.hasProperty(k)) {
return rtp.getStringArray(k, dft);
} else {
return RTConfig.getStringArray(k, dft);
}
}
}
// ------------------------------------------------------------------------
public String getStringProperty(String key, String dft)
{
RTProperties rtp = this.getDefaultProperties();
if (rtp.hasProperty(key)) {
return rtp.getString(key, dft);
} else {
String k = this.normalizeKey(key);
if (rtp.hasProperty(k)) {
// local normalized key
return rtp.getString(k, dft);
} else
if (RTConfig.hasProperty(k)) {
// global normalized key
return RTConfig.getString(k, dft);
} else {
// global original key
return RTConfig.getString(key, dft);
}
}
}
public String getStringProperty(String key[], String dft)
{
RTProperties rtp = this.getDefaultProperties();
if (rtp.hasProperty(key)) {
return rtp.getString(key, dft);
} else {
String k[] = this.normalizeKeys(key);
if (rtp.hasProperty(k)) {
// local normalized key
return rtp.getString(k, dft);
} else
if (RTConfig.hasProperty(k)) {
// global normalized key
return RTConfig.getString(k, dft);
} else {
// global original key
return RTConfig.getString(key, dft);
}
}
}
// ------------------------------------------------------------------------
public int getIntProperty(String key, int dft)
{
RTProperties rtp = this.getDefaultProperties();
if (rtp.hasProperty(key)) {
return rtp.getInt(key, dft);
} else {
String k = this.normalizeKey(key);
if (rtp.hasProperty(k)) {
return rtp.getInt(k, dft);
} else {
return RTConfig.getInt(k, dft);
}
}
}
public int getIntProperty(String key[], int dft)
{
RTProperties rtp = this.getDefaultProperties();
if (rtp.hasProperty(key)) {
return rtp.getInt(key, dft);
} else {
String k[] = this.normalizeKeys(key);
if (rtp.hasProperty(k)) {
return rtp.getInt(k, dft);
} else {
return RTConfig.getInt(k, dft);
}
}
}
// ------------------------------------------------------------------------
public long getLongProperty(String key, long dft)
{
RTProperties rtp = this.getDefaultProperties();
if (rtp.hasProperty(key)) {
return rtp.getLong(key, dft);
} else {
String k = this.normalizeKey(key);
if (rtp.hasProperty(k)) {
return rtp.getLong(k, dft);
} else {
return RTConfig.getLong(k, dft);
}
}
}
public long getLongProperty(String key[], long dft)
{
RTProperties rtp = this.getDefaultProperties();
if (rtp.hasProperty(key)) {
return rtp.getLong(key, dft);
} else {
String k[] = this.normalizeKeys(key);
if (rtp.hasProperty(k)) {
return rtp.getLong(k, dft);
} else {
return RTConfig.getLong(k, dft);
}
}
}
// ------------------------------------------------------------------------
public double getDoubleProperty(String key, double dft)
{
RTProperties rtp = this.getDefaultProperties();
if (rtp.hasProperty(key)) {
return rtp.getDouble(key, dft);
} else {
String k = this.normalizeKey(key);
if (rtp.hasProperty(k)) {
return rtp.getDouble(k, dft);
} else {
return RTConfig.getDouble(k, dft);
}
}
}
public double getDoubleProperty(String key[], double dft)
{
RTProperties rtp = this.getDefaultProperties();
if (rtp.hasProperty(key)) {
return rtp.getDouble(key, dft);
} else {
String k[] = this.normalizeKeys(key);
if (rtp.hasProperty(k)) {
return rtp.getDouble(k, dft);
} else {
return RTConfig.getDouble(k, dft);
}
}
}
// ------------------------------------------------------------------------
public boolean getBooleanProperty(String key, boolean dft)
{
RTProperties rtp = this.getDefaultProperties();
if (rtp.hasProperty(key)) {
return rtp.getBoolean(key, dft);
} else {
String k = this.normalizeKey(key);
if (rtp.hasProperty(k)) {
return rtp.getBoolean(k, dft);
} else {
return RTConfig.getBoolean(k, dft);
}
}
}
public boolean getBooleanProperty(String key[], boolean dft)
{
RTProperties rtp = this.getDefaultProperties();
if (rtp.hasProperty(key)) {
return rtp.getBoolean(key, dft);
} else {
String k[] = this.normalizeKeys(key);
if (rtp.hasProperty(k)) {
return rtp.getBoolean(k, dft);
} else {
return RTConfig.getBoolean(k, dft);
}
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Returns the state of the indicated bit within the mask for this device type.
*** @param mask The input mask from the device
*** @param bit The bit to test
**/
public boolean getDigitalInputState(long mask, int bit)
{
int ofs = this.getIntProperty(DCServerFactory.PROP_Attribute_InputOffset, -1);
int b = (ofs > 0)? (ofs - bit) : bit;
return (b >= 0)? ((mask & (1L << b)) != 0L) : false;
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Returns true if the 'other' DCServerCOnfig is equal to this DCServerConfig
*** based on the name.
*** @param other The other DCServerConfig instance.
*** @return True if the other DCServerConfig as the same name as this DCServerConfig
**/
public boolean equals(Object other)
{
if (other instanceof DCServerConfig) {
String thisName = this.getName();
String otherName = ((DCServerConfig)other).getName();
return thisName.equals(otherName);
} else {
return false;
}
}
/**
*** Compares another DCServerConfig instance to this instance.
*** @param other The other DCServerConfig instance.
*** @return 'compareTo' operator on DCServerConfig names.
**/
public int compareTo(Object other)
{
if (other instanceof DCServerConfig) {
String thisName = this.getName();
String otherName = ((DCServerConfig)other).getName();
return thisName.compareTo(otherName);
} else {
return -1;
}
}
/**
*** Return hashCode based on the DCServerConfig name
*** @return this.getNmae().hashCoe()
**/
public int hashCode()
{
return this.getName().hashCode();
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Returns a String representation of this instance
*** @return A String representation
**/
public String toString()
{
return this.toString(true);
}
/**
*** Returns a String representation of this instance
*** @param inclName True to include the name in the returnsed String representation
*** @return A String representation
**/
public String toString(boolean inclName)
{
// "(opendmtp) OpenDMTP Server [TCP=31000 UDP=31000 CMD=30050]
StringBuffer sb = new StringBuffer();
/* name/description */
if (inclName) {
sb.append("(").append(this.getName()).append(") ");
}
sb.append(this.getDescription()).append(" ");
/* ports */
sb.append("[");
this.getPortsString(sb);
sb.append("]");
/* String representation */
return sb.toString();
}
public StringBuffer getPortsString(StringBuffer sb)
{
if (sb == null) { sb = new StringBuffer(); }
int p = 0;
int tcp[] = this.getTcpPorts();
if (!ListTools.isEmpty(tcp)) {
if (p > 0) { sb.append(" "); }
sb.append("TCP=" + StringTools.join(tcp,","));
p++;
}
int udp[] = this.getUdpPorts();
if (!ListTools.isEmpty(udp)) {
if (p > 0) { sb.append(" "); }
sb.append("UDP=" + StringTools.join(udp,","));
p++;
}
int cmd = this.getCommandDispatcherPort();
if (cmd > 0) {
if (p > 0) { sb.append(" "); }
sb.append("CMD=" + cmd);
p++;
}
if (p == 0) {
sb.append("no-ports");
}
return sb;
}
public String getPortsString()
{
return this.getPortsString(null).toString();
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Return running jar file path
**/
public File[] getRunningJarPath()
{
return DCServerConfig.getRunningJarPath(this.getName());
}
}
| {
"content_hash": "ac264f75818305e4a71f193e07cdc225",
"timestamp": "",
"source": "github",
"line_count": 2722,
"max_line_length": 131,
"avg_line_length": 35.203894195444526,
"alnum_prop": 0.5111400991390556,
"repo_name": "CASPED/OpenGTS",
"id": "6500b2d48b991415fa157c6e63c1ff09e8645b64",
"size": "95825",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/opengts/db/DCServerConfig.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4957656"
},
{
"name": "Perl",
"bytes": "12845"
},
{
"name": "Shell",
"bytes": "28341"
}
],
"symlink_target": ""
} |
//===- ARMInstPrinter.h - Convert ARM MCInst to assembly syntax -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class prints an ARM MCInst to a .s file.
//
//===----------------------------------------------------------------------===//
/* Capstone Disassembly Engine */
/* By Nguyen Anh Quynh <[email protected]>, 2013-2019 */
#ifndef CS_ARMINSTPRINTER_H
#define CS_ARMINSTPRINTER_H
#include "../../MCInst.h"
#include "../../MCRegisterInfo.h"
#include "../../SStream.h"
void ARM_printInst(MCInst *MI, SStream *O, void *Info);
void ARM_post_printer(csh handle, cs_insn *pub_insn, char *mnem, MCInst *mci);
// setup handle->get_regname
void ARM_getRegName(cs_struct *handle, int value);
// specify vector data type for vector instructions
void ARM_addVectorDataType(MCInst *MI, arm_vectordata_type vd);
void ARM_addVectorDataSize(MCInst *MI, int size);
void ARM_addReg(MCInst *MI, int reg);
// load usermode registers (LDM, STM)
void ARM_addUserMode(MCInst *MI);
// sysreg for MRS/MSR
void ARM_addSysReg(MCInst *MI, arm_sysreg reg);
#endif
| {
"content_hash": "9d7b086374619b32bff2bb19a147e907",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 80,
"avg_line_length": 29.976744186046513,
"alnum_prop": 0.6089992242048099,
"repo_name": "emoon/ProDBG",
"id": "4332d1a913c906e7fae05d2ab741d5fb75469724",
"size": "1289",
"binary": false,
"copies": "3",
"ref": "refs/heads/dev",
"path": "src/external/capstone/arch/ARM/ARMInstPrinter.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "7276"
},
{
"name": "C",
"bytes": "343366"
},
{
"name": "C++",
"bytes": "1062219"
},
{
"name": "HTML",
"bytes": "16730"
},
{
"name": "Lua",
"bytes": "698970"
},
{
"name": "Python",
"bytes": "4540"
},
{
"name": "Rust",
"bytes": "123765"
},
{
"name": "Shell",
"bytes": "416"
}
],
"symlink_target": ""
} |
declare module 'vscode' {
// https://github.com/microsoft/vscode/issues/157734
export namespace workspace {
/**
*
* @param scheme The URI scheme that this provider can provide edit session identities for.
* @param provider A provider which can convert URIs for workspace folders of scheme @param scheme to
* an edit session identifier which is stable across machines. This enables edit sessions to be resolved.
*/
export function registerEditSessionIdentityProvider(scheme: string, provider: EditSessionIdentityProvider): Disposable;
}
export interface EditSessionIdentityProvider {
/**
*
* @param workspaceFolder The workspace folder to provide an edit session identity for.
* @param token A cancellation token for the request.
* @returns A string representing the edit session identity for the requested workspace folder.
*/
provideEditSessionIdentity(workspaceFolder: WorkspaceFolder, token: CancellationToken): ProviderResult<string>;
/**
*
* @param identity1 An edit session identity.
* @param identity2 A second edit session identity to compare to @param identity1.
* @param token A cancellation token for the request.
* @returns An {@link EditSessionIdentityMatch} representing the edit session identity match confidence for the provided identities.
*/
provideEditSessionIdentityMatch(identity1: string, identity2: string, token: CancellationToken): ProviderResult<EditSessionIdentityMatch>;
}
export enum EditSessionIdentityMatch {
Complete = 100,
Partial = 50,
None = 0
}
}
| {
"content_hash": "57df924d55421d900e962367098fc417",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 140,
"avg_line_length": 38.1219512195122,
"alnum_prop": 0.7613563659628919,
"repo_name": "microsoft/vscode",
"id": "048da2830ba4b61f728705c485159d84b6eb151b",
"size": "1914",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "extensions/git/src/typings/vscode.proposed.contribEditSessions.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "19488"
},
{
"name": "C",
"bytes": "818"
},
{
"name": "C#",
"bytes": "709"
},
{
"name": "C++",
"bytes": "2745"
},
{
"name": "CSS",
"bytes": "694473"
},
{
"name": "Clojure",
"bytes": "1206"
},
{
"name": "CoffeeScript",
"bytes": "590"
},
{
"name": "Cuda",
"bytes": "3634"
},
{
"name": "Dart",
"bytes": "324"
},
{
"name": "Dockerfile",
"bytes": "475"
},
{
"name": "F#",
"bytes": "634"
},
{
"name": "Go",
"bytes": "652"
},
{
"name": "Groovy",
"bytes": "3928"
},
{
"name": "HLSL",
"bytes": "184"
},
{
"name": "HTML",
"bytes": "386747"
},
{
"name": "Hack",
"bytes": "16"
},
{
"name": "Handlebars",
"bytes": "1064"
},
{
"name": "Inno Setup",
"bytes": "307296"
},
{
"name": "Java",
"bytes": "599"
},
{
"name": "JavaScript",
"bytes": "956022"
},
{
"name": "Julia",
"bytes": "940"
},
{
"name": "Jupyter Notebook",
"bytes": "929"
},
{
"name": "Less",
"bytes": "1029"
},
{
"name": "Lua",
"bytes": "252"
},
{
"name": "Makefile",
"bytes": "2252"
},
{
"name": "Objective-C",
"bytes": "1387"
},
{
"name": "Objective-C++",
"bytes": "1387"
},
{
"name": "PHP",
"bytes": "998"
},
{
"name": "Perl",
"bytes": "1922"
},
{
"name": "PowerShell",
"bytes": "13597"
},
{
"name": "Pug",
"bytes": "654"
},
{
"name": "Python",
"bytes": "2171"
},
{
"name": "R",
"bytes": "362"
},
{
"name": "Roff",
"bytes": "351"
},
{
"name": "Ruby",
"bytes": "1703"
},
{
"name": "Rust",
"bytes": "301179"
},
{
"name": "SCSS",
"bytes": "6732"
},
{
"name": "Scilab",
"bytes": "54706"
},
{
"name": "ShaderLab",
"bytes": "330"
},
{
"name": "Shell",
"bytes": "63596"
},
{
"name": "Swift",
"bytes": "284"
},
{
"name": "TeX",
"bytes": "1602"
},
{
"name": "TypeScript",
"bytes": "43400033"
},
{
"name": "Visual Basic .NET",
"bytes": "893"
}
],
"symlink_target": ""
} |
/*************navigation****************/
#navigation {
background-color: FOURTH;/*barra di navigazione*/
display: block;
position: relative;
left: 45em;
bottom: 5em;
width: 24em;
border-left: 1em #0A1612 solid;
}
/*************cookie***********/
#cookie { text-align: left; display: block; text-indent: 1em;}
#cookie h3{
border-top: .2em solid #0A1612;
font-weight: 700;
text-align: left;
background-repeat: no-repeat;
text-indent: 2em;
}
/************languages*************/
#languages { /*text-align: right;*/ display:none; }
#languages li {display:none;}
#languages h3 { display: none;}
/*********portfolio*****************/
#portfolio { text-align: left; display:inline;}
#portfolio h3 {
text-indent: 2em;
border-top: .2em solid #0A1612;
font-weight: 700;
text-align: left;
background-repeat: no-repeat;
}
| {
"content_hash": "5c0c93fb100343a604fc4ebf44e684ee",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 62,
"avg_line_length": 24.17142857142857,
"alnum_prop": 0.6016548463356974,
"repo_name": "alepuzio/buildCSS",
"id": "2f0793a4e42021f209e3e13f71ec243e7addd82c",
"size": "846",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "output/PROFESSIONAL_AND_MODERN-navigation.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "498"
},
{
"name": "CSS",
"bytes": "7153"
},
{
"name": "Java",
"bytes": "17779"
},
{
"name": "Shell",
"bytes": "814"
}
],
"symlink_target": ""
} |
// This file is distributed under the MIT license.
// See the LICENSE file for details.
#pragma once
#ifndef VSNRAY_GET_SURFACE_H
#define VSNRAY_GET_SURFACE_H 1
#include <iterator>
#include <type_traits>
#include <utility>
#include "texture/texture.h"
#include "array.h"
#include "bvh.h"
#include "generic_primitive.h"
#include "get_color.h"
#include "get_normal.h"
#include "get_shading_normal.h"
#include "get_tex_coord.h"
#include "prim_traits.h"
#include "surface.h"
#include "tags.h"
namespace visionaray
{
namespace detail
{
//-------------------------------------------------------------------------------------------------
// Helper functions
//
// deduce simd surface type from params -------------------
template <typename Params, typename T, typename Enable = void>
struct simd_decl_surface;
template <typename Params, typename T>
struct simd_decl_surface<Params, T, typename std::enable_if<
!(has_colors<Params>::value || has_textures<Params>::value)
>::type>
{
private:
enum { Size_ = simd::num_elements<T>::value };
using N_ = typename Params::normal_type;
using M_ = typename Params::material_type;
public:
using type = surface<
decltype(simd::pack(std::declval<array<N_, Size_>>())),
decltype(simd::pack(std::declval<array<M_, Size_>>()))
>;
using array_type = array<surface<N_, M_>, Size_>;
};
template <typename Params, typename T>
struct simd_decl_surface<Params, T, typename std::enable_if<
has_colors<Params>::value || has_textures<Params>::value
>::type>
{
private:
enum { Size_ = simd::num_elements<T>::value };
using N_ = typename Params::normal_type;
using M_ = typename Params::material_type;
using C_ = typename Params::color_type;
public:
using type = surface<
decltype(simd::pack(std::declval<array<N_, Size_>>())),
decltype(simd::pack(std::declval<array<M_, Size_>>())),
decltype(simd::pack(std::declval<array<C_, Size_>>()))
>;
using array_type = array<surface<N_, M_, C_>, Size_>;
};
//-------------------------------------------------------------------------------------------------
// Struct containing both the geometric and the shading normal
//
template <typename V>
struct normal_pair
{
V geometric_normal;
V shading_normal;
};
template <typename V>
VSNRAY_FUNC
inline normal_pair<V> make_normal_pair(V const& gn, V const& sn)
{
return normal_pair<V>{ gn, sn };
}
// TODO: consolidate the following with get_normal()?
// TODO: consolidate interface with get_color() and get_tex_coord()?
//-------------------------------------------------------------------------------------------------
// get_normal_pair()
//
template <typename Normals, typename HR, typename Primitive, typename NormalBinding>
VSNRAY_FUNC
inline auto get_normal_pair(
Normals normals,
HR const& hr,
Primitive prim,
NormalBinding /* */,
typename std::enable_if<num_normals<Primitive, NormalBinding>::value >= 2>::type* = 0
)
-> decltype( make_normal_pair(
get_normal(normals, hr, prim, NormalBinding{}),
get_shading_normal(normals, hr, prim, NormalBinding{})
) )
{
return make_normal_pair(
get_normal(normals, hr, prim, NormalBinding{}),
get_shading_normal(normals, hr, prim, NormalBinding{})
);
}
template <typename Normals, typename HR, typename Primitive, typename NormalBinding>
VSNRAY_FUNC
inline auto get_normal_pair(
Normals normals,
HR const& hr,
Primitive /* */,
NormalBinding /* */,
typename std::enable_if<num_normals<Primitive, NormalBinding>::value == 1>::type* = 0
)
-> decltype( make_normal_pair(
get_normal(normals, hr, Primitive{}, NormalBinding{}),
get_shading_normal(normals, hr, Primitive{}, NormalBinding{})
) )
{
return make_normal_pair(
get_normal(normals, hr, Primitive{}, NormalBinding{}),
get_shading_normal(normals, hr, Primitive{}, NormalBinding{})
);
}
template <typename Normals, typename HR, typename Primitive, typename NormalBinding>
VSNRAY_FUNC
inline auto get_normal_pair(
Normals normals,
HR const& hr,
Primitive prim,
NormalBinding /* */,
typename std::enable_if<num_normals<Primitive, NormalBinding>::value == 0>::type* = 0
)
-> decltype( make_normal_pair(
get_normal(hr, prim),
get_shading_normal(hr, prim)
) )
{
VSNRAY_UNUSED(normals);
return make_normal_pair(
get_normal(hr, prim),
get_shading_normal(hr, prim)
);
}
template <typename HR, typename Primitive>
VSNRAY_FUNC
inline auto get_normal_pair(
HR const& hr,
Primitive prim
)
-> decltype( make_normal_pair(
get_normal(hr, prim),
get_shading_normal(hr, prim)
) )
{
return make_normal_pair(
get_normal(hr, prim),
get_shading_normal(hr, prim)
);
}
// get_normal_pair as functor for template arguments
struct get_normal_pair_t
{
template <typename Normals, typename HR, typename Primitive, typename NormalBinding>
VSNRAY_FUNC
inline auto operator()(
Normals normals,
HR const& hr,
Primitive prim,
NormalBinding /* */
) const
-> decltype( get_normal_pair(normals, hr, prim, NormalBinding{}) )
{
return get_normal_pair(normals, hr, prim, NormalBinding{});
}
template <typename HR, typename Primitive>
VSNRAY_FUNC
inline auto operator()(
HR const& hr,
Primitive prim
) const
-> decltype( get_normal_pair(hr, prim) )
{
return get_normal_pair(hr, prim);
}
};
// overload for generic_primitive
template <
typename Normals,
typename HR,
typename ...Ts,
typename NormalBinding
>
VSNRAY_FUNC
inline auto get_normal_pair(
Normals normals,
HR const& hr,
generic_primitive<Ts...> prim,
NormalBinding /* */
)
-> normal_pair<typename std::iterator_traits<Normals>::value_type>
{
get_normal_from_generic_primitive_visitor<
get_normal_pair_t,
normal_pair<typename std::iterator_traits<Normals>::value_type>,
NormalBinding,
Normals,
HR
>visitor(
normals,
hr
);
return apply_visitor( visitor, prim );
}
//-------------------------------------------------------------------------------------------------
// dispatch function for get_normal()
//
template <
typename Params,
typename Normals,
typename HR,
typename Primitive = typename Params::primitive_type,
typename NormalBinding = typename Params::normal_binding,
typename = typename std::enable_if<!is_any_bvh<Primitive>::value>::type
>
VSNRAY_FUNC
inline auto get_normal_dispatch(
Params const& params,
Normals normals,
HR const& hr,
typename std::enable_if<
num_normals<Primitive, NormalBinding>::value == 1
>::type* = 0
)
-> decltype( get_normal_pair(normals, hr, Primitive{}, NormalBinding{}) )
{
VSNRAY_UNUSED(params);
return get_normal_pair(normals, hr, Primitive{}, NormalBinding{});
}
template <
typename Params,
typename Normals,
typename HR,
typename Primitive = typename Params::primitive_type,
typename NormalBinding = typename Params::normal_binding,
typename = typename std::enable_if<!is_any_bvh<Primitive>::value>::type
>
VSNRAY_FUNC
inline auto get_normal_dispatch(
Params const& params,
Normals normals,
HR const& hr,
typename std::enable_if<
num_normals<Primitive, NormalBinding>::value != 1
>::type* = 0
)
-> decltype( get_normal_pair(normals, hr, params.prims.begin[hr.prim_id], NormalBinding{}) )
{
return get_normal_pair(normals, hr, params.prims.begin[hr.prim_id], NormalBinding{});
}
// overload for BVHs
template <
typename Params,
typename Normals,
typename R,
typename Base,
typename Primitive = typename Params::primitive_type,
typename NormalBinding = typename Params::normal_binding,
typename = typename std::enable_if<is_any_bvh<Primitive>::value>::type
>
VSNRAY_FUNC
inline auto get_normal_dispatch(
Params const& params,
Normals normals,
hit_record_bvh<R, Base> const& hr,
typename std::enable_if<
num_normals<typename Primitive::primitive_type, NormalBinding>::value == 1
>::type* = 0
)
-> decltype( get_normal_pair(
normals,
static_cast<Base const&>(hr),
typename Primitive::primitive_type{},
NormalBinding{}
) )
{
VSNRAY_UNUSED(params);
return get_normal_pair(
normals,
static_cast<Base const&>(hr),
typename Primitive::primitive_type{},
NormalBinding{}
);
}
template <
typename Params,
typename Normals,
typename R,
typename Base,
typename Primitive = typename Params::primitive_type,
typename NormalBinding = typename Params::normal_binding,
typename = typename std::enable_if<is_any_bvh<Primitive>::value>::type
>
VSNRAY_FUNC
inline auto get_normal_dispatch(
Params const& params,
Normals normals,
hit_record_bvh<R, Base> const& hr,
typename std::enable_if<
num_normals<typename Primitive::primitive_type, NormalBinding>::value != 1
>::type* = 0
)
-> decltype( get_normal_pair(
normals,
static_cast<Base const&>(hr),
typename Primitive::primitive_type{},
NormalBinding{}
) )
{
// Find the BVH that contains prim_id
size_t num_primitives_total = 0;
size_t i = 0;
while (static_cast<size_t>(hr.prim_id) >= num_primitives_total + params.prims.begin[i].num_primitives())
{
num_primitives_total += params.prims.begin[i++].num_primitives();
}
return get_normal_pair(
normals,
static_cast<Base const&>(hr),
params.prims.begin[i].primitive(hr.primitive_list_index),
typename Params::normal_binding{}
);
}
//-------------------------------------------------------------------------------------------------
// Sample textures with range check
//
template <typename HR, typename Params>
VSNRAY_FUNC
inline typename Params::color_type get_tex_color(
HR const& hr,
Params const& params,
std::integral_constant<int, 1> /* */
)
{
using P = typename Params::primitive_type;
using C = typename Params::color_type;
auto coord = get_tex_coord(params.tex_coords, hr, P{});
auto const& tex = params.textures[hr.geom_id];
return tex.width() > 0 ? C(visionaray::tex1D(tex, coord)) : C(1.0);
}
template <typename HR, typename Params>
VSNRAY_FUNC
inline typename Params::color_type get_tex_color(
HR const& hr,
Params const& params,
std::integral_constant<int, 2> /* */
)
{
using P = typename Params::primitive_type;
using C = typename Params::color_type;
auto coord = get_tex_coord(params.tex_coords, hr, P{});
auto const& tex = params.textures[hr.geom_id];
return tex.width() > 0 && tex.height() > 0
? C(visionaray::tex2D(tex, coord))
: C(1.0);
}
template <typename HR, typename Params>
VSNRAY_FUNC
inline typename Params::color_type get_tex_color(
HR const& hr,
Params const& params,
std::integral_constant<int, 3> /* */
)
{
using P = typename Params::primitive_type;
using C = typename Params::color_type;
auto coord = get_tex_coord(params.tex_coords, hr, P{});
auto const& tex = params.textures[hr.geom_id];
return tex.width() > 0 && tex.height() > 0 && tex.depth() > 0
? C(visionaray::tex3D(tex, coord))
: C(1.0);
}
//-------------------------------------------------------------------------------------------------
//
//
template <typename HR, typename Params>
VSNRAY_FUNC
inline auto get_surface_impl(
has_no_normals_tag /* */,
has_no_colors_tag /* */,
has_no_textures_tag /* */,
HR const& hr,
Params const& params
)
-> surface<typename Params::normal_type, typename Params::material_type>
{
auto ns = get_normal_dispatch(params, nullptr, hr);
return make_surface(
ns.geometric_normal,
ns.shading_normal,
params.materials[hr.geom_id]
);
}
template <typename HR, typename Params>
VSNRAY_FUNC
inline auto get_surface_impl(
has_normals_tag /* */,
has_no_colors_tag /* */,
has_no_textures_tag /* */,
HR const& hr,
Params const& params
)
-> surface<typename Params::normal_type, typename Params::material_type>
{
auto ns = get_normal_dispatch(params, params.normals, hr);
return make_surface(
ns.geometric_normal,
ns.shading_normal,
params.materials[hr.geom_id]
);
}
template <typename HR, typename Params>
VSNRAY_FUNC
inline auto get_surface_impl(
has_normals_tag /* */,
has_no_colors_tag /* */,
has_textures_tag /* */,
HR const& hr,
Params const& params
)
-> surface<
typename Params::normal_type,
typename Params::material_type,
typename Params::color_type
>
{
auto ns = get_normal_dispatch(params, params.normals, hr);
auto tc = get_tex_color(
hr,
params,
std::integral_constant<int, Params::texture_type::dimensions>{}
);
return make_surface(
ns.geometric_normal,
ns.shading_normal,
params.materials[hr.geom_id],
tc
);
}
template <typename HR, typename Params>
VSNRAY_FUNC
inline auto get_surface_impl(
has_no_normals_tag /* */,
has_colors_tag /* */,
has_textures_tag /* */,
HR const& hr,
Params const& params
)
-> surface<
typename Params::normal_type,
typename Params::material_type,
typename Params::color_type
>
{
using P = typename Params::primitive_type;
auto ns = get_normal_dispatch(params, nullptr, hr);
auto color = get_color(params.colors, hr, P{}, typename Params::color_binding{});
auto tc = get_tex_color(
hr,
params,
std::integral_constant<int, Params::texture_type::dimensions>{}
);
return make_surface(
ns.geometric_normal,
ns.shading_normal,
params.materials[hr.geom_id],
color * tc
);
}
template <typename HR, typename Params>
VSNRAY_FUNC
inline auto get_surface_impl(
has_normals_tag /* */,
has_colors_tag /* */,
has_textures_tag /* */,
HR const& hr,
Params const& params
)
-> surface<
typename Params::normal_type,
typename Params::material_type,
typename Params::color_type
>
{
using P = typename Params::primitive_type;
auto ns = get_normal_dispatch(params, params.normals, hr);
auto color = get_color(params.colors, hr, P{}, typename Params::color_binding{});
auto tc = get_tex_color(
hr,
params,
std::integral_constant<int, Params::texture_type::dimensions>{}
);
return make_surface(
ns.geometric_normal,
ns.shading_normal,
params.materials[hr.geom_id],
color * tc
);
}
//-------------------------------------------------------------------------------------------------
// SIMD
//
template <
typename NormalsTag,
typename ColorsTag,
typename TexturesTag,
template <typename, typename...> class HR,
typename T,
typename ...HRP,
typename Params,
typename = typename std::enable_if<simd::is_simd_vector<T>::value>::type
>
VSNRAY_FUNC
inline auto get_surface_impl(
NormalsTag /* */,
ColorsTag /* */,
TexturesTag /* */,
HR<basic_ray<T>, HRP...> const& hr,
Params const& params
)
-> typename simd_decl_surface<Params, T>::type
{
auto hrs = unpack(hr);
typename simd_decl_surface<Params, T>::array_type surfs;
for (int i = 0; i < simd::num_elements<T>::value; ++i)
{
if (hrs[i].hit)
{
surfs[i] = get_surface_impl(
NormalsTag{},
ColorsTag{},
TexturesTag{},
hrs[i],
params
);
}
}
return simd::pack(surfs);
}
} // detail
template <typename HR, typename Params>
VSNRAY_FUNC
inline auto get_surface(HR const& hr, Params const& p)
-> decltype( detail::get_surface_impl(
detail::has_normals<Params>{},
detail::has_colors<Params>{},
detail::has_textures<Params>{},
hr,
p
) )
{
return detail::get_surface_impl(
detail::has_normals<Params>{},
detail::has_colors<Params>{},
detail::has_textures<Params>{},
hr,
p
);
}
} // visionaray
#endif // VSNRAY_SURFACE_H
| {
"content_hash": "b73c14bd11bf2dfef0636dc3fb027ffd",
"timestamp": "",
"source": "github",
"line_count": 646,
"max_line_length": 108,
"avg_line_length": 28.924148606811144,
"alnum_prop": 0.5316028900187316,
"repo_name": "ukoeln-vis/ctpperf",
"id": "139c6408826fc9374c4ff2cb49faa19e2da50d29",
"size": "18685",
"binary": false,
"copies": "1",
"ref": "refs/heads/shading_benchmark_oop",
"path": "include/visionaray/get_surface.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "18705"
},
{
"name": "C++",
"bytes": "1569452"
},
{
"name": "CMake",
"bytes": "73951"
},
{
"name": "Cuda",
"bytes": "30287"
}
],
"symlink_target": ""
} |
import classnames from "classnames";
import {MithrilComponent} from "jsx/mithril-component";
import _ from "lodash";
import m from "mithril";
import Stream from "mithril/stream";
import {NameableSet} from "models/pipeline_configs/nameable_set";
import {PipelineConfig} from "models/pipeline_configs/pipeline_config";
import {Stage} from "models/pipeline_configs/stage";
import {Template} from "models/pipeline_configs/templates_cache";
import {Primary, Reset} from "views/components/buttons";
import {FlashMessage, MessageType} from "views/components/flash_message";
import {Option, SelectField, SelectFieldOptions} from "views/components/forms/input_fields";
import * as Icons from "views/components/icons/index";
import pipelineConfigStyles from "views/pages/clicky_pipeline_config/index.scss";
import {ConfirmationDialog} from "views/pages/pipeline_activity/confirmation_modal";
import styles from "../stages.scss";
interface Attrs {
readonly: boolean;
pipelineConfig: PipelineConfig;
templates: Stream<Template[]>;
pipelineConfigSave: () => Promise<any>;
pipelineConfigReset: () => Promise<any>;
isPipelineDefinedOriginallyFromTemplate: Stream<boolean>;
}
export class PipelineTemplateWidget extends MithrilComponent<Attrs> {
view(vnode: m.Vnode<Attrs>) {
const disableLinks = !vnode.attrs.pipelineConfig.isUsingTemplate();
const doesTemplatesExist = vnode.attrs.templates() && vnode.attrs.templates().length > 0;
if (!doesTemplatesExist) {
return (<FlashMessage type={MessageType.warning}>
<code>There are no templates configured or you are unauthorized to view the existing templates.
Add one via the <a href="/go/admin/templates" title="Pipeline Templates">templates page</a>.</code>
</FlashMessage>);
}
return <div>
<div class={styles.templateWrapper}>
{this.templateOptions(vnode)}
<div class={classnames(styles.templateLink, {[styles.disabled]: disableLinks})}
onclick={this.openViewTemplatePage.bind(this, vnode)}
data-test-id="view-template">
<Icons.View disabled={disableLinks} iconOnly={true}/> View
</div>
<div class={classnames(styles.templateLink, {[styles.disabled]: disableLinks})}
onclick={this.openEditTemplatePage.bind(this, vnode)}
data-test-id="edit-template">
<Icons.Edit disabled={disableLinks} iconOnly={true}/> Edit
</div>
</div>
{this.buttons(vnode)}
</div>;
}
templateOptions({attrs}: { attrs: Attrs }) {
const config = attrs.pipelineConfig;
const templatesAsOptions = _.map(attrs.templates(), (template: Template) => {
return {id: template.name, text: template.name} as Option;
});
return <SelectField label="Template"
property={config.template}
readonly={attrs.readonly}
errorText={config.errors().errorsForDisplay("template")}
onchange={this.clearStages.bind(this, attrs)}
required={true}>
<SelectFieldOptions selected={config.template()} items={templatesAsOptions}/>
</SelectField>;
}
private clearStages(attrs: Attrs) {
attrs.pipelineConfig.stages(new NameableSet<Stage>());
}
private openViewTemplatePage(vnode: m.Vnode<Attrs>) {
const template = vnode.attrs.pipelineConfig.template();
if (template) {
window.open(`/go/admin/templates#!${template}/view`);
}
}
private renderConfirmation(vnode: m.Vnode<Attrs>) {
const body = <p>Switching to a template will cause all of the currently defined stages in this pipeline to be lost.
Are you sure you want to continue?
</p>;
new ConfirmationDialog("Confirm Save", body, () => {
vnode.attrs.isPipelineDefinedOriginallyFromTemplate(true);
return vnode.attrs.pipelineConfigSave();
}).render();
}
private buttons(vnode: m.Vnode<Attrs>): m.Children {
if (vnode.attrs.readonly) {
return;
}
return <div className={pipelineConfigStyles.buttonContainer}>
<Reset data-test-id={"cancel"}
onclick={vnode.attrs.pipelineConfigReset}>
RESET
</Reset>
<Primary data-test-id={"save"}
disabled={!vnode.attrs.pipelineConfig.isUsingTemplate()}
onclick={this.renderConfirmation.bind(this, vnode)}>
SAVE
</Primary>
</div>;
}
private openEditTemplatePage(vnode: m.Vnode<Attrs>) {
const template = vnode.attrs.pipelineConfig.template();
if (template) {
window.open(`/go/admin/templates/${template}/general`);
}
}
}
| {
"content_hash": "56b3f4f6778d78e7b7173c9d56c59f28",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 119,
"avg_line_length": 38.396694214876035,
"alnum_prop": 0.6739130434782609,
"repo_name": "marques-work/gocd",
"id": "bed38703635db899ff03bd2c092664b631f78e4d",
"size": "5247",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "server/src/main/webapp/WEB-INF/rails/webpack/views/pages/clicky_pipeline_config/tabs/pipeline/stage/pipeline_template_widget.tsx",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "466"
},
{
"name": "CSS",
"bytes": "807605"
},
{
"name": "FreeMarker",
"bytes": "9759"
},
{
"name": "Groovy",
"bytes": "2317159"
},
{
"name": "HTML",
"bytes": "641338"
},
{
"name": "Java",
"bytes": "21014983"
},
{
"name": "JavaScript",
"bytes": "2539248"
},
{
"name": "NSIS",
"bytes": "23525"
},
{
"name": "PowerShell",
"bytes": "691"
},
{
"name": "Ruby",
"bytes": "1907011"
},
{
"name": "Shell",
"bytes": "169586"
},
{
"name": "TSQL",
"bytes": "200114"
},
{
"name": "TypeScript",
"bytes": "3423163"
},
{
"name": "XSLT",
"bytes": "203240"
}
],
"symlink_target": ""
} |
@interface MainAppGeneralViewController : NSViewController {
// The array holding all views with their positions in scrollview
NSMutableArray *viewControllers;
NSMutableArray *windowControllers;
BOOL initDone;
NSMutableArray *undockButtons;
}
// The scrollview and it's inside view
@property NSFlippedView *documentView;
@property (weak) IBOutlet NSScrollView *scrollView;
@end
| {
"content_hash": "0289880bb1a7a56878133fe0d43db589",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 67,
"avg_line_length": 30,
"alnum_prop": 0.8,
"repo_name": "voelkerb/iHouse",
"id": "72692f6cdd0892f553eeacaccf6b980c7ea091ad",
"size": "822",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "iHouse/iHouse/MainAppGeneralViewController.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Arduino",
"bytes": "61927"
},
{
"name": "C",
"bytes": "111145"
},
{
"name": "C++",
"bytes": "115906"
},
{
"name": "DTrace",
"bytes": "692"
},
{
"name": "Objective-C",
"bytes": "6540399"
},
{
"name": "Objective-C++",
"bytes": "11630"
},
{
"name": "Python",
"bytes": "23800"
},
{
"name": "Ruby",
"bytes": "8366"
},
{
"name": "Shell",
"bytes": "1262"
},
{
"name": "Swift",
"bytes": "39025"
}
],
"symlink_target": ""
} |
namespace loader {
SceneLoader::SceneLoader()
{
}
SceneLoader::~SceneLoader()
{
}
enum NodeType {
NONE = 0,
NODE = 1,
ENTITY = 2,
LIGHT = 3,
CAMERA = 4,
TERRIAN = 5,
};
lly::Node * parse_normal(const Json::Value& root)
{
lly::Node * ret = new lly::Node;
return ret;
}
lly::Node * parse_entity(const Json::Value& root)
{
lly::Entity * ret = new lly::Entity;
auto file = root["path"].asString();
auto mesh = lly::System::instance().get_resource_manager().load_mesh("zhaoyun_.fbx");
auto mesh_ptr = lly::System::instance().get_resource_manager().get_mesh(mesh);
ret->add_mesh(mesh_ptr);
ret->play_animation("Take 001", true);
return ret;
}
lly::Node * parse_light(const Json::Value& root)
{
lly::Light * ret = new lly::Light;
auto color = root["color"];
ret->set_color(glm::vec4(color["r"].asFloat(), color["g"].asFloat(), color["b"].asFloat(), color["a"].asFloat()));
auto type = root["light_type"].asInt();
switch (type)
{
case 0:
{
ret->set_type(lly::Light::Type::AMBIENT);
}
break;
case 1:
{
ret->set_type(lly::Light::Type::DIRECTIONAL);
auto direction = root["direction"];
ret->set_direction(glm::vec3(direction["x"].asFloat(), direction["y"].asFloat(), direction["z"].asFloat()));
}
break;
case 2:
{
ret->set_type(lly::Light::Type::POINT);
ret->set_constant(root["constant"].asFloat());
ret->set_linear(root["linear"].asFloat());
ret->set_quadratic(root["quadratic"].asFloat());
}
break;
case 3:
{
ret->set_type(lly::Light::Type::SPOT);
auto direction = root["direction"];
ret->set_direction(glm::vec3(color["x"].asFloat(), color["y"].asFloat(), color["z"].asFloat()));
ret->set_constant(root["constant"].asFloat());
ret->set_linear(root["linear"].asFloat());
ret->set_quadratic(root["quadratic"].asFloat());
ret->set_exp(root["exp"].asFloat());
ret->set_cutoff(root["cutoff"].asFloat());
}
break;
default:
throw std::logic_error("unsupport light type");
}
return ret;
}
lly::Node * parse_camera(const Json::Value& root)
{
lly::Camera * ret = new lly::Camera;
ret->set_order(root["order"].asInt());
auto n = root["near"].asFloat();
auto f = root["far"].asFloat();
auto type = root["camera_type"].asInt();
switch (type)
{
case 0:
{
auto fovy = root["fovy"].asFloat();
auto aspect = root["aspect"].asFloat();
ret->set_prespective(fovy, aspect, n, f);
}
break;
case 1:
{
auto bottom = root["bottom"].asFloat();
auto top = root["top"].asFloat();
auto right = root["right"].asFloat();
auto left = root["left"].asFloat();
ret->set_ortho(left, right, top, bottom, n, f);
}
break;
default:
throw std::logic_error("unsupport camera type");
}
return ret;
}
lly::Node * parse_terrian(const Json::Value& root)
{
auto width = root["width"].asFloat();
auto height = root["height"].asFloat();
auto row = root["row"].asInt();
auto col = root["col"].asInt();
auto file = root["file"].asString();
auto precision = root["precision"].asFloat();
lly::HeightMap height_map;
height_map.load_from_file(file, precision);
lly::Terrian * ret = new lly::Terrian;
ret->create(width, height, row, col, height_map);
return ret;
}
lly::Node * parse_scene_node(const Json::Value& root)
{
lly::Node * ret = nullptr;
auto type = root["type"].asInt();
switch (type)
{
case NodeType::NODE: ret = parse_normal(root); break;
case NodeType::ENTITY: ret = parse_entity(root); break;
case NodeType::LIGHT: ret = parse_light(root); break;
case NodeType::CAMERA: ret = parse_camera(root); break;
case NodeType::TERRIAN: ret = parse_terrian(root); break;
default:
throw std::logic_error("unsupport node type");
break;
}
ret->set_name(root["name"].asString());
auto position = root["position"];
ret->set_position(position["x"].asFloat(), position["y"].asFloat(), position["z"].asFloat());
auto rotation = root["rotation"];
ret->set_rotation(rotation["x"].asFloat() * M_PI / 180.0f, rotation["y"].asFloat() * M_PI / 180.0f, rotation["z"].asFloat() * M_PI / 180.0f);
auto scale = root["scale"];
ret->set_scale(scale["x"].asFloat(), scale["y"].asFloat(), scale["z"].asFloat());
auto node_count = root["children"].size();
for (int i = 0; i < node_count; ++i)
{
lly::Node * node = parse_scene_node(root["children"][i]);
ret->add_child(node);
node->set_parent(ret);
}
return ret;
}
lly::Scene * SceneLoader::load_from(const std::string& file)
{
lly_util::Data data = lly_util::load_from_file(file);
Json::Reader reader;
Json::Value root;
if (!reader.parse(data.data(), root))
{
throw std::logic_error("load scene file failed.");
}
lly::Scene * scene = new lly::Scene;
auto node_count = root["nodes"].size();
for (int i = 0; i < node_count; ++i)
{
lly::Node * node = parse_scene_node(root["nodes"][i]);
scene->add_node(node);
node->visit([&scene](lly::Node * node) {
node->add_to_scene(scene);
});
}
return scene;
}
}
| {
"content_hash": "f7a5246a14cde50131e836bd8052aba7",
"timestamp": "",
"source": "github",
"line_count": 198,
"max_line_length": 143,
"avg_line_length": 25.696969696969695,
"alnum_prop": 0.6092767295597484,
"repo_name": "ooeyusea/GameEngine",
"id": "a466e73ecce28b012018cd7b8e8ee85e19a18d22",
"size": "5411",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LLY/LLY/resource/loader/SceneLoader.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "815"
},
{
"name": "C++",
"bytes": "483711"
},
{
"name": "GLSL",
"bytes": "4293"
}
],
"symlink_target": ""
} |
i18n.map("nl", {
resetPasswordDialog: {
title: "Wachtwoord resetten",
newPassword: "Nieuw wachtwoord",
newPasswordAgain: "Nieuw wachtwoord (opnieuw)",
cancel: "Annuleren",
submit: "Wachtwoord instellen"
},
enrollAccountDialog: {
title: "Stel een wachtwoord in",
newPassword: "Nieuw wachtwoord",
newPasswordAgain: "Nieuw wachtwoord (opnieuw)",
cancel: "Sluiten",
submit: "Wachtwoord instellen"
},
justVerifiedEmailDialog: {
verified: "E-mailadres geverifieerd",
dismiss: "Sluiten"
},
loginButtonsMessagesDialog: {
dismiss: "Sluiten",
},
loginButtonsLoggedInDropdownActions: {
password: "Wachtwoord veranderen",
signOut: "Afmelden"
},
loginButtonsLoggedOutDropdown: {
signIn: "Aanmelden",
up: "Registreren"
},
loginButtonsLoggedOutPasswordServiceSeparator: {
or: "of"
},
loginButtonsLoggedOutPasswordService: {
create: "Aanmaken",
signIn: "Aanmelden",
forgot: "Wachtwoord vergeten?",
createAcc: "Account aanmaken"
},
forgotPasswordForm: {
email: "E-mailadres",
reset: "Wachtwoord opnieuw instellen",
invalidEmail: "Ongeldig e-mailadres"
},
loginButtonsBackToLoginLink: {
back: "Annuleren"
},
loginButtonsChangePassword: {
submit: "Wachtwoord veranderen",
cancel: "Annuleren"
},
loginButtonsLoggedOutSingleLoginButton: {
signInWith: "Aanmelden via",
configure: "Instellen",
},
loginButtonsLoggedInSingleLogoutButton: {
signOut: "Afmelden"
},
loginButtonsLoggedOut: {
noLoginServices: "Geen aanmelddienst ingesteld"
},
loginFields: {
usernameOrEmail: "Gebruikersnaam of e-mailadres",
username: "Gebruikersnaam",
email: "E-mailadres",
password: "Wachtwoord"
},
signupFields: {
username: "Gebruikersnaam",
email: "E-mailadres",
emailOpt: "E-mailadres (niet verplicht)",
password: "Wachtwoord",
passwordAgain: "Wachtwoord (opnieuw)"
},
changePasswordFields: {
currentPassword: "Huidig wachtwoord",
newPassword: "Nieuw wachtwoord",
newPasswordAgain: "Nieuw wachtwoord (opnieuw)"
},
infoMessages : {
emailSent: "E-mail verstuurd",
passwordChanged: "Wachtwoord veranderd"
},
errorMessages: {
genericTitle: "Er is een fout opgetreden",
userNotFound: "Gebruiker niet gevonden",
invalidEmail: "Ongeldig e-mailadres",
incorrectPassword: "Onjuist wachtwoord",
usernameTooShort: "De gebruikersnaam moet minimaal uit 3 tekens bestaan",
passwordTooShort: "Het wachtwoord moet minimaal uit 6 tekens bestaan",
passwordsDontMatch: "De wachtwoorden komen niet overeen",
newPasswordSameAsOld: "Het oude en het nieuwe wachtwoord mogen niet hetzelfde zijn",
signupsForbidden: "Aanmeldingen niet toegestaan"
}
});
| {
"content_hash": "fbae53695890531588727ae72cbca3de",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 86,
"avg_line_length": 27.74736842105263,
"alnum_prop": 0.7355842185128983,
"repo_name": "nikhilpi/klick",
"id": "e2e1b665c1f46671a8f3f1fea9e78bc9a941bd5b",
"size": "2636",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/meteor-accounts-ui-bootstrap-3/i18n/nl.i18n.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "38834"
},
{
"name": "CoffeeScript",
"bytes": "1193"
},
{
"name": "HTML",
"bytes": "45116"
},
{
"name": "JavaScript",
"bytes": "217222"
}
],
"symlink_target": ""
} |
<?php
namespace Magento\Store\Model\ResourceModel\Website;
/**
* Factory class for @see \Magento\Store\Model\ResourceModel\Website\Collection
*/
class CollectionFactory
{
/**
* Object Manager instance
*
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $_objectManager = null;
/**
* Instance name to create
*
* @var string
*/
protected $_instanceName = null;
/**
* Factory constructor
*
* @param \Magento\Framework\ObjectManagerInterface $objectManager
* @param string $instanceName
*/
public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager, $instanceName = '\\Magento\\Store\\Model\\ResourceModel\\Website\\Collection')
{
$this->_objectManager = $objectManager;
$this->_instanceName = $instanceName;
}
/**
* Create class instance with specified parameters
*
* @param array $data
* @return \Magento\Store\Model\ResourceModel\Website\Collection
*/
public function create(array $data = array())
{
return $this->_objectManager->create($this->_instanceName, $data);
}
}
| {
"content_hash": "4e770d66bddc6a9a522df794d31c7185",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 168,
"avg_line_length": 26.133333333333333,
"alnum_prop": 0.6445578231292517,
"repo_name": "tarikgwa/test",
"id": "e5ccd60442b0414d47bc1aec867bf0576a39977d",
"size": "1176",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "html/var/generation/Magento/Store/Model/ResourceModel/Website/CollectionFactory.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "26588"
},
{
"name": "CSS",
"bytes": "4874492"
},
{
"name": "HTML",
"bytes": "8635167"
},
{
"name": "JavaScript",
"bytes": "6810903"
},
{
"name": "PHP",
"bytes": "55645559"
},
{
"name": "Perl",
"bytes": "7938"
},
{
"name": "Shell",
"bytes": "4505"
},
{
"name": "XSLT",
"bytes": "19889"
}
],
"symlink_target": ""
} |
import React, { Component } from 'react'
import LoginForm from '../components/LoginForm'
import auth from '../http/auth'
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {actions as snackBarActions} from '../reducers/snackBar'
import styles from './Styles';
import { SubmissionError } from 'redux-form'
class Login extends Component {
render() {
const {router, location, openSnackBar} = this.props;
return (
<div style={styles.page}>
<LoginForm router={router} openSnackBar={openSnackBar}/>
</div>
)
}
}
export default connect(state => state, dispatch => bindActionCreators(snackBarActions, dispatch))(Login);
| {
"content_hash": "e23cc4a766565a781d2020b46de5bf34",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 105,
"avg_line_length": 25.77777777777778,
"alnum_prop": 0.6939655172413793,
"repo_name": "wanyine/vr-store-frontend",
"id": "bc391ccc769d822befbac4b1b31f094ee1fb363a",
"size": "696",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/containers/LoginPage.js",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "569"
},
{
"name": "HTML",
"bytes": "816"
},
{
"name": "JavaScript",
"bytes": "40532"
}
],
"symlink_target": ""
} |
package com.linecorp.armeria.server.docs;
import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Map;
import org.apache.thrift.meta_data.StructMetaData;
import org.apache.thrift.protocol.TType;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.linecorp.armeria.common.SerializationFormat;
import com.linecorp.armeria.service.test.thrift.main.FooService;
import com.linecorp.armeria.service.test.thrift.main.FooService.bar3_args;
import com.linecorp.armeria.service.test.thrift.main.FooStruct;
public class ServiceInfoTest {
@Test
public void fooServiceTest() throws Exception {
final ServiceInfo service =
ServiceInfo.of(FooService.class,
Arrays.asList(
EndpointInfo.of("*", "/foo", SerializationFormat.THRIFT_BINARY,
EnumSet.of(SerializationFormat.THRIFT_BINARY)),
EndpointInfo.of("*", "/debug/foo", SerializationFormat.THRIFT_TEXT,
EnumSet.of(SerializationFormat.THRIFT_TEXT))),
ImmutableMap.of(bar3_args.class, new bar3_args().setIntVal(10)));
assertThat(service.endpoints(), hasSize(2));
// Should be sorted alphabetically
assertThat(service.endpoints(),
contains(EndpointInfo.of("*", "/debug/foo", SerializationFormat.THRIFT_TEXT,
EnumSet.of(SerializationFormat.THRIFT_TEXT)),
EndpointInfo.of("*", "/foo", SerializationFormat.THRIFT_BINARY,
EnumSet.of(SerializationFormat.THRIFT_BINARY))));
final Map<String, FunctionInfo> functions = service.functions();
assertThat(functions.size(), is(5));
final FunctionInfo bar1 = functions.get("bar1");
assertThat(bar1.parameters().isEmpty(), is(true));
assertThat(bar1.returnType(), is(TypeInfo.VOID));
assertThat(bar1.exceptions().size(), is(1));
assertEquals("", bar1.sampleJsonRequest());
final TypeInfo string = TypeInfo.of(ValueType.STRING, false);
final FunctionInfo bar2 = functions.get("bar2");
assertThat(bar2.parameters().isEmpty(), is(true));
assertThat(bar2.returnType(), is(string));
assertThat(bar2.exceptions().size(), is(1));
assertEquals("", bar2.sampleJsonRequest());
final StructInfo foo = StructInfo.of(new StructMetaData(TType.STRUCT, FooStruct.class));
final FunctionInfo bar3 = functions.get("bar3");
assertThat(bar3.parameters().size(), is(2));
assertThat(bar3.parameters().get(0),
is(FieldInfo.of("intVal", RequirementType.DEFAULT, TypeInfo.of(ValueType.I32, false))));
assertThat(bar3.parameters().get(1), is(FieldInfo.of("foo", RequirementType.DEFAULT, foo)));
assertThat(bar3.returnType(), is(foo));
assertThat(bar3.exceptions().size(), is(1));
assertJsonEquals("{\"intVal\": 10}", bar3.sampleJsonRequest());
final FunctionInfo bar4 = functions.get("bar4");
assertThat(bar4.parameters().size(), is(1));
assertThat(bar4.parameters().get(0),
is(FieldInfo.of("foos", RequirementType.DEFAULT, ListInfo.of(foo))));
assertThat(bar4.returnType(), is(ListInfo.of(foo)));
assertThat(bar4.exceptions().size(), is(1));
assertEquals("", bar4.sampleJsonRequest());
final FunctionInfo bar5 = functions.get("bar5");
assertThat(bar5.parameters().size(), is(1));
assertThat(bar5.parameters().get(0),
is(FieldInfo.of("foos", RequirementType.DEFAULT, MapInfo.of(string, foo))));
assertThat(bar5.returnType(), is(MapInfo.of(string, foo)));
assertThat(bar5.exceptions().size(), is(1));
assertEquals("", bar5.sampleJsonRequest());
}
}
| {
"content_hash": "8a54942edd70de6970e24a47946867b6",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 107,
"avg_line_length": 47.75555555555555,
"alnum_prop": 0.6321544904606794,
"repo_name": "synk/armeria",
"id": "5299cd786061e894b724cea044ff2a1cf6c00acf",
"size": "4930",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/test/java/com/linecorp/armeria/server/docs/ServiceInfoTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "22445"
},
{
"name": "HTML",
"bytes": "21620"
},
{
"name": "Java",
"bytes": "1187508"
},
{
"name": "JavaScript",
"bytes": "11959"
},
{
"name": "Python",
"bytes": "2940"
},
{
"name": "Thrift",
"bytes": "58650"
}
],
"symlink_target": ""
} |
=======================
Integrating with Django
=======================
Since Django is currently the most famous Python web framework, this chapter explains how to plot graphs using pyFlot template tags.
| {
"content_hash": "f2b7c019c9e8fc3a4a5d6da9592c3aaa",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 132,
"avg_line_length": 41.2,
"alnum_prop": 0.6359223300970874,
"repo_name": "andrefsp/pyflot",
"id": "915a28cebf6b93b7a021884be248e35ae19b1b50",
"size": "206",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/integrating-with-django.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "119052"
},
{
"name": "Python",
"bytes": "36606"
},
{
"name": "Shell",
"bytes": "4106"
}
],
"symlink_target": ""
} |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at [email protected]
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System.Xml;
namespace Subtext.ImportExport
{
public interface IBlogMLWriter
{
void Write(XmlWriter writer);
}
}
| {
"content_hash": "1c27fe837c9490b4dc8842ea550a1698",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 99,
"avg_line_length": 31.03846153846154,
"alnum_prop": 0.5489467162329615,
"repo_name": "jeuvin/Subtext",
"id": "903990daf651988edce6ece1c55306e291c63513",
"size": "809",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/Subtext.Framework/ImportExport/IBlogMLWriter.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "1237950"
},
{
"name": "Batchfile",
"bytes": "301"
},
{
"name": "C#",
"bytes": "4386066"
},
{
"name": "CSS",
"bytes": "530006"
},
{
"name": "ColdFusion",
"bytes": "8968"
},
{
"name": "HTML",
"bytes": "1983395"
},
{
"name": "JavaScript",
"bytes": "2397173"
},
{
"name": "PHP",
"bytes": "11178"
},
{
"name": "Pascal",
"bytes": "1670"
},
{
"name": "Perl",
"bytes": "9294"
}
],
"symlink_target": ""
} |
#include <aws/config/model/ResourceType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace ConfigService
{
namespace Model
{
namespace ResourceTypeMapper
{
static const int AWS_EC2_CustomerGateway_HASH = HashingUtils::HashString("AWS::EC2::CustomerGateway");
static const int AWS_EC2_EIP_HASH = HashingUtils::HashString("AWS::EC2::EIP");
static const int AWS_EC2_Host_HASH = HashingUtils::HashString("AWS::EC2::Host");
static const int AWS_EC2_Instance_HASH = HashingUtils::HashString("AWS::EC2::Instance");
static const int AWS_EC2_InternetGateway_HASH = HashingUtils::HashString("AWS::EC2::InternetGateway");
static const int AWS_EC2_NetworkAcl_HASH = HashingUtils::HashString("AWS::EC2::NetworkAcl");
static const int AWS_EC2_NetworkInterface_HASH = HashingUtils::HashString("AWS::EC2::NetworkInterface");
static const int AWS_EC2_RouteTable_HASH = HashingUtils::HashString("AWS::EC2::RouteTable");
static const int AWS_EC2_SecurityGroup_HASH = HashingUtils::HashString("AWS::EC2::SecurityGroup");
static const int AWS_EC2_Subnet_HASH = HashingUtils::HashString("AWS::EC2::Subnet");
static const int AWS_CloudTrail_Trail_HASH = HashingUtils::HashString("AWS::CloudTrail::Trail");
static const int AWS_EC2_Volume_HASH = HashingUtils::HashString("AWS::EC2::Volume");
static const int AWS_EC2_VPC_HASH = HashingUtils::HashString("AWS::EC2::VPC");
static const int AWS_EC2_VPNConnection_HASH = HashingUtils::HashString("AWS::EC2::VPNConnection");
static const int AWS_EC2_VPNGateway_HASH = HashingUtils::HashString("AWS::EC2::VPNGateway");
static const int AWS_IAM_Group_HASH = HashingUtils::HashString("AWS::IAM::Group");
static const int AWS_IAM_Policy_HASH = HashingUtils::HashString("AWS::IAM::Policy");
static const int AWS_IAM_Role_HASH = HashingUtils::HashString("AWS::IAM::Role");
static const int AWS_IAM_User_HASH = HashingUtils::HashString("AWS::IAM::User");
static const int AWS_ACM_Certificate_HASH = HashingUtils::HashString("AWS::ACM::Certificate");
static const int AWS_RDS_DBInstance_HASH = HashingUtils::HashString("AWS::RDS::DBInstance");
static const int AWS_RDS_DBSubnetGroup_HASH = HashingUtils::HashString("AWS::RDS::DBSubnetGroup");
static const int AWS_RDS_DBSecurityGroup_HASH = HashingUtils::HashString("AWS::RDS::DBSecurityGroup");
static const int AWS_RDS_DBSnapshot_HASH = HashingUtils::HashString("AWS::RDS::DBSnapshot");
static const int AWS_RDS_EventSubscription_HASH = HashingUtils::HashString("AWS::RDS::EventSubscription");
static const int AWS_ElasticLoadBalancingV2_LoadBalancer_HASH = HashingUtils::HashString("AWS::ElasticLoadBalancingV2::LoadBalancer");
static const int AWS_S3_Bucket_HASH = HashingUtils::HashString("AWS::S3::Bucket");
static const int AWS_SSM_ManagedInstanceInventory_HASH = HashingUtils::HashString("AWS::SSM::ManagedInstanceInventory");
static const int AWS_Redshift_Cluster_HASH = HashingUtils::HashString("AWS::Redshift::Cluster");
static const int AWS_Redshift_ClusterSnapshot_HASH = HashingUtils::HashString("AWS::Redshift::ClusterSnapshot");
static const int AWS_Redshift_ClusterParameterGroup_HASH = HashingUtils::HashString("AWS::Redshift::ClusterParameterGroup");
static const int AWS_Redshift_ClusterSecurityGroup_HASH = HashingUtils::HashString("AWS::Redshift::ClusterSecurityGroup");
static const int AWS_Redshift_ClusterSubnetGroup_HASH = HashingUtils::HashString("AWS::Redshift::ClusterSubnetGroup");
static const int AWS_Redshift_EventSubscription_HASH = HashingUtils::HashString("AWS::Redshift::EventSubscription");
static const int AWS_CloudWatch_Alarm_HASH = HashingUtils::HashString("AWS::CloudWatch::Alarm");
static const int AWS_CloudFormation_Stack_HASH = HashingUtils::HashString("AWS::CloudFormation::Stack");
static const int AWS_DynamoDB_Table_HASH = HashingUtils::HashString("AWS::DynamoDB::Table");
static const int AWS_AutoScaling_AutoScalingGroup_HASH = HashingUtils::HashString("AWS::AutoScaling::AutoScalingGroup");
static const int AWS_AutoScaling_LaunchConfiguration_HASH = HashingUtils::HashString("AWS::AutoScaling::LaunchConfiguration");
static const int AWS_AutoScaling_ScalingPolicy_HASH = HashingUtils::HashString("AWS::AutoScaling::ScalingPolicy");
static const int AWS_AutoScaling_ScheduledAction_HASH = HashingUtils::HashString("AWS::AutoScaling::ScheduledAction");
static const int AWS_CodeBuild_Project_HASH = HashingUtils::HashString("AWS::CodeBuild::Project");
static const int AWS_WAF_RateBasedRule_HASH = HashingUtils::HashString("AWS::WAF::RateBasedRule");
static const int AWS_WAF_Rule_HASH = HashingUtils::HashString("AWS::WAF::Rule");
static const int AWS_WAF_WebACL_HASH = HashingUtils::HashString("AWS::WAF::WebACL");
static const int AWS_WAFRegional_RateBasedRule_HASH = HashingUtils::HashString("AWS::WAFRegional::RateBasedRule");
static const int AWS_WAFRegional_Rule_HASH = HashingUtils::HashString("AWS::WAFRegional::Rule");
static const int AWS_WAFRegional_WebACL_HASH = HashingUtils::HashString("AWS::WAFRegional::WebACL");
static const int AWS_CloudFront_Distribution_HASH = HashingUtils::HashString("AWS::CloudFront::Distribution");
static const int AWS_CloudFront_StreamingDistribution_HASH = HashingUtils::HashString("AWS::CloudFront::StreamingDistribution");
static const int AWS_WAF_RuleGroup_HASH = HashingUtils::HashString("AWS::WAF::RuleGroup");
static const int AWS_WAFRegional_RuleGroup_HASH = HashingUtils::HashString("AWS::WAFRegional::RuleGroup");
static const int AWS_Lambda_Function_HASH = HashingUtils::HashString("AWS::Lambda::Function");
static const int AWS_ElasticBeanstalk_Application_HASH = HashingUtils::HashString("AWS::ElasticBeanstalk::Application");
static const int AWS_ElasticBeanstalk_ApplicationVersion_HASH = HashingUtils::HashString("AWS::ElasticBeanstalk::ApplicationVersion");
static const int AWS_ElasticBeanstalk_Environment_HASH = HashingUtils::HashString("AWS::ElasticBeanstalk::Environment");
static const int AWS_ElasticLoadBalancing_LoadBalancer_HASH = HashingUtils::HashString("AWS::ElasticLoadBalancing::LoadBalancer");
static const int AWS_XRay_EncryptionConfig_HASH = HashingUtils::HashString("AWS::XRay::EncryptionConfig");
static const int AWS_SSM_AssociationCompliance_HASH = HashingUtils::HashString("AWS::SSM::AssociationCompliance");
static const int AWS_SSM_PatchCompliance_HASH = HashingUtils::HashString("AWS::SSM::PatchCompliance");
static const int AWS_Shield_Protection_HASH = HashingUtils::HashString("AWS::Shield::Protection");
static const int AWS_ShieldRegional_Protection_HASH = HashingUtils::HashString("AWS::ShieldRegional::Protection");
static const int AWS_Config_ResourceCompliance_HASH = HashingUtils::HashString("AWS::Config::ResourceCompliance");
static const int AWS_CodePipeline_Pipeline_HASH = HashingUtils::HashString("AWS::CodePipeline::Pipeline");
ResourceType GetResourceTypeForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == AWS_EC2_CustomerGateway_HASH)
{
return ResourceType::AWS_EC2_CustomerGateway;
}
else if (hashCode == AWS_EC2_EIP_HASH)
{
return ResourceType::AWS_EC2_EIP;
}
else if (hashCode == AWS_EC2_Host_HASH)
{
return ResourceType::AWS_EC2_Host;
}
else if (hashCode == AWS_EC2_Instance_HASH)
{
return ResourceType::AWS_EC2_Instance;
}
else if (hashCode == AWS_EC2_InternetGateway_HASH)
{
return ResourceType::AWS_EC2_InternetGateway;
}
else if (hashCode == AWS_EC2_NetworkAcl_HASH)
{
return ResourceType::AWS_EC2_NetworkAcl;
}
else if (hashCode == AWS_EC2_NetworkInterface_HASH)
{
return ResourceType::AWS_EC2_NetworkInterface;
}
else if (hashCode == AWS_EC2_RouteTable_HASH)
{
return ResourceType::AWS_EC2_RouteTable;
}
else if (hashCode == AWS_EC2_SecurityGroup_HASH)
{
return ResourceType::AWS_EC2_SecurityGroup;
}
else if (hashCode == AWS_EC2_Subnet_HASH)
{
return ResourceType::AWS_EC2_Subnet;
}
else if (hashCode == AWS_CloudTrail_Trail_HASH)
{
return ResourceType::AWS_CloudTrail_Trail;
}
else if (hashCode == AWS_EC2_Volume_HASH)
{
return ResourceType::AWS_EC2_Volume;
}
else if (hashCode == AWS_EC2_VPC_HASH)
{
return ResourceType::AWS_EC2_VPC;
}
else if (hashCode == AWS_EC2_VPNConnection_HASH)
{
return ResourceType::AWS_EC2_VPNConnection;
}
else if (hashCode == AWS_EC2_VPNGateway_HASH)
{
return ResourceType::AWS_EC2_VPNGateway;
}
else if (hashCode == AWS_IAM_Group_HASH)
{
return ResourceType::AWS_IAM_Group;
}
else if (hashCode == AWS_IAM_Policy_HASH)
{
return ResourceType::AWS_IAM_Policy;
}
else if (hashCode == AWS_IAM_Role_HASH)
{
return ResourceType::AWS_IAM_Role;
}
else if (hashCode == AWS_IAM_User_HASH)
{
return ResourceType::AWS_IAM_User;
}
else if (hashCode == AWS_ACM_Certificate_HASH)
{
return ResourceType::AWS_ACM_Certificate;
}
else if (hashCode == AWS_RDS_DBInstance_HASH)
{
return ResourceType::AWS_RDS_DBInstance;
}
else if (hashCode == AWS_RDS_DBSubnetGroup_HASH)
{
return ResourceType::AWS_RDS_DBSubnetGroup;
}
else if (hashCode == AWS_RDS_DBSecurityGroup_HASH)
{
return ResourceType::AWS_RDS_DBSecurityGroup;
}
else if (hashCode == AWS_RDS_DBSnapshot_HASH)
{
return ResourceType::AWS_RDS_DBSnapshot;
}
else if (hashCode == AWS_RDS_EventSubscription_HASH)
{
return ResourceType::AWS_RDS_EventSubscription;
}
else if (hashCode == AWS_ElasticLoadBalancingV2_LoadBalancer_HASH)
{
return ResourceType::AWS_ElasticLoadBalancingV2_LoadBalancer;
}
else if (hashCode == AWS_S3_Bucket_HASH)
{
return ResourceType::AWS_S3_Bucket;
}
else if (hashCode == AWS_SSM_ManagedInstanceInventory_HASH)
{
return ResourceType::AWS_SSM_ManagedInstanceInventory;
}
else if (hashCode == AWS_Redshift_Cluster_HASH)
{
return ResourceType::AWS_Redshift_Cluster;
}
else if (hashCode == AWS_Redshift_ClusterSnapshot_HASH)
{
return ResourceType::AWS_Redshift_ClusterSnapshot;
}
else if (hashCode == AWS_Redshift_ClusterParameterGroup_HASH)
{
return ResourceType::AWS_Redshift_ClusterParameterGroup;
}
else if (hashCode == AWS_Redshift_ClusterSecurityGroup_HASH)
{
return ResourceType::AWS_Redshift_ClusterSecurityGroup;
}
else if (hashCode == AWS_Redshift_ClusterSubnetGroup_HASH)
{
return ResourceType::AWS_Redshift_ClusterSubnetGroup;
}
else if (hashCode == AWS_Redshift_EventSubscription_HASH)
{
return ResourceType::AWS_Redshift_EventSubscription;
}
else if (hashCode == AWS_CloudWatch_Alarm_HASH)
{
return ResourceType::AWS_CloudWatch_Alarm;
}
else if (hashCode == AWS_CloudFormation_Stack_HASH)
{
return ResourceType::AWS_CloudFormation_Stack;
}
else if (hashCode == AWS_DynamoDB_Table_HASH)
{
return ResourceType::AWS_DynamoDB_Table;
}
else if (hashCode == AWS_AutoScaling_AutoScalingGroup_HASH)
{
return ResourceType::AWS_AutoScaling_AutoScalingGroup;
}
else if (hashCode == AWS_AutoScaling_LaunchConfiguration_HASH)
{
return ResourceType::AWS_AutoScaling_LaunchConfiguration;
}
else if (hashCode == AWS_AutoScaling_ScalingPolicy_HASH)
{
return ResourceType::AWS_AutoScaling_ScalingPolicy;
}
else if (hashCode == AWS_AutoScaling_ScheduledAction_HASH)
{
return ResourceType::AWS_AutoScaling_ScheduledAction;
}
else if (hashCode == AWS_CodeBuild_Project_HASH)
{
return ResourceType::AWS_CodeBuild_Project;
}
else if (hashCode == AWS_WAF_RateBasedRule_HASH)
{
return ResourceType::AWS_WAF_RateBasedRule;
}
else if (hashCode == AWS_WAF_Rule_HASH)
{
return ResourceType::AWS_WAF_Rule;
}
else if (hashCode == AWS_WAF_WebACL_HASH)
{
return ResourceType::AWS_WAF_WebACL;
}
else if (hashCode == AWS_WAFRegional_RateBasedRule_HASH)
{
return ResourceType::AWS_WAFRegional_RateBasedRule;
}
else if (hashCode == AWS_WAFRegional_Rule_HASH)
{
return ResourceType::AWS_WAFRegional_Rule;
}
else if (hashCode == AWS_WAFRegional_WebACL_HASH)
{
return ResourceType::AWS_WAFRegional_WebACL;
}
else if (hashCode == AWS_CloudFront_Distribution_HASH)
{
return ResourceType::AWS_CloudFront_Distribution;
}
else if (hashCode == AWS_CloudFront_StreamingDistribution_HASH)
{
return ResourceType::AWS_CloudFront_StreamingDistribution;
}
else if (hashCode == AWS_WAF_RuleGroup_HASH)
{
return ResourceType::AWS_WAF_RuleGroup;
}
else if (hashCode == AWS_WAFRegional_RuleGroup_HASH)
{
return ResourceType::AWS_WAFRegional_RuleGroup;
}
else if (hashCode == AWS_Lambda_Function_HASH)
{
return ResourceType::AWS_Lambda_Function;
}
else if (hashCode == AWS_ElasticBeanstalk_Application_HASH)
{
return ResourceType::AWS_ElasticBeanstalk_Application;
}
else if (hashCode == AWS_ElasticBeanstalk_ApplicationVersion_HASH)
{
return ResourceType::AWS_ElasticBeanstalk_ApplicationVersion;
}
else if (hashCode == AWS_ElasticBeanstalk_Environment_HASH)
{
return ResourceType::AWS_ElasticBeanstalk_Environment;
}
else if (hashCode == AWS_ElasticLoadBalancing_LoadBalancer_HASH)
{
return ResourceType::AWS_ElasticLoadBalancing_LoadBalancer;
}
else if (hashCode == AWS_XRay_EncryptionConfig_HASH)
{
return ResourceType::AWS_XRay_EncryptionConfig;
}
else if (hashCode == AWS_SSM_AssociationCompliance_HASH)
{
return ResourceType::AWS_SSM_AssociationCompliance;
}
else if (hashCode == AWS_SSM_PatchCompliance_HASH)
{
return ResourceType::AWS_SSM_PatchCompliance;
}
else if (hashCode == AWS_Shield_Protection_HASH)
{
return ResourceType::AWS_Shield_Protection;
}
else if (hashCode == AWS_ShieldRegional_Protection_HASH)
{
return ResourceType::AWS_ShieldRegional_Protection;
}
else if (hashCode == AWS_Config_ResourceCompliance_HASH)
{
return ResourceType::AWS_Config_ResourceCompliance;
}
else if (hashCode == AWS_CodePipeline_Pipeline_HASH)
{
return ResourceType::AWS_CodePipeline_Pipeline;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<ResourceType>(hashCode);
}
return ResourceType::NOT_SET;
}
Aws::String GetNameForResourceType(ResourceType enumValue)
{
switch(enumValue)
{
case ResourceType::AWS_EC2_CustomerGateway:
return "AWS::EC2::CustomerGateway";
case ResourceType::AWS_EC2_EIP:
return "AWS::EC2::EIP";
case ResourceType::AWS_EC2_Host:
return "AWS::EC2::Host";
case ResourceType::AWS_EC2_Instance:
return "AWS::EC2::Instance";
case ResourceType::AWS_EC2_InternetGateway:
return "AWS::EC2::InternetGateway";
case ResourceType::AWS_EC2_NetworkAcl:
return "AWS::EC2::NetworkAcl";
case ResourceType::AWS_EC2_NetworkInterface:
return "AWS::EC2::NetworkInterface";
case ResourceType::AWS_EC2_RouteTable:
return "AWS::EC2::RouteTable";
case ResourceType::AWS_EC2_SecurityGroup:
return "AWS::EC2::SecurityGroup";
case ResourceType::AWS_EC2_Subnet:
return "AWS::EC2::Subnet";
case ResourceType::AWS_CloudTrail_Trail:
return "AWS::CloudTrail::Trail";
case ResourceType::AWS_EC2_Volume:
return "AWS::EC2::Volume";
case ResourceType::AWS_EC2_VPC:
return "AWS::EC2::VPC";
case ResourceType::AWS_EC2_VPNConnection:
return "AWS::EC2::VPNConnection";
case ResourceType::AWS_EC2_VPNGateway:
return "AWS::EC2::VPNGateway";
case ResourceType::AWS_IAM_Group:
return "AWS::IAM::Group";
case ResourceType::AWS_IAM_Policy:
return "AWS::IAM::Policy";
case ResourceType::AWS_IAM_Role:
return "AWS::IAM::Role";
case ResourceType::AWS_IAM_User:
return "AWS::IAM::User";
case ResourceType::AWS_ACM_Certificate:
return "AWS::ACM::Certificate";
case ResourceType::AWS_RDS_DBInstance:
return "AWS::RDS::DBInstance";
case ResourceType::AWS_RDS_DBSubnetGroup:
return "AWS::RDS::DBSubnetGroup";
case ResourceType::AWS_RDS_DBSecurityGroup:
return "AWS::RDS::DBSecurityGroup";
case ResourceType::AWS_RDS_DBSnapshot:
return "AWS::RDS::DBSnapshot";
case ResourceType::AWS_RDS_EventSubscription:
return "AWS::RDS::EventSubscription";
case ResourceType::AWS_ElasticLoadBalancingV2_LoadBalancer:
return "AWS::ElasticLoadBalancingV2::LoadBalancer";
case ResourceType::AWS_S3_Bucket:
return "AWS::S3::Bucket";
case ResourceType::AWS_SSM_ManagedInstanceInventory:
return "AWS::SSM::ManagedInstanceInventory";
case ResourceType::AWS_Redshift_Cluster:
return "AWS::Redshift::Cluster";
case ResourceType::AWS_Redshift_ClusterSnapshot:
return "AWS::Redshift::ClusterSnapshot";
case ResourceType::AWS_Redshift_ClusterParameterGroup:
return "AWS::Redshift::ClusterParameterGroup";
case ResourceType::AWS_Redshift_ClusterSecurityGroup:
return "AWS::Redshift::ClusterSecurityGroup";
case ResourceType::AWS_Redshift_ClusterSubnetGroup:
return "AWS::Redshift::ClusterSubnetGroup";
case ResourceType::AWS_Redshift_EventSubscription:
return "AWS::Redshift::EventSubscription";
case ResourceType::AWS_CloudWatch_Alarm:
return "AWS::CloudWatch::Alarm";
case ResourceType::AWS_CloudFormation_Stack:
return "AWS::CloudFormation::Stack";
case ResourceType::AWS_DynamoDB_Table:
return "AWS::DynamoDB::Table";
case ResourceType::AWS_AutoScaling_AutoScalingGroup:
return "AWS::AutoScaling::AutoScalingGroup";
case ResourceType::AWS_AutoScaling_LaunchConfiguration:
return "AWS::AutoScaling::LaunchConfiguration";
case ResourceType::AWS_AutoScaling_ScalingPolicy:
return "AWS::AutoScaling::ScalingPolicy";
case ResourceType::AWS_AutoScaling_ScheduledAction:
return "AWS::AutoScaling::ScheduledAction";
case ResourceType::AWS_CodeBuild_Project:
return "AWS::CodeBuild::Project";
case ResourceType::AWS_WAF_RateBasedRule:
return "AWS::WAF::RateBasedRule";
case ResourceType::AWS_WAF_Rule:
return "AWS::WAF::Rule";
case ResourceType::AWS_WAF_WebACL:
return "AWS::WAF::WebACL";
case ResourceType::AWS_WAFRegional_RateBasedRule:
return "AWS::WAFRegional::RateBasedRule";
case ResourceType::AWS_WAFRegional_Rule:
return "AWS::WAFRegional::Rule";
case ResourceType::AWS_WAFRegional_WebACL:
return "AWS::WAFRegional::WebACL";
case ResourceType::AWS_CloudFront_Distribution:
return "AWS::CloudFront::Distribution";
case ResourceType::AWS_CloudFront_StreamingDistribution:
return "AWS::CloudFront::StreamingDistribution";
case ResourceType::AWS_WAF_RuleGroup:
return "AWS::WAF::RuleGroup";
case ResourceType::AWS_WAFRegional_RuleGroup:
return "AWS::WAFRegional::RuleGroup";
case ResourceType::AWS_Lambda_Function:
return "AWS::Lambda::Function";
case ResourceType::AWS_ElasticBeanstalk_Application:
return "AWS::ElasticBeanstalk::Application";
case ResourceType::AWS_ElasticBeanstalk_ApplicationVersion:
return "AWS::ElasticBeanstalk::ApplicationVersion";
case ResourceType::AWS_ElasticBeanstalk_Environment:
return "AWS::ElasticBeanstalk::Environment";
case ResourceType::AWS_ElasticLoadBalancing_LoadBalancer:
return "AWS::ElasticLoadBalancing::LoadBalancer";
case ResourceType::AWS_XRay_EncryptionConfig:
return "AWS::XRay::EncryptionConfig";
case ResourceType::AWS_SSM_AssociationCompliance:
return "AWS::SSM::AssociationCompliance";
case ResourceType::AWS_SSM_PatchCompliance:
return "AWS::SSM::PatchCompliance";
case ResourceType::AWS_Shield_Protection:
return "AWS::Shield::Protection";
case ResourceType::AWS_ShieldRegional_Protection:
return "AWS::ShieldRegional::Protection";
case ResourceType::AWS_Config_ResourceCompliance:
return "AWS::Config::ResourceCompliance";
case ResourceType::AWS_CodePipeline_Pipeline:
return "AWS::CodePipeline::Pipeline";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return "";
}
}
} // namespace ResourceTypeMapper
} // namespace Model
} // namespace ConfigService
} // namespace Aws
| {
"content_hash": "1f219c9d4462627f94cd898ca41a271d",
"timestamp": "",
"source": "github",
"line_count": 501,
"max_line_length": 142,
"avg_line_length": 48.10578842315369,
"alnum_prop": 0.628687606323389,
"repo_name": "JoyIfBam5/aws-sdk-cpp",
"id": "691cb5ddc501eda9a103fc45b469e9d41020383a",
"size": "24674",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-config/source/model/ResourceType.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "11868"
},
{
"name": "C++",
"bytes": "167818064"
},
{
"name": "CMake",
"bytes": "591577"
},
{
"name": "HTML",
"bytes": "4471"
},
{
"name": "Java",
"bytes": "271801"
},
{
"name": "Python",
"bytes": "85650"
},
{
"name": "Shell",
"bytes": "5277"
}
],
"symlink_target": ""
} |
/******/ (function(modules) { // webpackBootstrap
/******/ // install a JSONP callback for chunk loading
/******/ var parentJsonpFunction = window["webpackJsonp"];
/******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules) {
/******/ // add "moreModules" to the modules object,
/******/ // then flag all "chunkIds" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0, callbacks = [];
/******/ for(;i < chunkIds.length; i++) {
/******/ chunkId = chunkIds[i];
/******/ if(installedChunks[chunkId])
/******/ callbacks.push.apply(callbacks, installedChunks[chunkId]);
/******/ installedChunks[chunkId] = 0;
/******/ }
/******/ for(moduleId in moreModules) {
/******/ modules[moduleId] = moreModules[moduleId];
/******/ }
/******/ if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules);
/******/ while(callbacks.length)
/******/ callbacks.shift().call(null, __webpack_require__);
/******/ if(moreModules[0]) {
/******/ installedModules[0] = 0;
/******/ return __webpack_require__(0);
/******/ }
/******/ };
/******/ // The module cache
/******/ var installedModules = {};
/******/ // object to store loaded and loading chunks
/******/ // "0" means "already loaded"
/******/ // Array means "loading", array contains callbacks
/******/ var installedChunks = {
/******/ 3:0
/******/ };
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // This file contains only the entry chunk.
/******/ // The chunk loading function for additional chunks
/******/ __webpack_require__.e = function requireEnsure(chunkId, callback) {
/******/ // "0" is the signal for "already loaded"
/******/ if(installedChunks[chunkId] === 0)
/******/ return callback.call(null, __webpack_require__);
/******/ // an array means "currently loading".
/******/ if(installedChunks[chunkId] !== undefined) {
/******/ installedChunks[chunkId].push(callback);
/******/ } else {
/******/ // start chunk loading
/******/ installedChunks[chunkId] = [callback];
/******/ var head = document.getElementsByTagName('head')[0];
/******/ var script = document.createElement('script');
/******/ script.type = 'text/javascript';
/******/ script.charset = 'utf-8';
/******/ script.async = true;
/******/ script.src = __webpack_require__.p + "" + chunkId + "." + ({"0":"A","1":"B"}[chunkId]||chunkId) + ".js";
/******/ head.appendChild(script);
/******/ }
/******/ };
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ })
/************************************************************************/
/******/ ([
/* 0 */,
/* 1 */
/***/ function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ }
/******/ ]); | {
"content_hash": "33d2110ec52cbc230533c5407439fb7c",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 116,
"avg_line_length": 35.931372549019606,
"alnum_prop": 0.5298772169167804,
"repo_name": "MingXingTeam/webpack-react-starter",
"id": "d730981970da123e945d47a996e20e52e22331cc",
"size": "3665",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/webpack/ex7/js/commons.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1133"
},
{
"name": "HTML",
"bytes": "3870"
},
{
"name": "JavaScript",
"bytes": "119453"
}
],
"symlink_target": ""
} |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('openstack', '0002_volumetype'),
]
operations = [
migrations.AlterField(
model_name='floatingip',
name='description',
field=models.CharField(
blank=True, max_length=2000, verbose_name='description'
),
),
migrations.AlterField(
model_name='network',
name='description',
field=models.CharField(
blank=True, max_length=2000, verbose_name='description'
),
),
migrations.AlterField(
model_name='securitygroup',
name='description',
field=models.CharField(
blank=True, max_length=2000, verbose_name='description'
),
),
migrations.AlterField(
model_name='subnet',
name='description',
field=models.CharField(
blank=True, max_length=2000, verbose_name='description'
),
),
migrations.AlterField(
model_name='tenant',
name='description',
field=models.CharField(
blank=True, max_length=2000, verbose_name='description'
),
),
migrations.AlterField(
model_name='volumetype',
name='description',
field=models.CharField(
blank=True, max_length=2000, verbose_name='description'
),
),
]
| {
"content_hash": "76ea9ac4d3cf37f9bd4419973f0432b9",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 71,
"avg_line_length": 29.69811320754717,
"alnum_prop": 0.5158831003811944,
"repo_name": "opennode/waldur-mastermind",
"id": "7e4266cd10eb5cac38beeb1aac908f7f2da3b9cd",
"size": "1624",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "src/waldur_openstack/openstack/migrations/0003_extend_description_limits.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4429"
},
{
"name": "Dockerfile",
"bytes": "6258"
},
{
"name": "HTML",
"bytes": "42329"
},
{
"name": "JavaScript",
"bytes": "729"
},
{
"name": "Python",
"bytes": "5520019"
},
{
"name": "Shell",
"bytes": "15429"
}
],
"symlink_target": ""
} |
namespace CantHelpFallingInLove
{
public sealed class Note
{
public Note(Pitch pitch, int duration)
{
m_pitch = pitch;
m_duration = duration;
}
public Pitch Pitch
{
get { return m_pitch; }
}
public int Duration
{
get { return m_duration; }
}
private readonly Pitch m_pitch;
private readonly int m_duration;
}
}
| {
"content_hash": "b090e62f4d42f25e9210206af2401f8c",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 46,
"avg_line_length": 19.291666666666668,
"alnum_prop": 0.4946004319654428,
"repo_name": "steinz/CantHelpFallingInLove",
"id": "90d47e50be3bee3f391afb06692a176f138f0bb8",
"size": "465",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "CantHelpFallingInLove/Note.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "13378"
},
{
"name": "Haskell",
"bytes": "1840"
}
],
"symlink_target": ""
} |
package org.apache.helix.messaging.handling;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
import com.google.common.collect.ImmutableList;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.NotificationContext;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.messaging.DefaultMessagingService;
import org.apache.helix.model.ConfigScope;
import org.apache.helix.model.Message;
import org.apache.helix.model.builder.ConfigScopeBuilder;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestConfigThreadpoolSize extends ZkStandAloneCMTestBase {
public static class TestMessagingHandlerFactory implements MultiTypeMessageHandlerFactory {
public static HashSet<String> _processedMsgIds = new HashSet<String>();
@Override
public MessageHandler createHandler(Message message, NotificationContext context) {
return null;
}
@Override
public String getMessageType() {
return "TestMsg";
}
@Override public List<String> getMessageTypes() {
return ImmutableList.of("TestMsg");
}
@Override
public void reset() {
// TODO Auto-generated method stub
}
}
public static class TestMessagingHandlerFactory2 implements MultiTypeMessageHandlerFactory {
public static HashSet<String> _processedMsgIds = new HashSet<String>();
@Override
public MessageHandler createHandler(Message message, NotificationContext context) {
return null;
}
@Override
public String getMessageType() {
return "TestMsg2";
}
@Override public List<String> getMessageTypes() {
return ImmutableList.of("TestMsg2");
}
@Override
public void reset() {
// TODO Auto-generated method stub
}
}
@Test
public void TestThreadPoolSizeConfig() {
String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + 0);
HelixManager manager = _participants[0];
ConfigAccessor accessor = manager.getConfigAccessor();
ConfigScope scope =
new ConfigScopeBuilder().forCluster(manager.getClusterName()).forParticipant(instanceName)
.build();
accessor.set(scope, "TestMsg." + HelixTaskExecutor.MAX_THREADS, "" + 12);
scope = new ConfigScopeBuilder().forCluster(manager.getClusterName()).build();
accessor.set(scope, "TestMsg." + HelixTaskExecutor.MAX_THREADS, "" + 8);
for (int i = 0; i < NODE_NR; i++) {
instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_participants[i].getMessagingService().registerMessageHandlerFactory("TestMsg",
new TestMessagingHandlerFactory());
_participants[i].getMessagingService()
.registerMessageHandlerFactory("TestMsg2", new TestMessagingHandlerFactory2());
}
for (int i = 0; i < NODE_NR; i++) {
instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
DefaultMessagingService svc =
(DefaultMessagingService) (_participants[i]
.getMessagingService());
HelixTaskExecutor helixExecutor = svc.getExecutor();
ThreadPoolExecutor executor =
(ThreadPoolExecutor) (helixExecutor._executorMap.get("TestMsg"));
ThreadPoolExecutor executor2 =
(ThreadPoolExecutor) (helixExecutor._executorMap.get("TestMsg2"));
if (i != 0) {
Assert.assertEquals(8, executor.getMaximumPoolSize());
} else {
Assert.assertEquals(12, executor.getMaximumPoolSize());
}
Assert.assertEquals(HelixTaskExecutor.DEFAULT_PARALLEL_TASKS, executor2.getMaximumPoolSize());
}
}
}
| {
"content_hash": "620a890b44052a4b64aeb5df589fbd55",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 100,
"avg_line_length": 31.94782608695652,
"alnum_prop": 0.7074033750680457,
"repo_name": "lei-xia/helix",
"id": "eee40e38950e94955a4b5b29da5a7d57ed681136",
"size": "4481",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "helix-core/src/test/java/org/apache/helix/messaging/handling/TestConfigThreadpoolSize.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "1275"
},
{
"name": "CSS",
"bytes": "8751"
},
{
"name": "HTML",
"bytes": "45086"
},
{
"name": "Java",
"bytes": "6361970"
},
{
"name": "JavaScript",
"bytes": "2052"
},
{
"name": "Pascal",
"bytes": "1940"
},
{
"name": "Python",
"bytes": "185190"
},
{
"name": "Shell",
"bytes": "142958"
},
{
"name": "SourcePawn",
"bytes": "1247"
},
{
"name": "TypeScript",
"bytes": "158324"
}
],
"symlink_target": ""
} |
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.test.bpmn.event.message;
import java.util.List;
import org.camunda.bpm.engine.impl.EventSubscriptionQueryImpl;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase;
import org.camunda.bpm.engine.runtime.EventSubscription;
import org.camunda.bpm.engine.runtime.Execution;
import org.camunda.bpm.engine.runtime.ExecutionQuery;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.test.util.TestExecutionListener;
/**
* @author Daniel Meyer
* @author Falko Menge
* @author Danny Gräf
*/
public class MessageEventSubprocessTest extends PluggableProcessEngineTestCase {
@Override
protected void tearDown() throws Exception {
try {
super.tearDown();
} finally {
TestExecutionListener.reset();
}
}
@Deployment
public void testInterruptingUnderProcessDefinition() {
testInterruptingUnderProcessDefinition(1);
}
/**
* Checks if unused event subscriptions are properly deleted.
*/
@Deployment
public void testTwoInterruptingUnderProcessDefinition() {
testInterruptingUnderProcessDefinition(2);
}
private void testInterruptingUnderProcessDefinition(int expectedNumberOfEventSubscriptions) {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("process");
// the process instance must have a message event subscription:
Execution execution = runtimeService.createExecutionQuery()
.executionId(processInstance.getId())
.messageEventSubscriptionName("newMessage")
.singleResult();
assertNotNull(execution);
assertEquals(expectedNumberOfEventSubscriptions, createEventSubscriptionQuery().count());
assertEquals(1, runtimeService.createExecutionQuery().count());
// if we trigger the usertask, the process terminates and the event subscription is removed:
Task task = taskService.createTaskQuery().singleResult();
assertEquals("task", task.getTaskDefinitionKey());
taskService.complete(task.getId());
assertProcessEnded(processInstance.getId());
assertEquals(0, createEventSubscriptionQuery().count());
assertEquals(0, runtimeService.createExecutionQuery().count());
// now we start a new instance but this time we trigger the event subprocess:
processInstance = runtimeService.startProcessInstanceByKey("process");
runtimeService.messageEventReceived("newMessage", processInstance.getId());
task = taskService.createTaskQuery().singleResult();
assertEquals("eventSubProcessTask", task.getTaskDefinitionKey());
taskService.complete(task.getId());
assertProcessEnded(processInstance.getId());
assertEquals(0, createEventSubscriptionQuery().count());
assertEquals(0, runtimeService.createExecutionQuery().count());
}
@Deployment
public void testEventSubprocessListenersInvoked() {
runtimeService.startProcessInstanceByKey("testProcess");
runtimeService.correlateMessage("message");
Task taskInEventSubProcess = taskService.createTaskQuery().singleResult();
assertEquals("taskInEventSubProcess", taskInEventSubProcess.getTaskDefinitionKey());
taskService.complete(taskInEventSubProcess.getId());
List<String> collectedEvents = TestExecutionListener.collectedEvents;
assertEquals("taskInMainFlow-start", collectedEvents.get(0));
assertEquals("taskInMainFlow-end", collectedEvents.get(1));
assertEquals("eventSubProcess-start", collectedEvents.get(2));
assertEquals("startEventInSubProcess-start", collectedEvents.get(3));
assertEquals("startEventInSubProcess-end", collectedEvents.get(4));
assertEquals("taskInEventSubProcess-start", collectedEvents.get(5));
assertEquals("taskInEventSubProcess-end", collectedEvents.get(6));
assertEquals("eventSubProcess-end", collectedEvents.get(7));
if (processEngineConfiguration.getHistoryLevel().getId() > ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE) {
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("taskInMainFlow").canceled().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("startEventInSubProcess").finished().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("taskInEventSubProcess").finished().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("endEventInSubProcess").finished().count());
// SEE: CAM-1755
// assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("eventSubProcess").finished().count());
}
}
@Deployment
public void testNonInterruptingEventSubprocessListenersInvoked() {
runtimeService.startProcessInstanceByKey("testProcess");
runtimeService.correlateMessage("message");
Task taskInMainFlow = taskService.createTaskQuery().taskDefinitionKey("taskInMainFlow").singleResult();
assertNotNull(taskInMainFlow);
Task taskInEventSubProcess = taskService.createTaskQuery().taskDefinitionKey("taskInEventSubProcess").singleResult();
assertNotNull(taskInEventSubProcess);
taskService.complete(taskInMainFlow.getId());
taskService.complete(taskInEventSubProcess.getId());
List<String> collectedEvents = TestExecutionListener.collectedEvents;
assertEquals("taskInMainFlow-start", collectedEvents.get(0));
assertEquals("eventSubProcess-start", collectedEvents.get(1));
assertEquals("startEventInSubProcess-start", collectedEvents.get(2));
assertEquals("startEventInSubProcess-end", collectedEvents.get(3));
assertEquals("taskInEventSubProcess-start", collectedEvents.get(4));
assertEquals("taskInMainFlow-end", collectedEvents.get(5));
assertEquals("taskInEventSubProcess-end", collectedEvents.get(6));
assertEquals("eventSubProcess-end", collectedEvents.get(7));
if (processEngineConfiguration.getHistoryLevel().getId() > ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE) {
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("startEventInSubProcess").finished().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("taskInMainFlow").finished().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("taskInEventSubProcess").finished().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("endEventInSubProcess").finished().count());
// SEE: CAM-1755
// assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("eventSubProcess").finished().count());
}
}
@Deployment
public void testNestedEventSubprocessListenersInvoked() {
runtimeService.startProcessInstanceByKey("testProcess");
runtimeService.correlateMessage("message");
Task taskInEventSubProcess = taskService.createTaskQuery().singleResult();
assertEquals("taskInEventSubProcess", taskInEventSubProcess.getTaskDefinitionKey());
taskService.complete(taskInEventSubProcess.getId());
List<String> collectedEvents = TestExecutionListener.collectedEvents;
assertEquals("taskInMainFlow-start", collectedEvents.get(0));
assertEquals("taskInMainFlow-end", collectedEvents.get(1));
assertEquals("eventSubProcess-start", collectedEvents.get(2));
assertEquals("startEventInSubProcess-start", collectedEvents.get(3));
assertEquals("startEventInSubProcess-end", collectedEvents.get(4));
assertEquals("taskInEventSubProcess-start", collectedEvents.get(5));
assertEquals("taskInEventSubProcess-end", collectedEvents.get(6));
assertEquals("eventSubProcess-end", collectedEvents.get(7));
if (processEngineConfiguration.getHistoryLevel().getId() > ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE) {
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("taskInMainFlow").canceled().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("startEventInSubProcess").finished().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("taskInEventSubProcess").finished().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("endEventInSubProcess").finished().count());
// SEE: CAM-1755
// assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("eventSubProcess").finished().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("subProcess").finished().count());
}
}
@Deployment
public void testNestedNonInterruptingEventSubprocessListenersInvoked() {
runtimeService.startProcessInstanceByKey("testProcess");
runtimeService.correlateMessage("message");
Task taskInMainFlow = taskService.createTaskQuery().taskDefinitionKey("taskInMainFlow").singleResult();
assertNotNull(taskInMainFlow);
Task taskInEventSubProcess = taskService.createTaskQuery().taskDefinitionKey("taskInEventSubProcess").singleResult();
assertNotNull(taskInEventSubProcess);
taskService.complete(taskInMainFlow.getId());
taskService.complete(taskInEventSubProcess.getId());
List<String> collectedEvents = TestExecutionListener.collectedEvents;
assertEquals("taskInMainFlow-start", collectedEvents.get(0));
assertEquals("eventSubProcess-start", collectedEvents.get(1));
assertEquals("startEventInSubProcess-start", collectedEvents.get(2));
assertEquals("startEventInSubProcess-end", collectedEvents.get(3));
assertEquals("taskInEventSubProcess-start", collectedEvents.get(4));
assertEquals("taskInMainFlow-end", collectedEvents.get(5));
assertEquals("taskInEventSubProcess-end", collectedEvents.get(6));
assertEquals("eventSubProcess-end", collectedEvents.get(7));
if (processEngineConfiguration.getHistoryLevel().getId() > ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE) {
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("taskInMainFlow").finished().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("startEventInSubProcess").finished().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("taskInEventSubProcess").finished().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("endEventInSubProcess").finished().count());
// SEE: CAM-1755
// assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("eventSubProcess").finished().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("subProcess").finished().count());
}
}
@Deployment
public void testEventSubprocessBoundaryListenersInvoked() {
runtimeService.startProcessInstanceByKey("testProcess");
runtimeService.correlateMessage("message");
Task taskInEventSubProcess = taskService.createTaskQuery().singleResult();
assertEquals("taskInEventSubProcess", taskInEventSubProcess.getTaskDefinitionKey());
runtimeService.correlateMessage("message2");
List<String> collectedEvents = TestExecutionListener.collectedEvents;
assertEquals("taskInMainFlow-start", collectedEvents.get(0));
assertEquals("taskInMainFlow-end", collectedEvents.get(1));
assertEquals("eventSubProcess-start", collectedEvents.get(2));
assertEquals("startEventInSubProcess-start", collectedEvents.get(3));
assertEquals("startEventInSubProcess-end", collectedEvents.get(4));
assertEquals("taskInEventSubProcess-start", collectedEvents.get(5));
assertEquals("taskInEventSubProcess-end", collectedEvents.get(6));
assertEquals("eventSubProcess-end", collectedEvents.get(7));
if (processEngineConfiguration.getHistoryLevel().getId() > ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE) {
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("taskInMainFlow").finished().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("taskInMainFlow").canceled().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("startEventInSubProcess").finished().count());
assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("taskInEventSubProcess").canceled().count());
// SEE: CAM-1755
// assertEquals(1, historyService.createHistoricActivityInstanceQuery().activityId("eventSubProcess").finished().count());
}
}
@Deployment
public void testNonInterruptingUnderProcessDefinition() {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("process");
// the process instance must have a message event subscription:
Execution execution = runtimeService.createExecutionQuery()
.executionId(processInstance.getId())
.messageEventSubscriptionName("newMessage")
.singleResult();
assertNotNull(execution);
assertEquals(1, createEventSubscriptionQuery().count());
assertEquals(1, runtimeService.createExecutionQuery().count());
// if we trigger the usertask, the process terminates and the event subscription is removed:
Task task = taskService.createTaskQuery().singleResult();
assertEquals("task", task.getTaskDefinitionKey());
taskService.complete(task.getId());
assertProcessEnded(processInstance.getId());
assertEquals(0, createEventSubscriptionQuery().count());
assertEquals(0, runtimeService.createExecutionQuery().count());
// ###################### now we start a new instance but this time we trigger the event subprocess:
processInstance = runtimeService.startProcessInstanceByKey("process");
runtimeService.messageEventReceived("newMessage", processInstance.getId());
assertEquals(2, taskService.createTaskQuery().count());
// now let's first complete the task in the main flow:
task = taskService.createTaskQuery().taskDefinitionKey("task").singleResult();
taskService.complete(task.getId());
// we still have 1 executions:
assertEquals(1, runtimeService.createExecutionQuery().count());
// now let's complete the task in the event subprocess
task = taskService.createTaskQuery().taskDefinitionKey("eventSubProcessTask").singleResult();
taskService.complete(task.getId());
// done!
assertProcessEnded(processInstance.getId());
assertEquals(0, runtimeService.createExecutionQuery().count());
// #################### again, the other way around:
processInstance = runtimeService.startProcessInstanceByKey("process");
runtimeService.messageEventReceived("newMessage", processInstance.getId());
assertEquals(2, taskService.createTaskQuery().count());
task = taskService.createTaskQuery().taskDefinitionKey("eventSubProcessTask").singleResult();
taskService.complete(task.getId());
// we still have 1 execution:
assertEquals(1, runtimeService.createExecutionQuery().count());
task = taskService.createTaskQuery().taskDefinitionKey("task").singleResult();
taskService.complete(task.getId());
// done!
assertProcessEnded(processInstance.getId());
assertEquals(0, runtimeService.createExecutionQuery().count());
}
@Deployment
public void testNonInterruptingUnderProcessDefinitionScope() {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("process");
// the process instance must have a message event subscription:
Execution execution = runtimeService.createExecutionQuery()
.messageEventSubscriptionName("newMessage")
.singleResult();
assertNotNull(execution);
assertEquals(1, createEventSubscriptionQuery().count());
assertEquals(2, runtimeService.createExecutionQuery().count());
// if we trigger the usertask, the process terminates and the event subscription is removed:
Task task = taskService.createTaskQuery().singleResult();
assertEquals("task", task.getTaskDefinitionKey());
taskService.complete(task.getId());
assertProcessEnded(processInstance.getId());
assertEquals(0, createEventSubscriptionQuery().count());
assertEquals(0, runtimeService.createExecutionQuery().count());
// ###################### now we start a new instance but this time we trigger the event subprocess:
processInstance = runtimeService.startProcessInstanceByKey("process");
runtimeService.correlateMessage("newMessage");
assertEquals(2, taskService.createTaskQuery().count());
assertEquals(1, createEventSubscriptionQuery().count());
// now let's first complete the task in the main flow:
task = taskService.createTaskQuery().taskDefinitionKey("task").singleResult();
taskService.complete(task.getId());
// we still have 1 executions:
assertEquals(1, runtimeService.createExecutionQuery().count());
// now let's complete the task in the event subprocess
task = taskService.createTaskQuery().taskDefinitionKey("eventSubProcessTask").singleResult();
taskService.complete(task.getId());
// done!
assertProcessEnded(processInstance.getId());
assertEquals(0, runtimeService.createExecutionQuery().count());
// #################### again, the other way around:
processInstance = runtimeService.startProcessInstanceByKey("process");
runtimeService.correlateMessage("newMessage");
assertEquals(2, taskService.createTaskQuery().count());
task = taskService.createTaskQuery().taskDefinitionKey("eventSubProcessTask").singleResult();
taskService.complete(task.getId());
// we still have 2 executions (usertask in main flow is scope):
assertEquals(2, runtimeService.createExecutionQuery().count());
task = taskService.createTaskQuery().taskDefinitionKey("task").singleResult();
taskService.complete(task.getId());
// done!
assertProcessEnded(processInstance.getId());
assertEquals(0, runtimeService.createExecutionQuery().count());
}
@Deployment
public void testNonInterruptingInEmbeddedSubprocess() {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("process");
// the process instance must have a message event subscription:
Execution execution = runtimeService.createExecutionQuery()
.messageEventSubscriptionName("newMessage")
.singleResult();
assertNotNull(execution);
assertEquals(1, createEventSubscriptionQuery().count());
// if we trigger the usertask, the process terminates and the event subscription is removed:
Task task = taskService.createTaskQuery().singleResult();
assertEquals("task", task.getTaskDefinitionKey());
taskService.complete(task.getId());
assertProcessEnded(processInstance.getId());
assertEquals(0, createEventSubscriptionQuery().count());
assertEquals(0, runtimeService.createExecutionQuery().count());
// ###################### now we start a new instance but this time we trigger the event subprocess:
processInstance = runtimeService.startProcessInstanceByKey("process");
runtimeService.correlateMessage("newMessage");
assertEquals(2, taskService.createTaskQuery().count());
// now let's first complete the task in the main flow:
task = taskService.createTaskQuery().taskDefinitionKey("task").singleResult();
taskService.complete(task.getId());
// we still have 2 executions:
assertEquals(2, runtimeService.createExecutionQuery().count());
// now let's complete the task in the event subprocess
task = taskService.createTaskQuery().taskDefinitionKey("eventSubProcessTask").singleResult();
taskService.complete(task.getId());
// done!
assertProcessEnded(processInstance.getId());
assertEquals(0, runtimeService.createExecutionQuery().count());
// #################### again, the other way around:
processInstance = runtimeService.startProcessInstanceByKey("process");
runtimeService.correlateMessage("newMessage");
assertEquals(2, taskService.createTaskQuery().count());
task = taskService.createTaskQuery().taskDefinitionKey("eventSubProcessTask").singleResult();
taskService.complete(task.getId());
// we still have 1 execution:
assertEquals(2, runtimeService.createExecutionQuery().count());
task = taskService.createTaskQuery().taskDefinitionKey("task").singleResult();
taskService.complete(task.getId());
// done!
assertProcessEnded(processInstance.getId());
assertEquals(0, runtimeService.createExecutionQuery().count());
}
@Deployment
public void testMultipleNonInterruptingInEmbeddedSubprocess() {
runtimeService.startProcessInstanceByKey("process");
// the process instance must have a message event subscription:
Execution subProcess = runtimeService.createExecutionQuery()
.messageEventSubscriptionName("newMessage")
.singleResult();
assertNotNull(subProcess);
assertEquals(1, createEventSubscriptionQuery().count());
Task subProcessTask = taskService.createTaskQuery().taskDefinitionKey("subProcessTask").singleResult();
assertNotNull(subProcessTask);
// start event sub process multiple times
for (int i = 1; i < 3; i++) {
runtimeService.messageEventReceived("newMessage", subProcess.getId());
// check that now i event sub process tasks exist
List<Task> eventSubProcessTasks = taskService.createTaskQuery().taskDefinitionKey("eventSubProcessTask").list();
assertEquals(i, eventSubProcessTasks.size());
// check that the parent execution of the event sub process task execution is the parent
// sub process
String taskExecutionId = eventSubProcessTasks.get(i-1).getExecutionId();
ExecutionEntity taskExecution = (ExecutionEntity) runtimeService.createExecutionQuery().executionId(taskExecutionId).singleResult();
assertEquals(subProcess.getId(), taskExecution.getParentId());
}
// complete sub process task
taskService.complete(subProcessTask.getId());
// after complete the sub process task all task should be deleted because of the terminating end event
assertEquals(0, taskService.createTaskQuery().count());
// and the process instance should be ended
assertEquals(0, runtimeService.createProcessInstanceQuery().count());
}
private EventSubscriptionQueryImpl createEventSubscriptionQuery() {
return new EventSubscriptionQueryImpl(processEngineConfiguration.getCommandExecutorTxRequired());
}
@Deployment
public void testNonInterruptingInMultiParallelEmbeddedSubprocess() {
// #################### I. start process and only complete the tasks
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("process");
// assert execution tree: scope (process) > scope (subprocess) > 2 x subprocess + usertask
assertEquals(6, runtimeService.createExecutionQuery().count());
// expect: two subscriptions, one for each instance
assertEquals(2, runtimeService.createEventSubscriptionQuery().count());
// expect: two subprocess instances, i.e. two tasks created
List<Task> tasks = taskService.createTaskQuery().list();
// then: complete both tasks
for (Task task : tasks) {
assertEquals("subUserTask", task.getTaskDefinitionKey());
taskService.complete(task.getId());
}
// expect: the event subscriptions are removed
assertEquals(0, runtimeService.createEventSubscriptionQuery().count());
// then: complete the last task of the main process
taskService.complete(taskService.createTaskQuery().singleResult().getId());
assertProcessEnded(processInstance.getId());
// #################### II. start process and correlate messages to trigger subprocesses instantiation
processInstance = runtimeService.startProcessInstanceByKey("process");
for (EventSubscription es : runtimeService.createEventSubscriptionQuery().list()) {
runtimeService.messageEventReceived("message", es.getExecutionId()); // trigger
}
// expect: both subscriptions are remaining and they can be re-triggered as long as the subprocesses are active
assertEquals(2, runtimeService.createEventSubscriptionQuery().count());
// expect: two additional task, one for each triggered process
tasks = taskService.createTaskQuery().taskName("Message User Task").list();
assertEquals(2, tasks.size());
for (Task task : tasks) { // complete both tasks
taskService.complete(task.getId());
}
// then: complete one subprocess
taskService.complete(taskService.createTaskQuery().taskName("Sub User Task").list().get(0).getId());
// expect: only the subscription of the second subprocess instance is left
assertEquals(1, runtimeService.createEventSubscriptionQuery().count());
// then: trigger the second subprocess again
runtimeService.messageEventReceived("message",
runtimeService.createEventSubscriptionQuery().singleResult().getExecutionId());
// expect: one message subprocess task exist
assertEquals(1, taskService.createTaskQuery().taskName("Message User Task").list().size());
// then: complete all inner subprocess tasks
tasks = taskService.createTaskQuery().list();
for (Task task : tasks) {
taskService.complete(task.getId());
}
// expect: no subscription is left
assertEquals(0, runtimeService.createEventSubscriptionQuery().count());
// then: complete the last task of the main process
taskService.complete(taskService.createTaskQuery().singleResult().getId());
assertProcessEnded(processInstance.getId());
}
@Deployment
public void testNonInterruptingInMultiSequentialEmbeddedSubprocess() {
// start process and trigger the first message sub process
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("process");
runtimeService.messageEventReceived("message", runtimeService.createEventSubscriptionQuery().singleResult().getExecutionId());
// expect: one subscription is remaining for the first instance
assertEquals(1, runtimeService.createEventSubscriptionQuery().count());
// then: complete both tasks (subprocess and message subprocess)
taskService.complete(taskService.createTaskQuery().taskName("Message User Task").singleResult().getId());
taskService.complete(taskService.createTaskQuery().taskName("Sub User Task").list().get(0).getId());
// expect: the second instance is started
assertEquals(1, runtimeService.createEventSubscriptionQuery().count());
// then: just complete this
taskService.complete(taskService.createTaskQuery().taskName("Sub User Task").list().get(0).getId());
// expect: no subscription is left
assertEquals(0, runtimeService.createEventSubscriptionQuery().count());
// then: complete the last task of the main process
taskService.complete(taskService.createTaskQuery().singleResult().getId());
assertProcessEnded(processInstance.getId());
}
@Deployment
public void testNonInterruptingWithParallelForkInsideEmbeddedSubProcess() {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("process");
runtimeService.messageEventReceived("newMessage", runtimeService.createEventSubscriptionQuery().singleResult().getExecutionId());
ExecutionQuery executionQuery = runtimeService.createExecutionQuery();
String forkId = executionQuery
.processInstanceId(processInstance.getId())
.activityId("fork")
.singleResult()
.getId();
Execution eventSubProcessTaskExecution = executionQuery
.processInstanceId(processInstance.getId())
.activityId("eventSubProcessTask")
.singleResult();
ExecutionEntity executionEntity = (ExecutionEntity) eventSubProcessTaskExecution;
assertEquals(forkId, executionEntity.getParentId());
List<Task> tasks = taskService.createTaskQuery().list();
for (Task task : tasks) {
taskService.complete(task.getId());
}
assertProcessEnded(processInstance.getId());
}
@Deployment
public void testNonInterruptingWithReceiveTask() {
String processInstanceId = runtimeService.startProcessInstanceByKey("process").getId();
// when (1)
runtimeService.correlateMessage("firstMessage");
// then (1)
assertEquals(1, taskService.createTaskQuery().count());
Task task1 = taskService.createTaskQuery()
.taskDefinitionKey("eventSubProcessTask")
.singleResult();
assertNotNull(task1);
Execution task1Execution = runtimeService
.createExecutionQuery()
.activityId("eventSubProcessTask")
.singleResult();
assertEquals(processInstanceId, ((ExecutionEntity) task1Execution).getParentId());
// when (2)
runtimeService.correlateMessage("secondMessage");
// then (2)
assertEquals(2, taskService.createTaskQuery().count());
task1 = taskService.createTaskQuery()
.taskDefinitionKey("eventSubProcessTask")
.singleResult();
assertNotNull(task1);
task1Execution = runtimeService
.createExecutionQuery()
.activityId("eventSubProcessTask")
.singleResult();
assertEquals(processInstanceId, ((ExecutionEntity) task1Execution).getParentId());
Task task2 = taskService.createTaskQuery()
.taskDefinitionKey("userTask")
.singleResult();
assertNotNull(task2);
Execution task2Execution = runtimeService
.createExecutionQuery()
.activityId("userTask")
.singleResult();
assertEquals(processInstanceId, ((ExecutionEntity) task2Execution).getParentId());
assertEquals(1, runtimeService.createEventSubscriptionQuery().count());
taskService.complete(task1.getId());
taskService.complete(task2.getId());
assertProcessEnded(processInstanceId);
}
@Deployment
public void testNonInterruptingWithReceiveTaskInsideEmbeddedSubProcess() {
String processInstanceId = runtimeService.startProcessInstanceByKey("process").getId();
// when (1)
runtimeService.correlateMessage("firstMessage");
// then (1)
assertEquals(1, taskService.createTaskQuery().count());
Task task1 = taskService.createTaskQuery()
.taskDefinitionKey("eventSubProcessTask")
.singleResult();
assertNotNull(task1);
Execution task1Execution = runtimeService
.createExecutionQuery()
.activityId("eventSubProcessTask")
.singleResult();
assertFalse(processInstanceId.equals(((ExecutionEntity) task1Execution).getParentId()));
// when (2)
runtimeService.correlateMessage("secondMessage");
// then (2)
assertEquals(2, taskService.createTaskQuery().count());
task1 = taskService.createTaskQuery()
.taskDefinitionKey("eventSubProcessTask")
.singleResult();
assertNotNull(task1);
task1Execution = runtimeService
.createExecutionQuery()
.activityId("eventSubProcessTask")
.singleResult();
assertFalse(processInstanceId.equals(((ExecutionEntity) task1Execution).getParentId()));
Task task2 = taskService.createTaskQuery()
.taskDefinitionKey("userTask")
.singleResult();
assertNotNull(task2);
Execution task2Execution = runtimeService
.createExecutionQuery()
.activityId("eventSubProcessTask")
.singleResult();
assertFalse(processInstanceId.equals(((ExecutionEntity) task2Execution).getParentId()));
// both have the same parent (but it is not the process instance)
assertTrue(((ExecutionEntity) task1Execution).getParentId().equals(((ExecutionEntity) task2Execution).getParentId()));
assertEquals(1, runtimeService.createEventSubscriptionQuery().count());
taskService.complete(task1.getId());
taskService.complete(task2.getId());
assertProcessEnded(processInstanceId);
}
@Deployment
public void testNonInterruptingWithUserTaskAndBoundaryEventInsideEmbeddedSubProcess() {
String processInstanceId = runtimeService.startProcessInstanceByKey("process").getId();
// when
runtimeService.correlateMessage("newMessage");
// then
assertEquals(2, taskService.createTaskQuery().count());
Task task1 = taskService.createTaskQuery()
.taskDefinitionKey("eventSubProcessTask")
.singleResult();
assertNotNull(task1);
Execution task1Execution = runtimeService
.createExecutionQuery()
.activityId("eventSubProcessTask")
.singleResult();
assertFalse(processInstanceId.equals(((ExecutionEntity) task1Execution).getParentId()));
Task task2 = taskService.createTaskQuery()
.taskDefinitionKey("task")
.singleResult();
assertNotNull(task2);
Execution task2Execution = runtimeService
.createExecutionQuery()
.activityId("eventSubProcessTask")
.singleResult();
assertFalse(processInstanceId.equals(((ExecutionEntity) task2Execution).getParentId()));
// both have the same parent (but it is not the process instance)
assertTrue(((ExecutionEntity) task1Execution).getParentId().equals(((ExecutionEntity) task2Execution).getParentId()));
assertEquals(1, runtimeService.createEventSubscriptionQuery().count());
taskService.complete(task1.getId());
taskService.complete(task2.getId());
assertProcessEnded(processInstanceId);
}
@Deployment
public void testNonInterruptingOutsideEmbeddedSubProcessWithReceiveTaskInsideEmbeddedSubProcess() {
String processInstanceId = runtimeService.startProcessInstanceByKey("process").getId();
// when (1)
runtimeService.correlateMessage("firstMessage");
// then (1)
assertEquals(1, taskService.createTaskQuery().count());
Task task1 = taskService.createTaskQuery()
.taskDefinitionKey("eventSubProcessTask")
.singleResult();
assertNotNull(task1);
Execution task1Execution = runtimeService
.createExecutionQuery()
.activityId("eventSubProcessTask")
.singleResult();
assertEquals(processInstanceId, ((ExecutionEntity) task1Execution).getParentId());
// when (2)
runtimeService.correlateMessage("secondMessage");
// then (2)
assertEquals(2, taskService.createTaskQuery().count());
task1 = taskService.createTaskQuery()
.taskDefinitionKey("eventSubProcessTask")
.singleResult();
assertNotNull(task1);
task1Execution = runtimeService
.createExecutionQuery()
.activityId("eventSubProcessTask")
.singleResult();
assertEquals(processInstanceId, ((ExecutionEntity) task1Execution).getParentId());
Task task2 = taskService.createTaskQuery()
.taskDefinitionKey("userTask")
.singleResult();
assertNotNull(task2);
Execution task2Execution = runtimeService
.createExecutionQuery()
.activityId("userTask")
.singleResult();
assertEquals(processInstanceId, ((ExecutionEntity) task2Execution).getParentId());
assertEquals(1, runtimeService.createEventSubscriptionQuery().count());
taskService.complete(task1.getId());
taskService.complete(task2.getId());
assertProcessEnded(processInstanceId);
}
}
| {
"content_hash": "164cae34e7ba713aace815728fb667c6",
"timestamp": "",
"source": "github",
"line_count": 843,
"max_line_length": 138,
"avg_line_length": 42.730723606168446,
"alnum_prop": 0.7466270612403532,
"repo_name": "menski/camunda-bpm-platform",
"id": "65402cbf9ddc42215d8c82419772f7a1cf66e710",
"size": "36023",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "engine/src/test/java/org/camunda/bpm/engine/test/bpmn/event/message/MessageEventSubprocessTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6650"
},
{
"name": "Groovy",
"bytes": "1280"
},
{
"name": "Java",
"bytes": "14755862"
},
{
"name": "JavaScript",
"bytes": "43"
},
{
"name": "Python",
"bytes": "187"
},
{
"name": "Ruby",
"bytes": "60"
},
{
"name": "Shell",
"bytes": "10705"
}
],
"symlink_target": ""
} |
describe("page-service", function() {
var pageService;
beforeEach(module('pgApexApp'));
beforeEach(inject(function(_pageService_){
pageService = _pageService_;
pageService.apiService = {
"get": function() {}
};
}));
it("should pass on application ID when calling getPages", function() {
spyOn(pageService.apiService, "get");
pageService.getPages(123);
expect(pageService.apiService.get).toHaveBeenCalledWith('page/pages/123');
});
}); | {
"content_hash": "26aba4e77e8e0225602f1407c28e9592",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 78,
"avg_line_length": 26.61111111111111,
"alnum_prop": 0.6722338204592901,
"repo_name": "raitraidma/pgapex",
"id": "9ae619d7e0c6033eedcdd25451ef5b9aa2d99dc8",
"size": "479",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pgapex/tests/javascript/app/services/page-service.spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "702"
},
{
"name": "HTML",
"bytes": "108367"
},
{
"name": "JavaScript",
"bytes": "141536"
},
{
"name": "PHP",
"bytes": "116399"
},
{
"name": "PLpgSQL",
"bytes": "124198"
},
{
"name": "Shell",
"bytes": "6959"
},
{
"name": "TeX",
"bytes": "140165"
}
],
"symlink_target": ""
} |
int main(int argc, char *argv[])
{
[NSApplication sharedApplication];
NSMenu * mainMenu = createMainMenu(nil);
[NSApp setMainMenu:mainMenu];
NSWindow *window = createMainWindow(nil);
[window orderFront:nil];
[NSApp run];
return 0;
} | {
"content_hash": "0728c425b96a8e5435c122086c33dea2",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 45,
"avg_line_length": 26,
"alnum_prop": 0.6692307692307692,
"repo_name": "hsoft/xibless",
"id": "cc1ddc862c3ddba997ce94f8e3e89498405393c3",
"size": "329",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demos/allwidgets/main.m",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Objective-C",
"bytes": "5994"
},
{
"name": "Python",
"bytes": "113224"
}
],
"symlink_target": ""
} |
/* $Id: SetSeedList.java 988245 2010-08-23 18:39:35Z kwright $ */
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.manifoldcf.crawler.connectors.rss;
import java.io.*;
import org.apache.manifoldcf.core.interfaces.*;
import org.apache.manifoldcf.crawler.interfaces.*;
import org.apache.manifoldcf.crawler.system.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
/** This class is used to set the seed list for a specified RSS job.
*/
public class SetSeedList
{
public static final String _rcsid = "@(#)$Id: SetSeedList.java 988245 2010-08-23 18:39:35Z kwright $";
private SetSeedList()
{
}
public static void main(String[] args)
{
if (args.length != 1)
{
System.err.println("Usage: SetSeedList <job_id>");
System.err.println("(Reads a set of urls from stdin)");
System.exit(-1);
}
String jobString = args[0];
try
{
IThreadContext tc = ThreadContextFactory.make();
ManifoldCF.initializeEnvironment(tc);
IJobManager jobManager = JobManagerFactory.make(tc);
IJobDescription desc = jobManager.load(new Long(jobString));
// Edit the job specification
Specification ds = desc.getSpecification();
// Delete all url specs first
int i = 0;
while (i < ds.getChildCount())
{
SpecificationNode sn = ds.getChild(i);
if (sn.getType().equals("feed"))
ds.removeChild(i);
else
i++;
}
java.io.Reader str = new java.io.InputStreamReader(System.in, StandardCharsets.UTF_8);
try
{
java.io.BufferedReader is = new java.io.BufferedReader(str);
try
{
while (true)
{
String nextString = is.readLine();
if (nextString == null)
break;
if (nextString.length() == 0)
continue;
SpecificationNode node = new SpecificationNode("feed");
node.setAttribute("url",nextString);
ds.addChild(ds.getChildCount(),node);
}
}
finally
{
is.close();
}
}
finally
{
str.close();
}
// Now, save
jobManager.save(desc);
}
catch (Exception e)
{
e.printStackTrace();
System.exit(-2);
}
}
}
| {
"content_hash": "31d4503c15926df4bc916183348d5b4a",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 104,
"avg_line_length": 28.155963302752294,
"alnum_prop": 0.6331052460084718,
"repo_name": "apache/manifoldcf",
"id": "b711cd279eeead2f8f7376b189fde93fe6bb216d",
"size": "3069",
"binary": false,
"copies": "3",
"ref": "refs/heads/trunk",
"path": "connectors/rss/connector/src/main/java/org/apache/manifoldcf/crawler/connectors/rss/SetSeedList.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "33401"
},
{
"name": "C",
"bytes": "40584"
},
{
"name": "HTML",
"bytes": "679037"
},
{
"name": "Java",
"bytes": "13088567"
},
{
"name": "JavaScript",
"bytes": "317650"
},
{
"name": "Less",
"bytes": "345287"
},
{
"name": "Makefile",
"bytes": "1712"
},
{
"name": "Python",
"bytes": "158817"
},
{
"name": "Shell",
"bytes": "37379"
},
{
"name": "XSLT",
"bytes": "31845"
}
],
"symlink_target": ""
} |
"use strict";
var angular = require("angular");
angular
.module("elektra.rest.angular")
.controller("MainController", require("./MainController"));
require("./website");
| {
"content_hash": "6b4ff510656fcaf8caef2cecb84a4cd9",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 61,
"avg_line_length": 19.666666666666668,
"alnum_prop": 0.6949152542372882,
"repo_name": "mpranj/libelektra",
"id": "88d899aab94dcf52d282abbd50eb49f14688ad3e",
"size": "177",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/tools/website/resources/assets/js/controllers/main/index.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Awk",
"bytes": "7774"
},
{
"name": "C",
"bytes": "4588361"
},
{
"name": "C++",
"bytes": "1620424"
},
{
"name": "CMake",
"bytes": "453752"
},
{
"name": "CSS",
"bytes": "6818"
},
{
"name": "Dockerfile",
"bytes": "97321"
},
{
"name": "Go",
"bytes": "37235"
},
{
"name": "Groovy",
"bytes": "43620"
},
{
"name": "HTML",
"bytes": "24613"
},
{
"name": "Inform 7",
"bytes": "394"
},
{
"name": "Java",
"bytes": "301170"
},
{
"name": "JavaScript",
"bytes": "272637"
},
{
"name": "Kotlin",
"bytes": "55441"
},
{
"name": "Less",
"bytes": "17593"
},
{
"name": "Lex",
"bytes": "17150"
},
{
"name": "Lua",
"bytes": "17205"
},
{
"name": "Makefile",
"bytes": "8660"
},
{
"name": "Mustache",
"bytes": "50110"
},
{
"name": "Objective-C",
"bytes": "6283"
},
{
"name": "Python",
"bytes": "130633"
},
{
"name": "QML",
"bytes": "87865"
},
{
"name": "QMake",
"bytes": "4256"
},
{
"name": "Roff",
"bytes": "791"
},
{
"name": "Ruby",
"bytes": "84714"
},
{
"name": "Rust",
"bytes": "92230"
},
{
"name": "SWIG",
"bytes": "77718"
},
{
"name": "Shell",
"bytes": "292686"
},
{
"name": "Tcl",
"bytes": "338"
},
{
"name": "Yacc",
"bytes": "4652"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
scan: 当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true。
scanPeriod: 设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。
当scan为true时,此属性生效。默认的时间间隔为1分钟。
debug: 当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。
-->
<configuration scan="true" scanPeriod="30 seconds" debug="false">
<property name="LOG_HOME" value="/tmp/logs" />
<property name="APPLICATION_NAME" value="build" />
<!-- console logger -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{43} : %m%n</pattern>
</encoder>
</appender>
<!-- everyday create logger file -->
<appender name="rollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${LOG_HOME}/${APPLICATION_NAME}/${APPLICATION_NAME}.%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>100</MaxHistory>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{43} : %m%n</pattern>
</encoder>
</appender>
<root level="warn">
<appender-ref ref="console" />
<appender-ref ref="rollingFile" />
</root>
<logger name="org.springframework" level="warn" additivity="false">
<appender-ref ref="console"/>
</logger>
<logger name="com.build" level="trace" additivity="false">
<appender-ref ref="console"/>
</logger>
</configuration>
| {
"content_hash": "7d0a78cf36ee60404950cedbd1c6f821",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 120,
"avg_line_length": 33.270833333333336,
"alnum_prop": 0.641202254226675,
"repo_name": "suntion/suns_build",
"id": "78764b7fbcec7991806cc9920305e6b91a21e7dd",
"size": "1849",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "build/build-mgr/src/test/resources/logback.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "744"
},
{
"name": "Java",
"bytes": "117269"
},
{
"name": "JavaScript",
"bytes": "100657"
}
],
"symlink_target": ""
} |
package com.hymane.materialhome.bean;
import java.io.Serializable;
/**
* Author :hymanme
* Email :[email protected]
* Create at 2016/1/8
* Description:
*/
public class BookRatingBean implements Serializable {
private int max;
private int numRaters;
private String average;
private int min;
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public int getNumRaters() {
return numRaters;
}
public void setNumRaters(int numRaters) {
this.numRaters = numRaters;
}
public String getAverage() {
return average;
}
public void setAverage(String average) {
this.average = average;
}
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
}
| {
"content_hash": "7902afad3ad6d77eb21c18ab03398843",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 53,
"avg_line_length": 17.833333333333332,
"alnum_prop": 0.6004672897196262,
"repo_name": "hymanme/MaterialHome",
"id": "b186127edff35847ec66e696d850eacdf65cd53d",
"size": "856",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/hymane/materialhome/bean/BookRatingBean.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "700418"
}
],
"symlink_target": ""
} |
<?php
Class Account_model extends MY_Model{
var $table ='accounts';
function join_permission ($phone){
$this->db->select('permissions,role_name,roles.id as role_id,accounts.id as account_id,shops.id as shop_id,buyers.id as buyer_id,active,expiration_date');
$this->db->from('accounts');
$this->db->join('roles', 'accounts.role_id = roles.id','left');
$this->db->join('shops ', 'shops.account_id=accounts.id','left');
$this->db->join('fees ', 'shops.id=fees.shop_id','left');
$this->db->join('buyers', 'buyers.account_id=accounts.id','left');
$this->db->where('accounts.phone', $phone);
$query = $this->db->get();
return $query->row();
}
function join_shops($id){
$this->db->select('role_id,accounts.id as account_id,shops.id as shop_id,image_shop,shop_name,phone,address,phone');
$this->db->from('accounts');
$this->db->join('shops ', 'shops.account_id=accounts.id','left');
$this->db->where('accounts.id', $id);
$query = $this->db->get();
return $query->row();
}
function join_buyer ($id){
$this->db->select('accounts.id as account_id,buyers.id as buyer_id,buyer_name,phone,address, phone as buyer_phone,name_receiver,phone_receiver,address_receiver');
$this->db->from('accounts');
$this->db->join('buyers', 'buyers.account_id=accounts.id','left');
$this->db->where('accounts.id', $id);
$query = $this->db->get();
return $query->row();
}
function join_shopsname($id){
$this->db->select('role_id,accounts.id as account_id,shops.id as shop_id,shops.shop_name as shop_name ,accounts.email as email,shops.phone as phone,shops.address as address ');
$this->db->from('accounts');
$this->db->join('shops ', 'shops.account_id=accounts.id','left');
$this->db->where('accounts.id', $id);
$query = $this->db->get();
return $query->row();
}
function join_buyername($id){
$this->db->select('role_id,accounts.id as account_id,buyers.id as id,buyers.buyer_name as buyer_name ,accounts.email as email,buyers.phone as phone,buyers.address as address ');
$this->db->from('accounts');
$this->db->join('buyers ', 'buyers.account_id=accounts.id','left');
$this->db->where('accounts.id', $id);
$query = $this->db->get();
return $query->row();
}
function join_shop_order ($id){
$this->db->select('accounts.id as account_id,shops.id as shop_id,orders.date_order as date_order,orders.description as description,order_details.quantity as quantity,
order_details.status as status,products.product_name as product_name,orders.id as id
');
$this->db->from('accounts');
$this->db->join('shops', 'shops.account_id=accounts.id','left');
$this->db->join('order_details', 'order_details.shop_id=shops.id','left');
$this->db->join('order_details', 'order_details.order_id=orders.id','left');
$this->db->join('products', 'products.id=order_details.product_id','left');
$this->db->where('accounts.id', $id);
$query = $this->db->get();
return $query->row();
}
function join_buyer_feedback($id)
{
$this->db->select('accounts.id as account_id,buyers.id as buyer_id,buyer_name,buyers.address as address, accounts.phone as phone,feedback.reason as reason,feedback.description as description');
$this->db->from('accounts');
$this->db->join('buyers', 'buyers.account_id=accounts.id', 'left');
$this->db->join('feedback', 'feedback.account_id=accounts.id', 'left');
$this->db->where('accounts.id', $id);
$query = $this->db->get();
return $query->row();
}
function join_shop_feedback($id)
{
$this->db->select('accounts.id as account_id,shops.id as shop_id,shop_name,shops.address as address,accounts.phone as phone,feedback.reason as reason,feedback.description as description');
$this->db->from('accounts');
$this->db->join('shops', 'shops.account_id=accounts.id', 'left');
$this->db->join('feedback', 'feedback.account_id=accounts.id', 'left');
$this->db->where('accounts.id', $id);
$query = $this->db->get();
return $query->row();
}
/*hàm của đức*/
function join_role(){
$this->db->select('accounts.id as account_id, role_name,accounts.phone as phone,address,name');
$this->db->from('accounts');
$this->db->join('roles', 'accounts.role_id = roles.id');
$this->db->join('admin', 'accounts.id = admin.account_id');
$this->db->where('roles.id <> 2 and roles.id <> 3');
$query = $this->db->get();
return $query->result();
}
}
?>
| {
"content_hash": "98b6a597873afff11b462a4b6da6f637",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 198,
"avg_line_length": 34.10526315789474,
"alnum_prop": 0.63668430335097,
"repo_name": "anhptse03395/e-market",
"id": "f009074606aa8885ed64556ca1fc3f59144d7ba2",
"size": "4542",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/models/Account_model.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1189"
},
{
"name": "CSS",
"bytes": "670909"
},
{
"name": "HTML",
"bytes": "533375"
},
{
"name": "JavaScript",
"bytes": "1714280"
},
{
"name": "PHP",
"bytes": "2372402"
}
],
"symlink_target": ""
} |
#import <TwitterCore/TWTRAuthConfig.h>
#import "TWTRAppAPIClient.h"
#import "TWTRAuthenticationConstants.h"
#import "TWTRTestCase.h"
static NSString *const TWTRTestAccessToken = @"tokentokentoken";
@interface TWTRAppAPIClientTests : TWTRTestCase
@property (nonatomic) TWTRAppAPIClient *appAPIClient;
@end
@implementation TWTRAppAPIClientTests
- (void)setUp
{
[super setUp];
self.appAPIClient = [[TWTRAppAPIClient alloc] initWithAuthConfig:[[TWTRAuthConfig alloc] initWithConsumerKey:@"consumerKey" consumerSecret:@"consumerSecret"] accessToken:TWTRTestAccessToken];
}
- (void)tearDown
{
self.appAPIClient = nil;
[super tearDown];
}
- (void)testAuthHeader
{
NSURLRequest *request = [[self appAPIClient] URLRequestWithMethod:@"GET" URLString:@"" parameters:nil];
NSString *authHeaderValue = [request valueForHTTPHeaderField:TWTRAuthorizationHeaderField];
NSString *expectedAuthHeaderValue = [NSString stringWithFormat:@"Bearer %@", TWTRTestAccessToken];
XCTAssertEqualObjects(authHeaderValue, expectedAuthHeaderValue);
}
- (void)testGET
{
NSURLRequest *request = [[self appAPIClient] URLRequestWithMethod:@"GET" URLString:@"" parameters:nil];
XCTAssertEqualObjects([request HTTPMethod], @"GET");
}
- (void)testPOST
{
NSURLRequest *request = [[self appAPIClient] URLRequestWithMethod:@"POST" URLString:@"" parameters:nil];
XCTAssertEqualObjects([request HTTPMethod], @"POST");
}
- (void)testDELETE
{
NSURLRequest *request = [[self appAPIClient] URLRequestWithMethod:@"DELETE" URLString:@"" parameters:nil];
XCTAssertEqualObjects([request HTTPMethod], @"DELETE");
}
@end
| {
"content_hash": "21cab66fb767c557b2589da0b521599d",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 195,
"avg_line_length": 28.736842105263158,
"alnum_prop": 0.757020757020757,
"repo_name": "BalestraPatrick/TweetsCounter",
"id": "85fdf4f5491f68bc0ed4be461db3ca1f441e218c",
"size": "2242",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Carthage/Checkouts/twitter-kit-ios/TwitterCore/TwitterCoreTests/NetworkingTests/TwitterAppAPIClientTests.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "838"
},
{
"name": "Objective-C",
"bytes": "87927"
},
{
"name": "Ruby",
"bytes": "658"
},
{
"name": "Swift",
"bytes": "94200"
}
],
"symlink_target": ""
} |
function SpotMatrix(element, dataset, chart_options) {
var spotRadius = chart_options.spot_radius;
var minColor = chart_options.min_color;
var maxColor = chart_options.max_color;
var spotCellPadding = chart_options.spot_cell_padding;
var spotCellMargin = chart_options.spot_cell_margin;
var spotMatrixType = chart_options.spot_matrix_type;
var strokeColor = chart_options.stroke_color;
if (isNaN(spotRadius) || spotRadius < 0) {
throw new Error("Spot Radius must be a Positive Number");
}
if (isNaN(spotCellPadding) || spotCellPadding < 0) {
throw new Error("Spot Cell Padding must be a Positive Number");
}
if (isNaN(spotCellMargin) || spotCellMargin < 0) {
throw new Error("Spot Cell Margin must be a Positive Number");
}
if (!(spotMatrixType.localeCompare("fill") || spotMatrixType.localeCompare("color") || spotMatrixType.localeCompare("size") || spotMatrixType.localeCompare("ring"))) {
throw new Error("Valid spotMatrixTypes are 'fill,'color','size','ring'");
}
if (!isNaN(minColor)) {
throw new Error("minColor must be a String");
}
if (!isNaN(maxColor)) {
throw new Error("maxColor must be a String");
}
if (!isNaN(strokeColor)) {
throw new Error("strokeColor must be a String");
}
var div = d3.select(element);
var column_topics = d3.keys(dataset[0]);
var extentOfData = d3.extent(
function(array, names) {
var res = [];
array.forEach(function(item) {
names.forEach(function(name) {
if (!isNaN(item[name]))
res = res.concat(item[name]);
});
});
return (res);
}(dataset, column_topics)
)
function toRadians(degs) {
return Math.PI * degs / 180;
}
function toDegrees(radians) {
return 180 * radians / Math.PI;
}
var minValue = extentOfData[0];
var maxValue = extentOfData[1];
var colorScale = d3.scaleLinear().domain([minValue, maxValue])
.range([minColor, maxColor]);
var radiusScale = d3.scaleLinear().domain([minValue, maxValue])
.range([0, spotRadius]);
var inverseRadiusScale = d3.scaleLinear().domain([minValue, maxValue])
.range([spotRadius, 0]);
var radialScale = d3.scaleLinear().domain([minValue, maxValue])
.range([0, toRadians(359)]);
var gradientScaleSVG = div.append("svg").attr("width", 0).attr("height", 0);
// append a table to the div
var table = div.append("table")
.attr("class", "table_spot-matrix")
.classed("display", true);
// append a header to the table
var thead = table.append("thead");
// append a body to the table
var tbody = table.append("tbody");
// append a row to the header
var theadRow = thead.append("tr");
// return a selection of cell elements in the header row
// attribute (join) data to the selection
// update (enter) the selection with nodes that have data
// append the cell elements to the header row
// return the text string for each item in the data array
theadRow.selectAll("td")
.data(d3.keys(dataset[0]))
.enter()
.append("td")
.attr('style', "padding:" + spotCellPadding + "px;" + "margin:" + spotCellMargin + "px")
.html(function(d) {
return evalText(d);
});
// table body rows
var tableBodyRows = tbody.selectAll("tr")
.data(dataset)
.enter()
.append("tr");
//table body row cells
tableBodyRows.selectAll("td")
.data(function(d) {
return d3.values(d);
})
.enter()
.append("td")
.attr('style', "padding:" + spotCellPadding + "px;" + "margin:" + spotCellMargin + "px;")
.html(function(d) {
return evalText(d);
})
.filter(function(d) {
return !isNaN(d);
})
.append(function(d, i, j) {
return renderSpots(d, i, j);
});
function renderSpots(d, i, j) {
var w = spotRadius * 2;
var h = spotRadius * 2;
var spots = document.createElement("div");
var svg = d3.select(spots).append("svg");
svg.attr("width", w);
svg.attr("height", h);
svg.attr("style", "padding:" + spotCellPadding + "px;" + "margin:" + spotCellMargin + "px;");
var elem = svg.selectAll("div")
.data([d]);
var elemEnter = elem.enter()
.append("g");
var elemEnterCircle = elemEnter.append("circle");
elemEnterCircle.attr("class", "spots")
spotAttr(elemEnterCircle, d, i, j);
elemEnterCircle.attr("fill", spotStyle(d, i, j));
if (spotMatrixType == 'ring') {
var elem = svg.selectAll("div")
.data([d]);
var elemEnter = elem.enter()
.append("g");
var elemEnterCircle = elemEnter.append("circle")
elemEnterCircle.attr("class", "spots")
elemEnterCircle.attr("cx", spotRadius);
elemEnterCircle.attr("cy", spotRadius);
elemEnterCircle.attr("r", inverseRadiusScale(d));
elemEnterCircle.attr("fill", minColor);
}
if (spotMatrixType == 'sector') {
var arc = d3.arc()
.innerRadius(0)
.outerRadius(spotRadius)
.startAngle(0)
.endAngle(radialScale(d));
var elem = svg.selectAll("div")
.data([d]);
var elemEnter = elem.enter()
.append("g");
elemEnter.append("path")
.attr("class", "arc spots")
.attr("transform", "translate(" + spotRadius + "," + spotRadius + ")")
.attr("d", arc)
.style("fill", maxColor)
.style("stroke", maxColor)
.style("stroke-width", 1)
}
add_tooltips();
function add_tooltips() {
// Adding a tooltip which on mouseover shows the date range and the last_close points range.
var tooltip = d3.select(element)
.append('div')
.attr('class', 'tooltip_spot-matrix');
tooltip.append('div')
.attr('class', 'value');
svg.selectAll(".spots")
.on('mouseover', function(d) {
var html = d;
tooltip.select('.value').html(html);
tooltip.style('display', 'block');
tooltip.style('opacity', 2);
})
.on('mousemove', function(d) {
tooltip.style('top', (d3.event.layerY + 10) + 'px')
.style('left', (d3.event.layerX - 25) + 'px');
})
.on('mouseout', function(d) {
tooltip.style('display', 'none');
tooltip.style('opacity', 0);
});
}
return spots;
}
function spotAttr(elem, d, i, j) {
elem.attr("cx", spotRadius);
elem.attr("cy", spotRadius);
elem.attr("stroke", strokeColor);
if (spotMatrixType != 'size') {
elem.attr("r", spotRadius);
} else {
elem.attr("r", radiusScale(d));
}
}
function spotStyle(d, i, j) {
if (spotMatrixType == 'color') {
return colorScale(d)
} else if (spotMatrixType == 'fill') {
var gradientScale = gradientScaleSVG
.append("defs")
.append("linearGradient")
.attr("id", "gradientScale-" + i + "," + d)
.attr("x1", "0%")
.attr("x2", "100%")
.attr("y1", "0%")
.attr("y2", "0%");
var offset = (d / maxValue) * 100;
gradientScale.append("stop").attr("offset", offset + "%").style("stop-color", maxColor);
gradientScale.append("stop").attr("offset", offset + "%").style("stop-color", minColor);
return "url(#gradientScale-" + i + "," + d + ")"
} else if (spotMatrixType == 'size') {
return maxColor
} else if (spotMatrixType == 'ring') {
return maxColor
} else if (spotMatrixType == 'sector') {
return "white"
}
}
function evalColor(d) {
if (!isNaN(d)) {
return createSVG(d);
} else {
return d;
}
}
function evalText(d) {
if (!isNaN(d)) {
//Do nothing
} else {
return "<b>" + d + "</b>";
}
}
} | {
"content_hash": "e8984198fe40ba771764974f1fb45252",
"timestamp": "",
"source": "github",
"line_count": 289,
"max_line_length": 171,
"avg_line_length": 30.346020761245676,
"alnum_prop": 0.5171037628278221,
"repo_name": "arpitnarechania/d3-spotmatrix",
"id": "ac112c5e744524029c347015e98c5622631516ca",
"size": "10168",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dist/SpotMatrix.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
using namespace chrono;
using namespace std;
#define TIME(X, Y) \
timer.start(); \
for (int i = 0; i < body_list->size(); i++) { \
X; \
} \
timer.stop(); \
cout << Y << timer() << endl;
#define TIMEBODY(X, Y) TIME(body_list->at(i)->X, Y)
int main() {
ChTimer<double> timer, full;
const int num_bodies = 1000000;
const double current_time = 1;
const double time_step = .1;
ChSystem dynamics_system;
for (int i = 0; i < num_bodies; i++) {
auto body = std::make_shared<ChBody>();
body->SetPos(ChVector<>(rand() % 1000 / 1000.0, rand() % 1000 / 1000.0, rand() % 1000 / 1000.0));
dynamics_system.AddBody(body);
}
std::vector<std::shared_ptr<ChBody> >* body_list = dynamics_system.Get_bodylist();
full.start();
TIMEBODY(UpdateTime(current_time), "UpdateTime ");
TIMEBODY(UpdateForces(current_time), "UpdateForces ");
TIMEBODY(UpdateMarkers(current_time), "UpdateMarkers ");
TIMEBODY(ClampSpeed(), "ClampSpeed ");
TIMEBODY(ComputeGyro(), "ComputeGyro ");
TIMEBODY(VariablesFbReset(), "VariablesFbReset ");
TIMEBODY(VariablesFbLoadForces(time_step), "VariablesFbLoadForces ");
TIMEBODY(VariablesQbLoadSpeed(), "VariablesQbLoadSpeed ");
TIMEBODY(VariablesQbIncrementPosition(time_step), "VariablesQbIncrementPosition ");
TIMEBODY(VariablesQbSetSpeed(time_step), "VariablesQbSetSpeed ");
// TIMEBODY(VariablesBody().GetBodyInvInertia(), "GetBodyInvInertia ");
full.stop();
cout << "Total: " << full() << endl;
timer.start();
for (int i = 0; i < body_list->size(); i++) {
body_list->at(i)->UpdateTime(current_time);
body_list->at(i)->UpdateForces(current_time);
body_list->at(i)->UpdateMarkers(current_time);
body_list->at(i)->ClampSpeed();
body_list->at(i)->ComputeGyro();
body_list->at(i)->VariablesFbReset();
body_list->at(i)->VariablesFbLoadForces(time_step);
body_list->at(i)->VariablesQbLoadSpeed();
body_list->at(i)->VariablesQbIncrementPosition(time_step);
body_list->at(i)->VariablesQbSetSpeed(time_step);
}
timer.stop();
cout << "SIngle Loop " << timer() << endl;
return 0;
}
| {
"content_hash": "648bb57f692d4df9a856be6e8604a8ef",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 105,
"avg_line_length": 37.609375,
"alnum_prop": 0.5766514333194849,
"repo_name": "andrewseidl/chrono",
"id": "68f6304c8897dbc29c434660db914695f066a772",
"size": "2809",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "src/unit_tests/benchmark/utest_CH_benchmark_ChBody.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "2059577"
},
{
"name": "C++",
"bytes": "15956802"
},
{
"name": "CMake",
"bytes": "367219"
},
{
"name": "CSS",
"bytes": "170229"
},
{
"name": "Cuda",
"bytes": "263684"
},
{
"name": "GLSL",
"bytes": "4731"
},
{
"name": "HTML",
"bytes": "8318"
},
{
"name": "Inno Setup",
"bytes": "23502"
},
{
"name": "JavaScript",
"bytes": "4731"
},
{
"name": "Objective-C",
"bytes": "46356"
},
{
"name": "POV-Ray SDL",
"bytes": "23109"
},
{
"name": "Python",
"bytes": "106362"
}
],
"symlink_target": ""
} |
using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using Owin;
using TestWebEngine.Data.Contexts.Authorization;
using TestWebEngine.Web;
using TestWebEngine.Web.Providers;
[assembly: OwinStartup(typeof(Startup))]
namespace TestWebEngine.Web
{
public class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static string PublicClientId { get; private set; }
static Startup()
{
PublicClientId = "web";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
AuthorizeEndpointPath = new PathString("/Account/Authorize"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
}
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(EfAuthorizationContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
}
} | {
"content_hash": "cd0965fd15e7c421b40ead41e051cd88",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 113,
"avg_line_length": 35.96610169491525,
"alnum_prop": 0.647502356267672,
"repo_name": "SKorolchuk/test-web-engine",
"id": "91669458761daa661ab235c5e953bf10105ffa81",
"size": "2124",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "TestWebEngine/TestWebEngine.Web/App_Start/OWIN.StartUp.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "100"
},
{
"name": "C#",
"bytes": "74405"
},
{
"name": "CSS",
"bytes": "4789"
},
{
"name": "HTML",
"bytes": "19621"
},
{
"name": "JavaScript",
"bytes": "812332"
},
{
"name": "Pascal",
"bytes": "1094"
},
{
"name": "PowerShell",
"bytes": "106195"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "2cb26215a246caeb0067f92668f003fd",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "f5f643e777ccbc8aa2091c5a9eccb3a3b56c1888",
"size": "177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Plantaginaceae/Veronica/Veronica subsimilis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
{% set b = button %}
{% set _obj = version if amo.HAS_COMPAT[addon.type] else addon %}
{% set compat = _obj.compatible_apps[APP] if _obj else None %}
<div class="install-shell">
<div class="install {{ b.install_class|join(' ') }}"
data-addon="{{ addon.id }}"
data-icon="{{ addon.icon_url }}"
data-developers="{{ addon.meet_the_dev_url() }}"
data-name="{{ addon.name }}"
{{ b.attrs()|xmlattr }}
{% if compat %}
data-min="{{ compat.min.version }}"
data-max="{{ compat.max.version }}"
data-version="{{ version.version }}"
data-compatible-apps="{{ version.compatible_apps[request.APP] }}"
data-lastupdated-isotime="{{ version.created|isotime }}"
data-lastupdated-datetime="{{ version.created|datetime }}"
{% endif %}>
<p class="install-button">
{% set links = b.links() %}
{% if not links %}
{{ _('No compatible versions') }}
{% endif %}
{% if settings.ADD_TO_MOBILE %}
{% if APP == amo.MOBILE %}
{% if request.user.is_authenticated() %}
{% set action = url('collections.alter', request.amo_user.username, 'mobile', 'add') %}
{% endif %}
{% if installed %}
{% set extra, text = 'status ok', _('Added to Mobile') %}
{% else %}
{% set text = _('Add to Mobile') %}
{% endif %}
<form method="post" action="{{ action }}">
{{ csrf() }}
<input type="hidden" name="addon_id" value="{{ addon.id }}">
<button class="button mobile {{ extra }} {{ b.button_class|join(' ') }}">
<b></b>
<span>{{ text }}</span>
</button>
</form>
{% endif %}
{% endif %}
{% for link in links %}
{% set extra = "platform " + link.os.shortname if link.os else "" %}
<a class="button {{ b.button_class|join(' ') }} {{ extra }} {% if addon.is_webapp() %}disabled{% endif %}"
{% if not addon.is_premium() %}
data-hash="{{ link.file.hash }}"
{% endif %}
{% if b.show_warning %}
href="{{ b.addon.get_url_path() }}"
data-realurl="{{ link.url }}"
{% else %}
href="{{ link.url }}"
{% endif %}>
<b></b>
<span>
{{ link.text }}
{% if link.os %}
<span class="os" data-os="{{ link.os.name }}">
{% if not (b.show_eula or b.show_contrib) %}
{# L10n: {0} is a platform name like Windows or Mac OS X. #}
{{ _('for {0}')|f(link.os.name) }}
{% endif %}
</span>
{% endif %}
</span>
</a>
{% endfor %}
</p>
{% if b.install_text -%}
<strong>{{ b.install_text }}</strong>
{%- endif %}
</div> {# install #}
{% if b.detailed %}
{% if addon.privacy_policy %}
<a class="privacy-policy" href="{{ url('addons.privacy', addon.slug) }}">
<strong>{{ _('View privacy policy') }}</strong>
</a>
{% endif %}
{% if addon.is_unreviewed() %}
<p class="warning">{% trans url=url('pages.faq') + "#unreviewed" %}
This add-on has not been reviewed by Mozilla.
<a href="{{ url }}">Learn more</a>
{% endtrans %} </p>
{% elif b.lite %}
<p class="warning">{% trans url=url('pages.faq') + "#preliminary" %}
This add-on has been preliminarily reviewed by Mozilla.
<a href="{{ url }}">Learn more</a>
{% endtrans %} </p>
{% elif addon.is_selfhosted() %}
<p class="warning">{{ _("This add-on is hosted on the developer's own website and has not been reviewed by Mozilla.") }}</p>
{% endif %}
{% endif %}
</div> {# install-shell #}
| {
"content_hash": "cb13ee25a94f4ea3d0796596d4756838",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 128,
"avg_line_length": 36.60204081632653,
"alnum_prop": 0.5071090047393365,
"repo_name": "jbalogh/zamboni",
"id": "ef73046df3b015b839f97c73f3b954eeb9e785ee",
"size": "3587",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apps/addons/templates/addons/button.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "4145"
},
{
"name": "JavaScript",
"bytes": "1553612"
},
{
"name": "Python",
"bytes": "2860649"
},
{
"name": "Shell",
"bytes": "8095"
}
],
"symlink_target": ""
} |
use std::fmt;
use std::io;
#[deriving(Clone)]
pub struct Layout {
pub logo: ~str,
pub favicon: ~str,
pub krate: ~str,
}
pub struct Page<'a> {
pub title: &'a str,
pub ty: &'a str,
pub root_path: &'a str,
}
pub fn render<T: fmt::Show, S: fmt::Show>(
dst: &mut io::Writer, layout: &Layout, page: &Page, sidebar: &S, t: &T)
-> fmt::Result
{
write!(dst,
r##"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>{title}</title>
<link href='http://fonts.googleapis.com/css?family=Oswald:700|Inconsolata:400,700'
rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="{root_path}main.css">
{favicon, select, none{} other{<link rel="shortcut icon" href="#" />}}
</head>
<body>
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
{logo, select, none{} other{
<a href='{root_path}{krate}/index.html'><img src='#' alt=''/></a>
}}
{sidebar}
</section>
<nav class="sub">
<form class="search-form js-only">
<button class="do-search">Search</button>
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Search documentation..."
type="search" />
</div>
</form>
</nav>
<section id='main' class="content {ty}">{content}</section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div class="shortcuts">
<h1>Keyboard shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>↑</dt>
<dd>Move up in search results</dd>
<dt>↓</dt>
<dd>Move down in search results</dd>
<dt>&\#9166;</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code> (or <code>str</code>), <code>enum</code>,
<code>trait</code>, <code>typedef</code> (or
<code>tdef</code>).
</p>
</div>
</div>
<script>
var rootPath = "{root_path}";
var currentCrate = "{krate}";
</script>
<script src="{root_path}jquery.js"></script>
<script src="{root_path}main.js"></script>
<script async src="{root_path}search-index.js"></script>
</body>
</html>
"##,
content = *t,
root_path = page.root_path,
ty = page.ty,
logo = nonestr(layout.logo),
title = page.title,
favicon = nonestr(layout.favicon),
sidebar = *sidebar,
krate = layout.krate,
)
}
fn nonestr<'a>(s: &'a str) -> &'a str {
if s == "" { "none" } else { s }
}
| {
"content_hash": "2d187da9d5cc4d122ba0c8f4bf3e6e58",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 86,
"avg_line_length": 28.355371900826448,
"alnum_prop": 0.4998542698921597,
"repo_name": "pythonesque/rust",
"id": "399dcf6991c86dcba542eb24cc3bae87320adba3",
"size": "3898",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/librustdoc/html/layout.rs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "21081"
},
{
"name": "Awk",
"bytes": "159"
},
{
"name": "C",
"bytes": "726143"
},
{
"name": "C++",
"bytes": "49183"
},
{
"name": "CSS",
"bytes": "13855"
},
{
"name": "Emacs Lisp",
"bytes": "41165"
},
{
"name": "JavaScript",
"bytes": "24035"
},
{
"name": "Perl",
"bytes": "1076"
},
{
"name": "Puppet",
"bytes": "5351"
},
{
"name": "Python",
"bytes": "56864"
},
{
"name": "Rust",
"bytes": "12600013"
},
{
"name": "Shell",
"bytes": "277231"
},
{
"name": "VimL",
"bytes": "22916"
}
],
"symlink_target": ""
} |
import copy
import sys
import traceback
from oslo.config import cfg
import six
from ceilometer.openstack.common.gettextutils import _ # noqa
from ceilometer.openstack.common import importutils
from ceilometer.openstack.common import jsonutils
from ceilometer.openstack.common import local
from ceilometer.openstack.common import log as logging
from ceilometer.openstack.common import versionutils
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
'''RPC Envelope Version.
This version number applies to the top level structure of messages sent out.
It does *not* apply to the message payload, which must be versioned
independently. For example, when using rpc APIs, a version number is applied
for changes to the API being exposed over rpc. This version number is handled
in the rpc proxy and dispatcher modules.
This version number applies to the message envelope that is used in the
serialization done inside the rpc layer. See serialize_msg() and
deserialize_msg().
The current message format (version 2.0) is very simple. It is:
{
'oslo.version': <RPC Envelope Version as a String>,
'oslo.message': <Application Message Payload, JSON encoded>
}
Message format version '1.0' is just considered to be the messages we sent
without a message envelope.
So, the current message envelope just includes the envelope version. It may
eventually contain additional information, such as a signature for the message
payload.
We will JSON encode the application message payload. The message envelope,
which includes the JSON encoded application message body, will be passed down
to the messaging libraries as a dict.
'''
_RPC_ENVELOPE_VERSION = '2.0'
_VERSION_KEY = 'oslo.version'
_MESSAGE_KEY = 'oslo.message'
_REMOTE_POSTFIX = '_Remote'
class RPCException(Exception):
msg_fmt = _("An unknown RPC related exception occurred.")
def __init__(self, message=None, **kwargs):
self.kwargs = kwargs
if not message:
try:
message = self.msg_fmt % kwargs
except Exception:
# kwargs doesn't match a variable in the message
# log the issue and the kwargs
LOG.exception(_('Exception in string format operation'))
for name, value in kwargs.iteritems():
LOG.error("%s: %s" % (name, value))
# at least get the core message out if something happened
message = self.msg_fmt
super(RPCException, self).__init__(message)
class RemoteError(RPCException):
"""Signifies that a remote class has raised an exception.
Contains a string representation of the type of the original exception,
the value of the original exception, and the traceback. These are
sent to the parent as a joined string so printing the exception
contains all of the relevant info.
"""
msg_fmt = _("Remote error: %(exc_type)s %(value)s\n%(traceback)s.")
def __init__(self, exc_type=None, value=None, traceback=None):
self.exc_type = exc_type
self.value = value
self.traceback = traceback
super(RemoteError, self).__init__(exc_type=exc_type,
value=value,
traceback=traceback)
class Timeout(RPCException):
"""Signifies that a timeout has occurred.
This exception is raised if the rpc_response_timeout is reached while
waiting for a response from the remote side.
"""
msg_fmt = _('Timeout while waiting on RPC response - '
'topic: "%(topic)s", RPC method: "%(method)s" '
'info: "%(info)s"')
def __init__(self, info=None, topic=None, method=None):
"""Initiates Timeout object.
:param info: Extra info to convey to the user
:param topic: The topic that the rpc call was sent to
:param rpc_method_name: The name of the rpc method being
called
"""
self.info = info
self.topic = topic
self.method = method
super(Timeout, self).__init__(
None,
info=info or _('<unknown>'),
topic=topic or _('<unknown>'),
method=method or _('<unknown>'))
class DuplicateMessageError(RPCException):
msg_fmt = _("Found duplicate message(%(msg_id)s). Skipping it.")
class InvalidRPCConnectionReuse(RPCException):
msg_fmt = _("Invalid reuse of an RPC connection.")
class UnsupportedRpcVersion(RPCException):
msg_fmt = _("Specified RPC version, %(version)s, not supported by "
"this endpoint.")
class UnsupportedRpcEnvelopeVersion(RPCException):
msg_fmt = _("Specified RPC envelope version, %(version)s, "
"not supported by this endpoint.")
class RpcVersionCapError(RPCException):
msg_fmt = _("Specified RPC version cap, %(version_cap)s, is too low")
class Connection(object):
"""A connection, returned by rpc.create_connection().
This class represents a connection to the message bus used for rpc.
An instance of this class should never be created by users of the rpc API.
Use rpc.create_connection() instead.
"""
def close(self):
"""Close the connection.
This method must be called when the connection will no longer be used.
It will ensure that any resources associated with the connection, such
as a network connection, and cleaned up.
"""
raise NotImplementedError()
def create_consumer(self, topic, proxy, fanout=False):
"""Create a consumer on this connection.
A consumer is associated with a message queue on the backend message
bus. The consumer will read messages from the queue, unpack them, and
dispatch them to the proxy object. The contents of the message pulled
off of the queue will determine which method gets called on the proxy
object.
:param topic: This is a name associated with what to consume from.
Multiple instances of a service may consume from the same
topic. For example, all instances of nova-compute consume
from a queue called "compute". In that case, the
messages will get distributed amongst the consumers in a
round-robin fashion if fanout=False. If fanout=True,
every consumer associated with this topic will get a
copy of every message.
:param proxy: The object that will handle all incoming messages.
:param fanout: Whether or not this is a fanout topic. See the
documentation for the topic parameter for some
additional comments on this.
"""
raise NotImplementedError()
def create_worker(self, topic, proxy, pool_name):
"""Create a worker on this connection.
A worker is like a regular consumer of messages directed to a
topic, except that it is part of a set of such consumers (the
"pool") which may run in parallel. Every pool of workers will
receive a given message, but only one worker in the pool will
be asked to process it. Load is distributed across the members
of the pool in round-robin fashion.
:param topic: This is a name associated with what to consume from.
Multiple instances of a service may consume from the same
topic.
:param proxy: The object that will handle all incoming messages.
:param pool_name: String containing the name of the pool of workers
"""
raise NotImplementedError()
def join_consumer_pool(self, callback, pool_name, topic, exchange_name):
"""Register as a member of a group of consumers.
Uses given topic from the specified exchange.
Exactly one member of a given pool will receive each message.
A message will be delivered to multiple pools, if more than
one is created.
:param callback: Callable to be invoked for each message.
:type callback: callable accepting one argument
:param pool_name: The name of the consumer pool.
:type pool_name: str
:param topic: The routing topic for desired messages.
:type topic: str
:param exchange_name: The name of the message exchange where
the client should attach. Defaults to
the configured exchange.
:type exchange_name: str
"""
raise NotImplementedError()
def consume_in_thread(self):
"""Spawn a thread to handle incoming messages.
Spawn a thread that will be responsible for handling all incoming
messages for consumers that were set up on this connection.
Message dispatching inside of this is expected to be implemented in a
non-blocking manner. An example implementation would be having this
thread pull messages in for all of the consumers, but utilize a thread
pool for dispatching the messages to the proxy objects.
"""
raise NotImplementedError()
def _safe_log(log_func, msg, msg_data):
"""Sanitizes the msg_data field before logging."""
SANITIZE = ['_context_auth_token', 'auth_token', 'new_pass']
def _fix_passwords(d):
"""Sanitizes the password fields in the dictionary."""
for k in six.iterkeys(d):
if k.lower().find('password') != -1:
d[k] = '<SANITIZED>'
elif k.lower() in SANITIZE:
d[k] = '<SANITIZED>'
elif isinstance(d[k], dict):
_fix_passwords(d[k])
return d
return log_func(msg, _fix_passwords(copy.deepcopy(msg_data)))
def serialize_remote_exception(failure_info, log_failure=True):
"""Prepares exception data to be sent over rpc.
Failure_info should be a sys.exc_info() tuple.
"""
tb = traceback.format_exception(*failure_info)
failure = failure_info[1]
if log_failure:
LOG.error(_("Returning exception %s to caller"),
six.text_type(failure))
LOG.error(tb)
kwargs = {}
if hasattr(failure, 'kwargs'):
kwargs = failure.kwargs
# NOTE(matiu): With cells, it's possible to re-raise remote, remote
# exceptions. Lets turn it back into the original exception type.
cls_name = str(failure.__class__.__name__)
mod_name = str(failure.__class__.__module__)
if (cls_name.endswith(_REMOTE_POSTFIX) and
mod_name.endswith(_REMOTE_POSTFIX)):
cls_name = cls_name[:-len(_REMOTE_POSTFIX)]
mod_name = mod_name[:-len(_REMOTE_POSTFIX)]
data = {
'class': cls_name,
'module': mod_name,
'message': six.text_type(failure),
'tb': tb,
'args': failure.args,
'kwargs': kwargs
}
json_data = jsonutils.dumps(data)
return json_data
def deserialize_remote_exception(conf, data):
failure = jsonutils.loads(str(data))
trace = failure.get('tb', [])
message = failure.get('message', "") + "\n" + "\n".join(trace)
name = failure.get('class')
module = failure.get('module')
# NOTE(ameade): We DO NOT want to allow just any module to be imported, in
# order to prevent arbitrary code execution.
if module not in conf.allowed_rpc_exception_modules:
return RemoteError(name, failure.get('message'), trace)
try:
mod = importutils.import_module(module)
klass = getattr(mod, name)
if not issubclass(klass, Exception):
raise TypeError("Can only deserialize Exceptions")
failure = klass(*failure.get('args', []), **failure.get('kwargs', {}))
except (AttributeError, TypeError, ImportError):
return RemoteError(name, failure.get('message'), trace)
ex_type = type(failure)
str_override = lambda self: message
new_ex_type = type(ex_type.__name__ + _REMOTE_POSTFIX, (ex_type,),
{'__str__': str_override, '__unicode__': str_override})
new_ex_type.__module__ = '%s%s' % (module, _REMOTE_POSTFIX)
try:
# NOTE(ameade): Dynamically create a new exception type and swap it in
# as the new type for the exception. This only works on user defined
# Exceptions and not core python exceptions. This is important because
# we cannot necessarily change an exception message so we must override
# the __str__ method.
failure.__class__ = new_ex_type
except TypeError:
# NOTE(ameade): If a core exception then just add the traceback to the
# first exception argument.
failure.args = (message,) + failure.args[1:]
return failure
class CommonRpcContext(object):
def __init__(self, **kwargs):
self.values = kwargs
def __getattr__(self, key):
try:
return self.values[key]
except KeyError:
raise AttributeError(key)
def to_dict(self):
return copy.deepcopy(self.values)
@classmethod
def from_dict(cls, values):
return cls(**values)
def deepcopy(self):
return self.from_dict(self.to_dict())
def update_store(self):
local.store.context = self
def elevated(self, read_deleted=None, overwrite=False):
"""Return a version of this context with admin flag set."""
# TODO(russellb) This method is a bit of a nova-ism. It makes
# some assumptions about the data in the request context sent
# across rpc, while the rest of this class does not. We could get
# rid of this if we changed the nova code that uses this to
# convert the RpcContext back to its native RequestContext doing
# something like nova.context.RequestContext.from_dict(ctxt.to_dict())
context = self.deepcopy()
context.values['is_admin'] = True
context.values.setdefault('roles', [])
if 'admin' not in context.values['roles']:
context.values['roles'].append('admin')
if read_deleted is not None:
context.values['read_deleted'] = read_deleted
return context
class ClientException(Exception):
"""Encapsulates actual exception expected to be hit by a RPC proxy object.
Merely instantiating it records the current exception information, which
will be passed back to the RPC client without exceptional logging.
"""
def __init__(self):
self._exc_info = sys.exc_info()
def catch_client_exception(exceptions, func, *args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
if type(e) in exceptions:
raise ClientException()
else:
raise
def client_exceptions(*exceptions):
"""Decorator for manager methods that raise expected exceptions.
Marking a Manager method with this decorator allows the declaration
of expected exceptions that the RPC layer should not consider fatal,
and not log as if they were generated in a real error scenario. Note
that this will cause listed exceptions to be wrapped in a
ClientException, which is used internally by the RPC layer.
"""
def outer(func):
def inner(*args, **kwargs):
return catch_client_exception(exceptions, func, *args, **kwargs)
return inner
return outer
# TODO(sirp): we should deprecate this in favor of
# using `versionutils.is_compatible` directly
def version_is_compatible(imp_version, version):
"""Determine whether versions are compatible.
:param imp_version: The version implemented
:param version: The version requested by an incoming message.
"""
return versionutils.is_compatible(version, imp_version)
def serialize_msg(raw_msg):
# NOTE(russellb) See the docstring for _RPC_ENVELOPE_VERSION for more
# information about this format.
msg = {_VERSION_KEY: _RPC_ENVELOPE_VERSION,
_MESSAGE_KEY: jsonutils.dumps(raw_msg)}
return msg
def deserialize_msg(msg):
# NOTE(russellb): Hang on to your hats, this road is about to
# get a little bumpy.
#
# Robustness Principle:
# "Be strict in what you send, liberal in what you accept."
#
# At this point we have to do a bit of guessing about what it
# is we just received. Here is the set of possibilities:
#
# 1) We received a dict. This could be 2 things:
#
# a) Inspect it to see if it looks like a standard message envelope.
# If so, great!
#
# b) If it doesn't look like a standard message envelope, it could either
# be a notification, or a message from before we added a message
# envelope (referred to as version 1.0).
# Just return the message as-is.
#
# 2) It's any other non-dict type. Just return it and hope for the best.
# This case covers return values from rpc.call() from before message
# envelopes were used. (messages to call a method were always a dict)
if not isinstance(msg, dict):
# See #2 above.
return msg
base_envelope_keys = (_VERSION_KEY, _MESSAGE_KEY)
if not all(map(lambda key: key in msg, base_envelope_keys)):
# See #1.b above.
return msg
# At this point we think we have the message envelope
# format we were expecting. (#1.a above)
if not version_is_compatible(_RPC_ENVELOPE_VERSION, msg[_VERSION_KEY]):
raise UnsupportedRpcEnvelopeVersion(version=msg[_VERSION_KEY])
raw_msg = jsonutils.loads(msg[_MESSAGE_KEY])
return raw_msg
| {
"content_hash": "0debe61180b5bc2c76cfff1f2e5c013c",
"timestamp": "",
"source": "github",
"line_count": 487,
"max_line_length": 79,
"avg_line_length": 36.29774127310061,
"alnum_prop": 0.6437743961079369,
"repo_name": "lexxito/monitoring",
"id": "6d034324013b1d0ff7692562c7fad33bbdedc5ad",
"size": "18440",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ceilometer/openstack/common/rpc/common.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6284"
},
{
"name": "HTML",
"bytes": "5892"
},
{
"name": "JavaScript",
"bytes": "63538"
},
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Python",
"bytes": "2077479"
},
{
"name": "Shell",
"bytes": "8171"
}
],
"symlink_target": ""
} |
package com.thecoffeine.auth.error.model.entity;
import java.util.ArrayList;
import java.util.List;
/**
* Object for describe input error.
*
* @version 1.0
*/
public class ValidationError {
/// *** Properties *** ///
/**
* List of errors/field.
*/
private List<Field> fieldErrors = new ArrayList<>();
//*** Methods *** ///
/**
* Add new fieldErrors.
*
* @param field Name of field.
* @param message Message about error for this field.
*/
public void addFieldError( String field, String message ) {
fieldErrors.add(
new Field(
field,
message
)
);
}
//- SECTION :: GET -//
/**
* Get field errors.
*
* @return List of errors/fields.
*/
public List<Field> getFieldErrors() {
return fieldErrors;
}
}
| {
"content_hash": "54714e802292b8af7a5ce3a5a0d48d9d",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 63,
"avg_line_length": 18.791666666666668,
"alnum_prop": 0.5221729490022173,
"repo_name": "coffeine-009/auth",
"id": "79cd87fcc37e694bc8db594ba0b1f22ecee4f59c",
"size": "1073",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/thecoffeine/auth/error/model/entity/ValidationError.java",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3634"
},
{
"name": "HTML",
"bytes": "6742"
},
{
"name": "Java",
"bytes": "205784"
}
],
"symlink_target": ""
} |
<?php
/* SensioDistributionBundle::Configurator/layout.html.twig */
class __TwigTemplate_b2fdf354463c9563417ba9043aff191369ab11847fbd3f29a49130c70b39dd75 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
try {
$this->parent = $this->env->loadTemplate("TwigBundle::layout.html.twig");
} catch (Twig_Error_Loader $e) {
$e->setTemplateFile($this->getTemplateName());
$e->setTemplateLine(1);
throw $e;
}
$this->blocks = array(
'head' => array($this, 'block_head'),
'title' => array($this, 'block_title'),
'body' => array($this, 'block_body'),
'content' => array($this, 'block_content'),
);
}
protected function doGetParent(array $context)
{
return "TwigBundle::layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_head($context, array $blocks = array())
{
// line 4
echo " <link rel=\"stylesheet\" href=\"";
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/sensiodistribution/webconfigurator/css/configurator.css"), "html", null, true);
echo "\" />
";
}
// line 7
public function block_title($context, array $blocks = array())
{
echo "Web Configurator Bundle";
}
// line 9
public function block_body($context, array $blocks = array())
{
// line 10
echo " <div class=\"block\">
";
// line 11
$this->displayBlock('content', $context, $blocks);
// line 12
echo " </div>
<div class=\"version\">Symfony Standard Edition v.";
// line 13
echo twig_escape_filter($this->env, (isset($context["version"]) ? $context["version"] : $this->getContext($context, "version")), "html", null, true);
echo "</div>
";
}
// line 11
public function block_content($context, array $blocks = array())
{
}
public function getTemplateName()
{
return "SensioDistributionBundle::Configurator/layout.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 72 => 11, 66 => 13, 63 => 12, 61 => 11, 58 => 10, 55 => 9, 49 => 7, 42 => 4, 39 => 3, 11 => 1,);
}
}
| {
"content_hash": "f421adcff83a2622db61d9ef16499d57",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 180,
"avg_line_length": 29.033333333333335,
"alnum_prop": 0.5587447378492154,
"repo_name": "csu6/Symfony",
"id": "45c938a67466fad85abf8fe6c31443f30313742e",
"size": "2613",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/cache/de_/twig/b2/fd/f354463c9563417ba9043aff191369ab11847fbd3f29a49130c70b39dd75.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3073"
},
{
"name": "CSS",
"bytes": "15716"
},
{
"name": "PHP",
"bytes": "84326"
}
],
"symlink_target": ""
} |
!!-------------helloworld.f95-------------------------------------------------!!
!
! hello world.f95
!
! Purpose: To check out some fortran!
!
!!----------------------------------------------------------------------------!!
program helloworld
!! definitons
character :: tab = char(9)
integer :: i = 10
real*8 :: variable
!! formatting / opeining
300 format(A, A, F4.2)
open(100, file = "output.dat")
!! writing
write(100,300) "hello world!", tab, 1.00
!! executing functions (subroutines)
call loop(i, variable)
write(*,*) variable, i
end program
!! subroutines -- pure!
pure subroutine loop(i, variable)
implicit none
integer, intent(inout) :: i
integer :: j
real*8, intent(out) :: variable
!! looping
do j=1,10
variable = variable + real(j) * real(i) * 0.001
i = i + 1
end do
end subroutine
| {
"content_hash": "9d7e101d32624cd7b58a7c6d8cecf454",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 80,
"avg_line_length": 24.025,
"alnum_prop": 0.4620187304890739,
"repo_name": "leios/simuleios",
"id": "9a2ccb22407e0c90697efcd92028c193bfb56f6f",
"size": "961",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Optimal_Control/helloworld.f95",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "737385"
},
{
"name": "Cuda",
"bytes": "13704"
},
{
"name": "Fortran",
"bytes": "18399"
},
{
"name": "GLSL",
"bytes": "376"
},
{
"name": "Gnuplot",
"bytes": "6771"
},
{
"name": "Julia",
"bytes": "77907"
},
{
"name": "Makefile",
"bytes": "16283"
},
{
"name": "Python",
"bytes": "123435"
}
],
"symlink_target": ""
} |
@interface XZEventHistoryElement ()
@property(nonatomic,strong)id<NSObject,NSCopying,NSCoding> data;
@property(nonatomic,strong)NSDate *timestamp;
@end
@implementation XZEventHistoryElement
- (instancetype)initWithData:(id<NSObject,NSCopying,NSCoding>)data{
self = [super init];
if ([data conformsToProtocol:@protocol(NSCoding)] == NO) {
return nil;
}
if (self != nil) {
_data = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:data]];
_timestamp = [NSDate date];
}
return self;
}
@end
| {
"content_hash": "e144645253d74f6f636600a3cf04c0f3",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 104,
"avg_line_length": 29.833333333333332,
"alnum_prop": 0.7616387337057728,
"repo_name": "xzeror/XZDataLayerViewer",
"id": "db9534dcce7ebfa56269a5d373f029d96fe72a53",
"size": "675",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Library/Sources/Model/XZEventHistoryElement.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "200"
},
{
"name": "Objective-C",
"bytes": "387434"
},
{
"name": "Ruby",
"bytes": "1973"
},
{
"name": "Shell",
"bytes": "8539"
}
],
"symlink_target": ""
} |
node-scrapy
===========
Simple, lightweight and expressive web scraping with Node.js
## Scraping made simple
```js
var scrapy = require('node-scrapy')
, url = 'https://github.com/strongloop/express'
, selector = '.repository-description'
scrapy.scrape(url, selector, function(err, data) {
if (err) return console.error(err)
console.log(data)
});
// 'Fast, unopinionated, minimalist web framework for node.'
```
Scrapy can resolve complex objects. Give it a data model:
```js
var scrapy = require('node-scrapy')
, url = 'https://github.com/strongloop/express'
, model =
{ author: '.author',
repo: '.js-current-repository',
stats:
{ commits: '.commits .num',
branches: '.numbers-summary > li.commits + li .num',
releases: '.numbers-summary > li.commits + li + li .num',
contributors: '.numbers-summary > li.commits + li + li + li .num',
social:
{ stars: '.star-button + .social-count',
forks: '.fork-button + .social-count' } },
files: '.js-directory-link' }
scrapy.scrape(url, model, function(err, data) {
if (err) return console.error(err)
console.log(data)
});
```
...and Scrapy will return:
```js
{ author: 'strongloop',
repo: 'express',
stats:
{ commits: '4,925',
branches: '12',
releases: '223',
contributors: '162',
social: { stars: '16,132', forks: '3,340' } },
files:
[ 'benchmarks', 'examples', 'lib', 'support', 'test', '.gitignore','.travis.yml', 'Contributing.md', 'History.md', 'LICENSE', 'Readme.md', 'index.js', 'package.json' ] }
```
## Install
```bash
npm install node-scrapy
```
## Features
🍠 __Simple__: No XPaths. No complex object inheritance. No extensive config files. Just JSON and the CSS selectors you're used to. Simple as [potatoes](http://youtu.be/efMHLkyb7ho).
⚡ __Lightweight:__ Scrapy relies only on [cheerio](https://www.npmjs.org/package/cheerio), [request](https://www.npmjs.org/package/request), and a [Lo-Dash custom build](https://lodash.com/custom-builds), all known for being fast.
📢 __Expressive:__ It's easy to talk to Scrapy. It will assume a lot of handy defaults to get what you actually meant to get. If Scrapy misunderstands, you can try to express yourself better using its [options](#optionsitemoptions).
## Limitations
Scrapy wraps [cheerio](https://www.npmjs.org/package/cheerio) and [request](https://www.npmjs.org/package/request) to parse HTML files over the wire. Cheerio can't parse javascript and neither will Scrapy, so with client-side-rendered pages Scrapy may not behave as one would expect. You can always check this visiting the page with your favorite browser and disabling javascript.
If the page you're trying to scrape is client-side-rendered, you still can change the HTTP user-agent to let the server know it is a machine and, if lucky, the server will return a non-AJAX version of the page. You may check [this list of bots' user-agents](http://user-agent-string.info/list-of-ua/bots) and configure Scrapy through its [request options](#optionsrequestoptions) to present itself as a bot.
## API
So far, Scrapy exposes only one method:
### .scrape( url, model, [options,] callback )
### url
A `string` representing a valid URL of the resource to scrape.
### model
It can be either a `string` with the [CSS selector](#selector) of the element(s) to retrieve:
```js
var url = 'https://www.npmjs.org/package/mocha'
, model = '.package-description'
scrapy.scrape(url, model, console.log)
// null 'simple, flexible, fun test framework'
// ^ no error passed to console.log
```
or an `object` whose enumerable properties hold [CSS selectors](#selector):
```js
var url = 'https://www.npmjs.org/package/mocha'
, model = { description: '.package-description', keywords: 'h3:contains(Keywords) + p a' }
scrapy.scrape(url, model, console.log)
/*
{ description: 'simple, flexible, fun test framework',
keywords:
[ 'mocha',
'test',
'bdd',
'tdd',
'tap' ] }
*/
```
or nested objects with embeded [options](#optionsitemoptions) for each item, in which case the `selector` key holding a [CSS selector](#selector) is a must:
```js
var url = 'https://www.npmjs.org/package/mocha'
, model = { description: { selector: '.package-description', required: true },
maintainers:
{ selector: '.humans li a',
get: 'href',
prefix: 'https://www.npmjs.org' } }
scrapy.scrape(url, model, console.log)
/*
{ description: 'simple, flexible, fun test framework',
maintainers:
[ 'https://www.npmjs.org/~travisjeffery',
'https://www.npmjs.org/~tjholowaychuk',
'https://www.npmjs.org/~travisjeffery',
'https://www.npmjs.org/~jbnicolai',
'https://www.npmjs.org/~boneskull' ] }
*/
```
### options
This is an optional `Object`. It lets you set request's options, cheerio's load options, and/or your own default options for every item passed into the `model`.
You can always look at Scrapy's defaults into the [defaults.json](./defaults.json) file.
#### options.itemOptions
_Important:_ the following options can be set in a per-item basis inside the `model`. Setting these options into `options.itemOptions` will simply overwrite the defaults used for the current `.scrape()` call.
##### selector
A `string` representing a CSS selector. It must be compliant with [CSSselector's supported selectors](https://github.com/fb55/CSSselect#supported-selectors).
##### get
Part of the selected element(s) to retrieve.
`'text'`: the DOM equivalent of [`Node.textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent).
`'{attribute}'`: gets the value of the given `attribute`. e.g. `'src'`, '`href`', `'disabled'`, etc.
Default: `'text'`
##### required
`false`: nothing happens.
`true`: Scrapy will stop and call back with an `Error` as first argument if no element in the page matches the `selector`. `err.bodyString` holds the entire HTTP response body for debugging purposes.
Default: `false`
##### unique
_Heads up!_ - if no single element matched the `selector`, the result will always be `null`; except when [`required`](#required) is set to `true`, in which case calls back with an `Error`.
`'auto'`: if a single element matched the `selector`, a `string` will be returned with its result. If many elements matched the selector, will return an `Array` of strings holding the result of each element.
`true`: will return a single `string`, no matter if many elements matched the `selector`. Only the first one will be taken.
`false`: even if a single element matched the `selector`, it will be returned boxed into an `Array`.
Default: `'auto'`
##### trim
Trims the result, before any other tramsformation, like `prefix`/`suffix`.
`false`: will not trim.
`'left'`: trim left.
`'right'`: trim right.
`true`: will trim both sides.
Default: `true`
##### prefix
A `string` to be prefixed to the result(s). Useful to transform relative URLs into absolute ones.
Default: `''` (empty string)
##### suffix
A `string` to be appended to the result(s).
Default: `''` (empty string)
#### options.cheerioOptions
These options are passed to cheerio on load. You can check all available options in [htmlparser2's wiki](https://github.com/fb55/htmlparser2/wiki/Parser-options) (in which cheerio relies).
Scrapy's default `cheerioOptions` are the following:
```json
{
"normalizeWhitespace": true,
"xmlMode": false,
"lowerCaseTags": false
}
```
As a reminder: you can always look at Scrapy's defaults into the [defaults.json](./defaults.json) file.
#### options.requestOptions
These options are passed directly to request's options.
Some useful options include: `encoding: 'binary'` for old sites without character encoding declaration (try it if you're getting strange chars), authorization options (HTTP, Oauth, etc), proxies, SSL, cookies, among others.
### callback
A callback `Function` that follows the NodeJS error-first callback convention.
```js
function(err, data) {
if (err) return console.error(err) // Handle error
console.log(data) // Do something with data
}
```
## Alternatives
Here some alternative nodejs-based solutions similar to node-scrapy (in popularity order):
* [node-crawler](https://github.com/sylvinus/node-crawler)
* [node-scraper](https://github.com/mape/node-scraper)
* [skim](https://github.com/tcr/skim)
* [wscraper](https://github.com/kalise/wscraper)
* [html-scrapper](https://github.com/harish2704/html-scrapper)
* [scrapy](https://github.com/orkz/scrapy)
## Contributing
Scrapy is in an early stage, we would love you to involve in its development! Go ahead and open a [new issue](https://github.com/eeshi/node-scrapy/issues).
## License
__❤__ [MIT](./LICENSE)
| {
"content_hash": "428b49450370f3e59b4b28431da9c685",
"timestamp": "",
"source": "github",
"line_count": 267,
"max_line_length": 407,
"avg_line_length": 33.02996254681648,
"alnum_prop": 0.6913482254223835,
"repo_name": "beeman/node-scrapy",
"id": "970c8b402c253bd319f410256f6c4ab027666612",
"size": "8829",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "58606"
}
],
"symlink_target": ""
} |
/**
* @license Highstock JS v8.1.1 (2020-06-09)
*
* Indicator series type for Highstock
*
* (c) 2010-2019 Kacper Madej
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/indicators/zigzag', ['highcharts', 'highcharts/modules/stock'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'indicators/zigzag.src.js', [_modules['parts/Utilities.js']], function (U) {
/* *
*
* (c) 2010-2020 Kacper Madej
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var seriesType = U.seriesType;
var UNDEFINED;
/**
* The Zig Zag series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.zigzag
*
* @augments Highcharts.Series
*/
seriesType('zigzag', 'sma',
/**
* Zig Zag indicator.
*
* This series requires `linkedTo` option to be set.
*
* @sample stock/indicators/zigzag
* Zig Zag indicator
*
* @extends plotOptions.sma
* @since 6.0.0
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/zigzag
* @optionparent plotOptions.zigzag
*/
{
/**
* @excluding index, period
*/
params: {
/**
* The point index which indicator calculations will base - low
* value.
*
* For example using OHLC data, index=2 means the indicator will be
* calculated using Low values.
*/
lowIndex: 2,
/**
* The point index which indicator calculations will base - high
* value.
*
* For example using OHLC data, index=1 means the indicator will be
* calculated using High values.
*/
highIndex: 1,
/**
* The threshold for the value change.
*
* For example deviation=1 means the indicator will ignore all price
* movements less than 1%.
*/
deviation: 1
}
},
/**
* @lends Highcharts.Series#
*/
{
nameComponents: ['deviation'],
nameSuffixes: ['%'],
nameBase: 'Zig Zag',
getValues: function (series, params) {
var lowIndex = params.lowIndex,
highIndex = params.highIndex,
deviation = params.deviation / 100,
deviations = {
'low': 1 + deviation,
'high': 1 - deviation
},
xVal = series.xData,
yVal = series.yData,
yValLen = yVal ? yVal.length : 0,
zigzag = [],
xData = [],
yData = [],
i,
j,
zigzagPoint,
firstZigzagLow,
firstZigzagHigh,
directionUp,
zigzagLen,
exitLoop = false,
yIndex = false;
// Exit if not enught points or no low or high values
if (!xVal || xVal.length <= 1 ||
(yValLen &&
(yVal[0][lowIndex] === UNDEFINED ||
yVal[0][highIndex] === UNDEFINED))) {
return;
}
// Set first zigzag point candidate
firstZigzagLow = yVal[0][lowIndex];
firstZigzagHigh = yVal[0][highIndex];
// Search for a second zigzag point candidate,
// this will also set first zigzag point
for (i = 1; i < yValLen; i++) {
// requried change to go down
if (yVal[i][lowIndex] <= firstZigzagHigh * deviations.high) {
zigzag.push([xVal[0], firstZigzagHigh]);
// second zigzag point candidate
zigzagPoint = [xVal[i], yVal[i][lowIndex]];
// next line will be going up
directionUp = true;
exitLoop = true;
// requried change to go up
}
else if (yVal[i][highIndex] >= firstZigzagLow * deviations.low) {
zigzag.push([xVal[0], firstZigzagLow]);
// second zigzag point candidate
zigzagPoint = [xVal[i], yVal[i][highIndex]];
// next line will be going down
directionUp = false;
exitLoop = true;
}
if (exitLoop) {
xData.push(zigzag[0][0]);
yData.push(zigzag[0][1]);
j = i++;
i = yValLen;
}
}
// Search for next zigzags
for (i = j; i < yValLen; i++) {
if (directionUp) { // next line up
// lower when going down -> change zigzag candidate
if (yVal[i][lowIndex] <= zigzagPoint[1]) {
zigzagPoint = [xVal[i], yVal[i][lowIndex]];
}
// requried change to go down -> new zigzagpoint and
// direction change
if (yVal[i][highIndex] >=
zigzagPoint[1] * deviations.low) {
yIndex = highIndex;
}
}
else { // next line down
// higher when going up -> change zigzag candidate
if (yVal[i][highIndex] >= zigzagPoint[1]) {
zigzagPoint = [xVal[i], yVal[i][highIndex]];
}
// requried change to go down -> new zigzagpoint and
// direction change
if (yVal[i][lowIndex] <=
zigzagPoint[1] * deviations.high) {
yIndex = lowIndex;
}
}
if (yIndex !== false) { // new zigzag point and direction change
zigzag.push(zigzagPoint);
xData.push(zigzagPoint[0]);
yData.push(zigzagPoint[1]);
zigzagPoint = [xVal[i], yVal[i][yIndex]];
directionUp = !directionUp;
yIndex = false;
}
}
zigzagLen = zigzag.length;
// no zigzag for last point
if (zigzagLen !== 0 &&
zigzag[zigzagLen - 1][0] < xVal[yValLen - 1]) {
// set last point from zigzag candidate
zigzag.push(zigzagPoint);
xData.push(zigzagPoint[0]);
yData.push(zigzagPoint[1]);
}
return {
values: zigzag,
xData: xData,
yData: yData
};
}
});
/**
* A `Zig Zag` series. If the [type](#series.zigzag.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.zigzag
* @since 6.0.0
* @product highstock
* @excluding dataParser, dataURL
* @requires stock/indicators/indicators
* @requires stock/indicators/zigzag
* @apioption series.zigzag
*/
''; // adds doclets above to transpiled file
});
_registerModule(_modules, 'masters/indicators/zigzag.src.js', [], function () {
});
})); | {
"content_hash": "2f79314fae5ef82786752c8df0484a8d",
"timestamp": "",
"source": "github",
"line_count": 236,
"max_line_length": 114,
"avg_line_length": 38.41949152542373,
"alnum_prop": 0.42450645196867764,
"repo_name": "cdnjs/cdnjs",
"id": "066fcb6a6cb4e97f7f2327abe325242bf6f8db64",
"size": "9067",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/highcharts/8.1.1/indicators/zigzag.src.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html><html><head>
<title>iron-pages-basic</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1,user-scalable=yes">
<script src="../../webcomponentsjs/webcomponents-lite.js"></script>
<script src="../../web-component-tester/browser.js"></script>
<link rel="import" href="../iron-pages.html">
</head>
<body>
<test-fixture id="basic">
<template>
<iron-pages>
<div id="page0">Page 0</div>
<div id="page1">Page 1</div>
<div id="page2">Page 2</div>
<div id="page3">Page 3</div>
</iron-pages>
</template>
</test-fixture>
<script>suite("basic",function(){var e;suite("defaults",function(){setup(function(){e=fixture("basic")}),test("to nothing selected",function(){assert.equal(e.selected,void 0)}),test("null activateEvent",function(){assert.equal(e.activateEvent,null)}),test("to iron-selected as selectedClass",function(){assert.equal(e.selectedClass,"iron-selected")}),test("as many items as children",function(){assert.equal(e.items.length,4)}),test("all pages are display:none",function(){e.items.forEach(function(e){assert.equal(getComputedStyle(e).display,"none")})})}),suite("set the selected attribute",function(){setup(function(){e=fixture("basic"),e.selected=0}),test("selected value",function(){assert.equal(e.selected,"0")}),test("selected item",function(){assert.equal(e.selectedItem,e.items[0])}),test("selected item is display:block and all others are display:none",function(){e.items.forEach(function(t){assert.equal(getComputedStyle(t).display,t==e.selectedItem?"block":"none")})})})});</script>
</body></html> | {
"content_hash": "45f690685e731b67e264c04c4d13caac",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 996,
"avg_line_length": 59.06896551724138,
"alnum_prop": 0.6713368359603036,
"repo_name": "vladimirbrasil/testghpagepolymer",
"id": "166ef8c7afd5f7bffb770f924379401540ad3187",
"size": "1713",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bower_components/iron-pages/test/basic.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "836513"
},
{
"name": "JavaScript",
"bytes": "21121"
}
],
"symlink_target": ""
} |
define(function (require, exports, module) {
"use strict";
var StyleSheet = require("boost/StyleSheet");
var LayoutPropTypes = require("boost/LayoutPropTypes");
var validator = require("boost/validator");
var number = validator.number;
var dp = validator.dp;
var string = validator.string;
var color = validator.color;
var font = validator.font;
var _enum = validator.oneOf;
var TextStylePropTypes = StyleSheet.createPropTypes(LayoutPropTypes, {
"color": [color, "black"],
//"fontFamily": string,
"backgroundColor": [color, "transparent"],
"fontFamily": [font, "sans-serif"],
"fontSize": [number, 14],
"fontStyle": [_enum('normal', 'italic'), "normal"],
"fontWeight": [_enum("normal", 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'), "normal"],
"letterSpacing": [number, null], //TODO: 未在native代码中找到相应属性
"lineHeight": [dp, 0], //TODO: ok?
"textAlign": [_enum("auto", 'left', 'right', 'center', 'justify'), "auto"],
//"textDecorationColor": [string, "black"],
//"textDecorationLine": [_enum("none", 'underline', 'line-through', 'underline line-through'), "none"],
//"textDecorationStyle": [_enum("solid", 'double', 'dotted', 'dashed'), "solid"],
"writingDirection": [_enum("auto", 'ltr', 'rtl'), "ltr"],
"textDecoration": [_enum("none", "underline", "line-through"), "none"]
});
module.exports = TextStylePropTypes;
});
| {
"content_hash": "598e3368de2f95193cee27ffd50c556d",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 121,
"avg_line_length": 43.4,
"alnum_prop": 0.5924950625411455,
"repo_name": "Clouda-team/boostui-native",
"id": "892b82e3d88c219cfba7db37e22618d74217cd09",
"size": "1541",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "boost/TextStylePropTypes.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "100717"
}
],
"symlink_target": ""
} |
package org.cuacfm.members.test.web.configuration;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import java.util.Locale;
import javax.inject.Inject;
import org.cuacfm.members.model.account.Account;
import org.cuacfm.members.model.account.Account.roles;
import org.cuacfm.members.model.accountservice.AccountService;
import org.cuacfm.members.model.element.Element;
import org.cuacfm.members.model.elementservice.ElementService;
import org.cuacfm.members.model.exceptions.UniqueException;
import org.cuacfm.members.model.exceptions.UniqueListException;
import org.cuacfm.members.test.config.WebSecurityConfigurationAware;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
/** The class ProfileControlTest. */
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
public class ElementCreateControllerTest extends WebSecurityConfigurationAware {
private MockHttpSession defaultSession;
@Inject
private AccountService accountService;
@Inject
private ElementService elementService;
/**
* Initialize default session.
*
* @throws UniqueException, UniqueListException
*/
@Before
public void initializeDefaultSession() throws UniqueException, UniqueListException {
Account admin = new Account("admin", "", "55555555C", "London", "admin", "[email protected]", "666666666", "666666666", "admin", roles.ROLE_ADMIN);
accountService.save(admin);
defaultSession = getDefaultSession("[email protected]");
}
/**
* Display elementList page without signin in test.
*
* @throws Exception the exception
*/
@Test
public void displayaccountCreateCreatePageWithoutSiginInTest() throws Exception {
mockMvc.perform(get("/configuration/elementCreate")).andExpect(redirectedUrl("http://localhost/signin"));
}
/**
* Send displayselementList.
*
* @throws Exception the exception
*/
@Test
public void displaysElementCreateTest() throws Exception {
mockMvc.perform(get("/configuration/elementCreate").locale(Locale.ENGLISH).session(defaultSession))
.andExpect(view().name("configuration/elementcreate"));
}
/**
* Send displayselementList.
*
* @throws Exception the exception
*/
@Test
public void postElementCreateTest() throws Exception {
mockMvc.perform(post("/configuration/elementCreate").locale(Locale.ENGLISH).session(defaultSession).param("name", "Element 1")
.param("description", "Pay by Element 1")).andExpect(view().name("redirect:/configuration"));
}
/**
* Send displayselementList.
*
* @throws Exception the exception
*/
@Test
public void nameAlreadyExistTest() throws Exception {
Element element = new Element("element 1", "element 1", true, true);
elementService.save(element);
mockMvc.perform(post("/configuration/elementCreate").locale(Locale.ENGLISH).session(defaultSession).param("name", "Element 1")
.param("description", "Element 1"))
.andExpect(view().name("configuration/elementcreate"));
}
/**
* notBlankMessage.
*
* @throws Exception the exception
*/
@Test
public void notBlankMessageTest() throws Exception {
mockMvc.perform(post("/configuration/elementCreate").locale(Locale.ENGLISH).session(defaultSession))
.andExpect(content().string(containsString("The value may not be empty!")))
.andExpect(view().name("configuration/elementcreate"));
}
/**
* "Already exist type of formation with name "+ element.getName() + ", please chose other" Send displayselementList.
*
* @throws Exception the exception
*/
@Test
public void maxCharactersTest() throws Exception {
mockMvc.perform(post("/configuration/elementCreate").locale(Locale.ENGLISH).session(defaultSession)
.param("name", "111111111111111111111111111111111111111111111111111111111111111111111111111111")
.param("description", "11111111111111111111111111111111111111111111111111111111111111111111111").param("discount", "0"))
.andExpect(content().string(containsString("Maximum 50 characters"))).andExpect(view().name("configuration/elementcreate"));
}
} | {
"content_hash": "cdf363d58d567a274f52a0bd8785febd",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 144,
"avg_line_length": 36.21875,
"alnum_prop": 0.7767471958584987,
"repo_name": "pablogrela/members_cuacfm",
"id": "9e80a03b44cda00d6f65451612520b53e0d7fc6f",
"size": "5267",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/org/cuacfm/members/test/web/configuration/ElementCreateControllerTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "97025"
},
{
"name": "HTML",
"bytes": "441360"
},
{
"name": "Java",
"bytes": "2211835"
},
{
"name": "JavaScript",
"bytes": "353599"
}
],
"symlink_target": ""
} |
AJS.Confluence.SharePage={};
AJS.Confluence.SharePage.autocompleteUser=function(C){C=C||document.body;
var D=AJS.$,A=/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var B=function(F){if(!F||!F.result){throw new Error("Invalid JSON format")
}var E=[];
E.push(F.result);
return E
};
D("input.autocomplete-sharepage[data-autocomplete-user-bound!=true]",C).each(function(){var G=D(this).attr("data-autocomplete-sharepage-bound","true").attr("autocomplete","off");
var F=G.attr("data-max")||10,I=G.attr("data-alignment")||"left",H=G.attr("data-dropdown-target"),E=null;
if(H){E=D(H)
}else{E=D("<div></div>");
G.after(E)
}E.addClass("aui-dd-parent autocomplete");
G.quicksearch(AJS.REST.getBaseUrl()+"search/user.json",function(){G.trigger("open.autocomplete-sharepage")
},{makeParams:function(J){return{"max-results":F,query:J}
},dropdownPlacement:function(J){E.append(J)
},makeRestMatrixFromData:B,addDropdownData:function(J){if(A.test(G.val())){J.push([{name:G.val(),email:G.val(),href:"#",icon:AJS.Confluence.getContextPath()+"/images/icons/profilepics/anonymous.png"}])
}if(!J.length){var K=G.attr("data-none-message");
if(K){J.push([{name:K,className:"no-results",href:"#"}])
}}return J
},ajsDropDownOptions:{alignment:I,displayHandler:function(J){if(J.restObj&&J.restObj.username){return J.name+" ("+J.restObj.username+")"
}return J.name
},selectionHandler:function(L,K){if(K.find(".search-for").length){G.trigger("selected.autocomplete-sharepage",{searchFor:G.val()});
return
}if(K.find(".no-results").length){this.hide();
L.preventDefault();
return
}var J=D("span:eq(0)",K).data("properties");
if(!J.email){J=J.restObj
}G.trigger("selected.autocomplete-sharepage",{content:J});
this.hide();
L.preventDefault()
}}})
})
};
(function(E){var D,B={hideCallback:A,width:280,offsetY:17,offsetX:-40,hideDelay:3600000};
var A=function(){E(".dashboard-actions .explanation").hide()
};
var C=function(I,G,H){I.empty();
I.append(AJS.template.load("share-content-popup").fill());
AJS.Confluence.SharePage.autocompleteUser();
var J=function(){D.hide();
return false
};
E(document).keyup(function(L){if(L.keyCode==27){J();
E(document).unbind("keyup",arguments.callee);
return false
}return true
});
I.find(".close-dialog").click(J);
I.find("form").submit(function(){var O=[];
I.find(".recipients li").each(function(P,Q){O.push(E(Q).attr("data-username"))
});
if(O.length<=0){return false
}E("button,input,textarea",this).attr("disabled","disabled");
I.find(".progress-messages").text("Sending");
var L=Raphael.spinner(I.find(".progress-messages-icon")[0],7,"#666");
I.find(".progress-messages-icon").css("left","10px").css("position","absolute");
I.find(".progress-messages").css("padding-left",I.find(".progress-messages-icon").innerWidth()+5);
var O=[];
I.find(".recipients li[data-username]").each(function(P,Q){O.push(E(Q).attr("data-username"))
});
var N=[];
I.find(".recipients li[data-email]").each(function(P,Q){N.push(E(Q).attr("data-email"))
});
var M={users:O,emails:N,note:I.find("#note").val(),entityId:AJS.params.pageId};
E.ajax({type:"POST",contentType:"application/json; charset=utf-8",url:AJS.Confluence.getContextPath()+"/rest/share-page/latest/share",data:JSON.stringify(M),dataType:"text",success:function(){setTimeout(function(){L();
I.find(".progress-messages-icon").css("width","17px");
I.find(".progress-messages-icon").css("height","17px");
I.find(".progress-messages-icon").addClass("done");
I.find(".progress-messages").text("Sent");
setTimeout(function(){J()
},1000)
},500)
},error:function(Q,P){L();
I.find(".progress-messages-icon").css("width","17px");
I.find(".progress-messages-icon").css("height","17px");
I.find(".progress-messages-icon").addClass("error");
I.find(".progress-messages").text("Error while sending")
}});
return false
});
var K=I.find("#users");
var F=I.find(".button-panel input");
K.bind("selected.autocomplete-sharepage",function(M,L){var N=function(P,Q){var S=I.find(".recipients"),R,O;
R="li[data-"+P+'="'+Q.content[P]+'"]';
if(S.find(R).length>0){S.find(R).hide()
}else{S.append(AJS.template.load("share-content-popup-recipient-"+P).fill(Q.content))
}O=S.find(R);
O.find(".remove-recipient").click(function(){O.remove();
if(S.find("li").length==0){F.attr("disabled","true")
}D.refresh();
K.focus();
return false
});
O.fadeIn(200)
};
if(L.content.email){N("email",L)
}else{N("username",L)
}D.refresh();
F.removeAttr("disabled");
K.val("");
return false
});
K.bind("open.autocomplete-sharepage",function(M,L){if(E("a:not(.no-results)",AJS.dropDown.current.links).length>0){AJS.dropDown.current.moveDown()
}});
K.keypress(function(L){if(L.keyCode==13){return false
}return true
});
E(document).bind("showLayer",function(N,M,L){if(M=="inlineDialog"&&L.popup==D){L.popup.find("#users").focus()
}});
H()
};
AJS.toInit(function(F){D=AJS.InlineDialog(F("#shareContentLink"),"shareContentPopup",C,B)
})
})(AJS.$);
| {
"content_hash": "f8de9b21343f236cffee0fbf2108972d",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 218,
"avg_line_length": 41.64102564102564,
"alnum_prop": 0.6898604269293924,
"repo_name": "mlc0202/dubbo.github.io",
"id": "2372b1438ba07a94a3423d9de50c7c417aa21fb3",
"size": "4872",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "com.atlassian.confluence.plugins.share-page-mail-page-resources.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "70278"
},
{
"name": "HTML",
"bytes": "353086757"
},
{
"name": "JavaScript",
"bytes": "835313"
}
],
"symlink_target": ""
} |
package entity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
public class TabInfo {
private String tag;
private Class<?> clss;
private Bundle args;
private Fragment fragment;
public TabInfo(String tag, Class<?> clazz, Bundle args) {
this.tag = tag;
this.clss = clazz;
this.args = args;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public Bundle getArgs() {
return args;
}
public void setArgs(Bundle args) {
this.args = args;
}
public Fragment getFragment() {
return fragment;
}
public void setFragment(Fragment fragment) {
this.fragment = fragment;
}
}
| {
"content_hash": "e1bdaed404958a02a4c0479f689b53c1",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 61,
"avg_line_length": 18.452380952380953,
"alnum_prop": 0.5935483870967742,
"repo_name": "chinglimchan/SwipeTabsDemo",
"id": "b51d8001ddbd535d49a5d91200867804b0b99a61",
"size": "775",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/entity/TabInfo.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "7450"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>zchinese: 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.8.0 / zchinese - 8.7.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
zchinese
<small>
8.7.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-02-19 02:36:57 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-19 02:36:57 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.8.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.1 Official release 4.09.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/zchinese"
license: "Unknown"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/ZChinese"]
depends: [
"ocaml"
"coq" {>= "8.7" & < "8.8~"}
]
tags: [ "keyword: number theory" "keyword: chinese remainder" "keyword: primality" "keyword: prime numbers" "category: Mathematics/Arithmetic and Number Theory/Number theory" "category: Miscellaneous/Extracted Programs/Arithmetic" ]
authors: [ "Valérie Ménissier-Morain" ]
bug-reports: "https://github.com/coq-contribs/zchinese/issues"
dev-repo: "git+https://github.com/coq-contribs/zchinese.git"
synopsis: "A proof of the Chinese Remainder Lemma"
description:
"This is a rewriting of the contribution chinese-lemma using Zarith"
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/zchinese/archive/v8.7.0.tar.gz"
checksum: "md5=1ab48fb8b7e465c03507ec79d9f77f32"
}
</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-zchinese.8.7.0 coq.8.8.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.8.0).
The following dependencies couldn't be met:
- coq-zchinese -> coq < 8.8~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
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-zchinese.8.7.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": "ae1f572033635301ca93dc501646d650",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 292,
"avg_line_length": 42.43636363636364,
"alnum_prop": 0.5458440445586975,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "d2b85832dc32c7e5c2a2c021103c94e665a1286d",
"size": "7029",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.09.1-2.0.6/released/8.8.0/zchinese/8.7.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
from __future__ import print_function
import glob
import motmot.FlyMovieFormat.FlyMovieFormat as FlyMovieFormat
# change this to current filenames
input_filenames = glob.glob("/home/jbender/data/081704_a*.fmf")
for input_filename in input_filenames:
output_filename = input_filename + ".aoi"
input_fmf = FlyMovieFormat.FlyMovie(input_filename)
in_width = input_fmf.get_width()
in_height = input_fmf.get_height()
# change these to current aoi
xmin, ymin = 280, 260
width, height = 100, 100
xmax = xmin + width
ymax = ymin + height
fmin = 0
fmax = input_fmf.get_n_frames()
finterval = 1
frame_numbers = range(fmin, fmax, finterval)
n_output_frames = len(frame_numbers)
output_fmf = FlyMovieFormat.FlyMovieSaver(output_filename, version=1)
print("%(input_filename)s (%(in_width)dx%(in_height)d, " "%(fmax)d frames) ->" % locals())
print(" %(output_filename)s (%(width)dx%(height)d, " "%(n_output_frames)d frames) : " % locals(), end=' ')
for i in range(fmin, fmax, finterval):
frame, timestamp = input_fmf.get_next_frame()
output_fmf.add_frame(frame[ymin:ymax, xmin:xmax], timestamp)
j = i + 1
print("\b\b\b\b\b\b\b\b\b\b%(j)4d/%(fmax)4d" % locals(), end=' ')
output_fmf.close()
print()
| {
"content_hash": "b080d39af55ca0d133829a3dc1f56cb5",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 122,
"avg_line_length": 32.95,
"alnum_prop": 0.6388467374810318,
"repo_name": "motmot/flymovieformat",
"id": "8f42cebf320a84f6931f66b063c287619d9b0a8b",
"size": "1340",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/fmf_batch_process.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "25332"
},
{
"name": "Makefile",
"bytes": "6443"
},
{
"name": "Matlab",
"bytes": "15721"
},
{
"name": "Python",
"bytes": "96796"
}
],
"symlink_target": ""
} |
package com.netflix.spinnaker.front50.migrations;
import com.netflix.spinnaker.front50.api.model.pipeline.Pipeline;
import com.netflix.spinnaker.front50.model.pipeline.PipelineDAO;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class SpelLoadBalancersMigration implements Migration {
private final PipelineDAO pipelineDAO;
public SpelLoadBalancersMigration(PipelineDAO pipelineDAO) {
this.pipelineDAO = pipelineDAO;
}
public boolean isValid() {
return true;
}
public void run() {
log.info("Starting spelLoadBalancers migration");
Collection<Pipeline> pipelines = pipelineDAO.all();
int migratedCount = 0;
int failureCount = 0;
for (Pipeline pipeline : pipelines) {
try {
if (migrate(pipeline)) {
migratedCount++;
}
} catch (Exception e) {
log.error(
"Failed to migrate pipeline {} ({}) for {} spelLoadBalancersMigration",
pipeline.getName(),
pipeline.getId(),
pipeline.getApplication(),
e);
failureCount++;
}
}
log.info(
"Done with spelLoadBalancers migration (migrated {} pipelines; {} failed to migrate)",
migratedCount,
failureCount);
}
/** Removes spelLoadBalancers and spelTargetGroups from all deploy stage[].clusters[] */
private boolean migrate(Pipeline pipeline) {
List<Map<String, Object>> stages = pipeline.getStages();
if (stages == null) {
stages = Collections.emptyList();
}
List<Map<String, Object>> clusters =
stages.stream()
.filter(stage -> "deploy".equals(stage.get("type")))
.flatMap(
stage ->
((List<Map<String, Object>>)
stage.getOrDefault("clusters", Collections.emptyList()))
.stream())
.filter(
cluster ->
cluster.get("spelLoadBalancers") != null
|| cluster.get("spelTargetGroups") != null)
.collect(Collectors.toList());
if (clusters.isEmpty()) {
return false;
}
for (Map<String, Object> cluster : clusters) {
cluster.remove("spelLoadBalancers");
cluster.remove("spelTargetGroups");
}
pipelineDAO.update(pipeline.getId(), pipeline);
log.info(
"Migrated pipeline {} ({}) for {} spelLoadBalancersMigration",
pipeline.getName(),
pipeline.getId(),
pipeline.getApplication());
return true;
}
}
| {
"content_hash": "6515bfdca0d94d543c7ad84431af1b44",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 94,
"avg_line_length": 30.662921348314608,
"alnum_prop": 0.6185415903261268,
"repo_name": "spinnaker/front50",
"id": "d26171341b64c19e4e92872a2e90c9c29c38c4af",
"size": "2729",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "front50-migrations/src/main/java/com/netflix/spinnaker/front50/migrations/SpelLoadBalancersMigration.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "216631"
},
{
"name": "Java",
"bytes": "502533"
},
{
"name": "Kotlin",
"bytes": "122942"
},
{
"name": "Shell",
"bytes": "394"
},
{
"name": "Slim",
"bytes": "380"
}
],
"symlink_target": ""
} |
@interface IndexBuffer : GraphicsResource {
uint bufferID;
BufferUsage bufferUsage;
int indexCount;
IndexElementSize indexElementSize;
}
- (id) initWithGraphicsDevice:(GraphicsDevice *)theGraphicsDevice
indexElementSize:(IndexElementSize)theIndexElementSize
indexCount:(int)theIndexCount
usage:(BufferUsage)theBufferUsage;
@property (nonatomic, readonly) BufferUsage bufferUsage;
@property (nonatomic, readonly) int indexCount;
@property (nonatomic, readonly) IndexElementSize indexElementSize;
- (void) setData:(IndexArray*)data;
@end | {
"content_hash": "a2d34f998af4bb64b6fd076b97202a44",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 66,
"avg_line_length": 29.526315789473685,
"alnum_prop": 0.7967914438502673,
"repo_name": "paidgeek/glomero-xni",
"id": "3c01b174bdaf927e8411b41a07c11436d09a2a50",
"size": "751",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "XNI/include/XNI/IndexBuffer.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "19421"
},
{
"name": "Objective-C",
"bytes": "287503"
},
{
"name": "Shell",
"bytes": "385"
}
],
"symlink_target": ""
} |
layout: post
title: The basic concepts of Angular JS
---

[courtesy](https://www.amitavroy.com/justread/content/articles/working-xml-angular-js/)
# Why should we use Angular JS?
- Helps organize the javascript code
- Helps create responsive (as in fast) websites
- Plays well with jQuery
- Is easy to test
# What is Angular JS?
> A client side javascript framework for adding interactivity to HTML.
We need to figure out when to trigger our Javascript.
# Directives
> A directive is a marker on a HTML tag that tells Angular to run or reference some Javascript code.
e.g. In the following code snippet, `ng-crontroller` is a **marker** on body tag
<body ng-crontroller='abcController'>
</body>
And the referenced javascript code is:
function abcController(){
alert('hello Angular JS!');
}
The first step is to download the library from the [official website](https://angularjs.org)
# Modules
- Modules are where we write pieces of our Angular application to keep our code encapsulated to make our code more maintainable, testable and readable.
- Modules are where we define depencies for our application.

Let's create a module:
var app = angular.module('abcApp',[]);
And use it:
<html ng-app='abcApp'>
</html>
The above code does nothing as such, currently it is just saying that the entire `HTML` area is part of the Angular application. We can start using expressions at this point:
{{ 4 + 6 }}
Expressions can also be used for string manipulation:
{{ 'Hello ' + 'AngularJS' }}
# Controllers
> Controllers are where we define our app's behavior by defining functions and values.
Let's have some data printed on the view using controller.
(function(){
var app = angular.module('abc', []);
app.controller('abcController', function(){
this.a = abc;
});
var abc = {
propertyA : 'A',
propertyB: 'B'
};
})();
The view should look like this:
<div ng-controller='abcController as abc' >
{{abc.a.propertyA}}
{{abc.a.propertyB}}
</div>
This works well with a single object but what if we have an array?
Inside a controller:
(function(){
var app = angular.module('abc', []);
app.controller('abcController', function(){
this.as = abc;
});
var abc = [{
propertyA : 'A',
propertyB: 'B'
}, {
propertyA : 'C',
propertyB: 'D'
}, {
propertyA : 'E',
propertyB: 'F'
}];
})();
To show this in the view, we need to use `ng-repeat`:
<div ng-controller='abcController as abc' >
<div ng-repeat='a in abc.as'>
{{a.propertyA}}
{{a.propertyB}}
</div>
</div>
There are a lot of [build in directives](http://www.techstrikers.com/AngularJS/angularjs-built-in-directives.php) like `ng-app`, `ng-controller`, `ng-show`, `ng-hide`, `ng-repeat` etc.
# Filters
The basic formula of filters is as follows:
{{ data* | filter: options*}}
e.g.:
{{ '1388123412323' | date: 'MM/dd/yyyy @ h:mm' }} <!-- formats the date -->
{{ 'lowercase string' | uppercase }} <!-- uppercases the string -->
{{ 'a vvveeeerrrryy llooonnngggg strrrriiiinngggg' | limitTo: 8 }} <!-- limits the string to specified number 8 -->
<li ng-repeat='a in abcs | limitTo: 3'> <!-- limits the array elements to specified number 3 -->
<li ng-repeat='a in abcs | orderBy: -A'> <!-- sorts the array elements in descending order because of - charachter -->
The pipe charachter in the expression asks the expression to take the first parameter to the expression and pass it to the second part of the expression. Like in the following:
{{ '$2.695865' | currency }}
Currency is a filter in this case.
[source](https://www.codeschool.com/courses/shaping-up-with-angularjs) | {
"content_hash": "a69f83218db9ca0d9a268992095424f2",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 699,
"avg_line_length": 30.789115646258505,
"alnum_prop": 0.7218294299602298,
"repo_name": "xameeramir/xameeramir.github.io",
"id": "31bc9498e3384a986731df1d5c6794f7f8f841d5",
"size": "4530",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2016-3-1-The-basic-concepts-of-Angular-JS.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "203632"
},
{
"name": "HTML",
"bytes": "802432"
},
{
"name": "JavaScript",
"bytes": "96"
}
],
"symlink_target": ""
} |
credit to blackrock digital for providing the base theme of this website.
below is the original readme.md as provided by the creator of this theme.
# [Start Bootstrap](http://startbootstrap.com/) - [Freelancer](http://startbootstrap.com/template-overviews/freelancer/)
[Freelancer](http://startbootstrap.com/template-overviews/freelancer/) is a one page freelancer portfolio theme for [Bootstrap](http://getbootstrap.com/) created by [Start Bootstrap](http://startbootstrap.com/). This theme features several content sections, a responsive portfolio grid with hover effects, full page portfolio item modals, and a working PHP contact form.
## Getting Started
To begin using this template, choose one of the following options to get started:
* [Download the latest release on Start Bootstrap](http://startbootstrap.com/template-overviews/freelancer/)
* Clone the repo: `git clone https://github.com/BlackrockDigital/startbootstrap-freelancer.git`
* Fork the repo
## Bugs and Issues
Have a bug or an issue with this template? [Open a new issue](https://github.com/BlackrockDigital/startbootstrap-freelancer/issues) here on GitHub or leave a comment on the [template overview page at Start Bootstrap](http://startbootstrap.com/template-overviews/freelancer/).
## Creator
Start Bootstrap was created by and is maintained by **[David Miller](http://davidmiller.io/)**, Owner of [Blackrock Digital](http://blackrockdigital.io/).
* https://twitter.com/davidmillerskt
* https://github.com/davidtmiller
Start Bootstrap is based on the [Bootstrap](http://getbootstrap.com/) framework created by [Mark Otto](https://twitter.com/mdo) and [Jacob Thorton](https://twitter.com/fat).
## Copyright and License
Copyright 2013-2016 Blackrock Digital LLC. Code released under the [MIT](https://github.com/BlackrockDigital/startbootstrap-freelancer/blob/gh-pages/LICENSE) license. | {
"content_hash": "e00bdcafc2d15fa9497f2d487839e78d",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 370,
"avg_line_length": 60.38709677419355,
"alnum_prop": 0.7841880341880342,
"repo_name": "patwong/patwong.github.io",
"id": "2bb8d521b8f0f3a0c641de8d813faeb6f6b3aa7a",
"size": "1891",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "21268"
},
{
"name": "HTML",
"bytes": "10315745"
},
{
"name": "JavaScript",
"bytes": "142369"
}
],
"symlink_target": ""
} |
import random
from neutron.common import constants
from neutron.common import exceptions
from neutron import context
from neutron.db import external_net_db
from neutron.db import l3_db
from neutron.db import models_v2
from neutron.openstack.common import jsonutils
from neutron.openstack.common import log
from neutron.openstack.common import loopingcall
from neutron.openstack.common import timeutils
from neutron.plugins.nicira.common import exceptions as nvp_exc
from neutron.plugins.nicira import NvpApiClient
from neutron.plugins.nicira import nvplib
LOG = log.getLogger(__name__)
class NvpCache(object):
"""A simple Cache for NVP resources.
Associates resource id with resource hash to rapidly identify
updated resources.
Each entry in the cache also stores the following information:
- changed: the resource in the cache has been altered following
an update or a delete
- hit: the resource has been visited during an update (and possibly
left unchanged)
- data: current resource data
- data_bk: backup of resource data prior to its removal
"""
def __init__(self):
# Maps a uuid to the dict containing it
self._uuid_dict_mappings = {}
# Dicts for NVP cached resources
self._lswitches = {}
self._lswitchports = {}
self._lrouters = {}
def __getitem__(self, key):
# uuids are unique across the various types of resources
# TODO(salv-orlando): Avoid lookups over all dictionaries
# when retrieving items
# Fetch lswitches, lports, or lrouters
resources = self._uuid_dict_mappings[key]
return resources[key]
def _update_resources(self, resources, new_resources):
# Clear the 'changed' attribute for all items
for uuid, item in resources.items():
if item.pop('changed', None) and not item.get('data'):
# The item is not anymore in NVP, so delete it
del resources[uuid]
del self._uuid_dict_mappings[uuid]
def do_hash(item):
return hash(jsonutils.dumps(item))
# Parse new data and identify new, deleted, and updated resources
for item in new_resources:
item_id = item['uuid']
if resources.get(item_id):
new_hash = do_hash(item)
if new_hash != resources[item_id]['hash']:
resources[item_id]['hash'] = new_hash
resources[item_id]['changed'] = True
resources[item_id]['data_bk'] = (
resources[item_id]['data'])
resources[item_id]['data'] = item
# Mark the item as hit in any case
resources[item_id]['hit'] = True
else:
resources[item_id] = {'hash': do_hash(item)}
resources[item_id]['hit'] = True
resources[item_id]['changed'] = True
resources[item_id]['data'] = item
# add a uuid to dict mapping for easy retrieval
# with __getitem__
self._uuid_dict_mappings[item_id] = resources
def _delete_resources(self, resources):
# Mark for removal all the elements which have not been visited.
# And clear the 'hit' attribute.
for to_delete in [k for (k, v) in resources.iteritems()
if not v.pop('hit', False)]:
resources[to_delete]['changed'] = True
resources[to_delete]['data_bk'] = (
resources[to_delete].pop('data', None))
def _get_resource_ids(self, resources, changed_only):
if changed_only:
return [k for (k, v) in resources.iteritems()
if v.get('changed')]
return resources.keys()
def get_lswitches(self, changed_only=False):
return self._get_resource_ids(self._lswitches, changed_only)
def get_lrouters(self, changed_only=False):
return self._get_resource_ids(self._lrouters, changed_only)
def get_lswitchports(self, changed_only=False):
return self._get_resource_ids(self._lswitchports, changed_only)
def update_lswitch(self, lswitch):
self._update_resources(self._lswitches, [lswitch])
def update_lrouter(self, lrouter):
self._update_resources(self._lrouters, [lrouter])
def update_lswitchport(self, lswitchport):
self._update_resources(self._lswitchports, [lswitchport])
def process_updates(self, lswitches=None,
lrouters=None, lswitchports=None):
self._update_resources(self._lswitches, lswitches)
self._update_resources(self._lrouters, lrouters)
self._update_resources(self._lswitchports, lswitchports)
return (self._get_resource_ids(self._lswitches, changed_only=True),
self._get_resource_ids(self._lrouters, changed_only=True),
self._get_resource_ids(self._lswitchports, changed_only=True))
def process_deletes(self):
self._delete_resources(self._lswitches)
self._delete_resources(self._lrouters)
self._delete_resources(self._lswitchports)
return (self._get_resource_ids(self._lswitches, changed_only=True),
self._get_resource_ids(self._lrouters, changed_only=True),
self._get_resource_ids(self._lswitchports, changed_only=True))
class SyncParameters():
"""Defines attributes used by the synchronization procedure.
chunk_size: Actual chunk size
extra_chunk_size: Additional data to fetch because of chunk size
adjustment
current_chunk: Counter of the current data chunk being synchronized
Page cursors: markers for the next resource to fetch.
'start' means page cursor unset for fetching 1st page
init_sync_performed: True if the initial synchronization concluded
"""
def __init__(self, min_chunk_size):
self.chunk_size = min_chunk_size
self.extra_chunk_size = 0
self.current_chunk = 0
self.ls_cursor = 'start'
self.lr_cursor = 'start'
self.lp_cursor = 'start'
self.init_sync_performed = False
self.total_size = 0
def _start_loopingcall(min_chunk_size, state_sync_interval, func):
"""Start a loopingcall for the synchronization task."""
# Start a looping call to synchronize operational status
# for neutron resources
if not state_sync_interval:
# do not start the looping call if specified
# sync interval is 0
return
state_synchronizer = loopingcall.DynamicLoopingCall(
func, sp=SyncParameters(min_chunk_size))
state_synchronizer.start(
periodic_interval_max=state_sync_interval)
return state_synchronizer
class NvpSynchronizer():
LS_URI = nvplib._build_uri_path(
nvplib.LSWITCH_RESOURCE, fields='uuid,tags,fabric_status',
relations='LogicalSwitchStatus')
LR_URI = nvplib._build_uri_path(
nvplib.LROUTER_RESOURCE, fields='uuid,tags,fabric_status',
relations='LogicalRouterStatus')
LP_URI = nvplib._build_uri_path(
nvplib.LSWITCHPORT_RESOURCE,
parent_resource_id='*',
fields='uuid,tags,fabric_status,link_status_up',
relations='LogicalPortStatus')
def __init__(self, plugin, cluster, state_sync_interval,
req_delay, min_chunk_size, max_rand_delay=0):
random.seed()
self._nvp_cache = NvpCache()
# Store parameters as instance members
# NOTE(salv-orlando): apologies if it looks java-ish
self._plugin = plugin
self._cluster = cluster
self._req_delay = req_delay
self._sync_interval = state_sync_interval
self._max_rand_delay = max_rand_delay
# Validate parameters
if self._sync_interval < self._req_delay:
err_msg = (_("Minimum request delay:%(req_delay)s must not "
"exceed synchronization interval:%(sync_interval)s") %
{'req_delay': self._req_delay,
'sync_interval': self._sync_interval})
LOG.error(err_msg)
raise nvp_exc.NvpPluginException(err_msg=err_msg)
# Backoff time in case of failures while fetching sync data
self._sync_backoff = 1
# Store the looping call in an instance variable to allow unit tests
# for controlling its lifecycle
self._sync_looping_call = _start_loopingcall(
min_chunk_size, state_sync_interval, self._synchronize_state)
def _get_tag_dict(self, tags):
return dict((tag.get('scope'), tag['tag']) for tag in tags)
def _update_neutron_object(self, context, neutron_data, status):
if status == neutron_data['status']:
# do nothing
return
with context.session.begin(subtransactions=True):
LOG.debug(_("Updating status for neutron resource %(q_id)s to: "
"%(status)s"), {'q_id': neutron_data['id'],
'status': status})
neutron_data['status'] = status
context.session.add(neutron_data)
def synchronize_network(self, context, neutron_network_data,
lswitches=None):
"""Synchronize a Neutron network with its NVP counterpart.
This routine synchronizes a set of switches when a Neutron
network is mapped to multiple lswitches.
"""
if not lswitches:
# Try to get logical switches from nvp
try:
lswitches = nvplib.get_lswitches(
self._cluster, neutron_network_data['id'])
except exceptions.NetworkNotFound:
# TODO(salv-orlando): We should be catching
# NvpApiClient.ResourceNotFound here
# The logical switch was not found
LOG.warning(_("Logical switch for neutron network %s not "
"found on NVP."), neutron_network_data['id'])
lswitches = []
else:
for lswitch in lswitches:
self._nvp_cache.update_lswitch(lswitch)
# By default assume things go wrong
status = constants.NET_STATUS_ERROR
# In most cases lswitches will contain a single element
for ls in lswitches:
if not ls:
# Logical switch was deleted
break
ls_status = ls['_relations']['LogicalSwitchStatus']
if not ls_status['fabric_status']:
status = constants.NET_STATUS_DOWN
break
else:
# No switch was down or missing. Set status to ACTIVE unless
# there were no switches in the first place!
if lswitches:
status = constants.NET_STATUS_ACTIVE
# Update db object
self._update_neutron_object(context, neutron_network_data, status)
def _synchronize_lswitches(self, ctx, ls_uuids, scan_missing=False):
if not ls_uuids and not scan_missing:
return
neutron_net_ids = set()
neutron_nvp_mappings = {}
# TODO(salvatore-orlando): Deal with the case the tag
# has been tampered with
for ls_uuid in ls_uuids:
# If the lswitch has been deleted, get backup copy of data
lswitch = (self._nvp_cache[ls_uuid].get('data') or
self._nvp_cache[ls_uuid].get('data_bk'))
tags = self._get_tag_dict(lswitch['tags'])
neutron_id = tags.get('neutron_net_id', ls_uuid)
neutron_net_ids.add(neutron_id)
neutron_nvp_mappings[neutron_id] = (
neutron_nvp_mappings.get(neutron_id, []) +
[self._nvp_cache[ls_uuid]])
with ctx.session.begin(subtransactions=True):
# Fetch neutron networks from database
filters = {'router:external': [False]}
if not scan_missing:
filters['id'] = neutron_net_ids
# TODO(salv-orlando): Filter out external networks
for network in self._plugin._get_collection_query(
ctx, models_v2.Network, filters=filters):
lswitches = neutron_nvp_mappings.get(network['id'], [])
lswitches = [lswitch.get('data') for lswitch in lswitches]
self.synchronize_network(ctx, network, lswitches)
def synchronize_router(self, context, neutron_router_data,
lrouter=None):
"""Synchronize a neutron router with its NVP counterpart."""
if not lrouter:
# Try to get router from nvp
try:
# This query will return the logical router status too
lrouter = nvplib.get_lrouter(
self._cluster, neutron_router_data['id'])
except exceptions.NotFound:
# NOTE(salv-orlando): We should be catching
# NvpApiClient.ResourceNotFound here
# The logical router was not found
LOG.warning(_("Logical router for neutron router %s not "
"found on NVP."), neutron_router_data['id'])
lrouter = None
else:
# Update the cache
self._nvp_cache.update_lrouter(lrouter)
# Note(salv-orlando): It might worth adding a check to verify neutron
# resource tag in nvp entity matches a Neutron id.
# By default assume things go wrong
status = constants.NET_STATUS_ERROR
if lrouter:
lr_status = (lrouter['_relations']
['LogicalRouterStatus']
['fabric_status'])
status = (lr_status and
constants.NET_STATUS_ACTIVE
or constants.NET_STATUS_DOWN)
# Update db object
self._update_neutron_object(context, neutron_router_data, status)
def _synchronize_lrouters(self, ctx, lr_uuids, scan_missing=False):
if not lr_uuids and not scan_missing:
return
neutron_router_mappings = (
dict((lr_uuid, self._nvp_cache[lr_uuid]) for lr_uuid in lr_uuids))
with ctx.session.begin(subtransactions=True):
# Fetch neutron routers from database
filters = ({} if scan_missing else
{'id': neutron_router_mappings.keys()})
for router in self._plugin._get_collection_query(
ctx, l3_db.Router, filters=filters):
lrouter = neutron_router_mappings.get(router['id'])
self.synchronize_router(
ctx, router, lrouter and lrouter.get('data'))
def synchronize_port(self, context, neutron_port_data,
lswitchport=None, ext_networks=None):
"""Synchronize a Neutron port with its NVP counterpart."""
# Skip synchronization for ports on external networks
if not ext_networks:
ext_networks = [net['id'] for net in context.session.query(
models_v2.Network).join(
external_net_db.ExternalNetwork,
(models_v2.Network.id ==
external_net_db.ExternalNetwork.network_id))]
if neutron_port_data['network_id'] in ext_networks:
with context.session.begin(subtransactions=True):
neutron_port_data['status'] = constants.PORT_STATUS_ACTIVE
return
if not lswitchport:
# Try to get port from nvp
try:
lp_uuid = self._plugin._nvp_get_port_id(
context, self._cluster, neutron_port_data)
if lp_uuid:
lswitchport = nvplib.get_port(
self._cluster, neutron_port_data['network_id'],
lp_uuid, relations='LogicalPortStatus')
except (exceptions.PortNotFoundOnNetwork):
# NOTE(salv-orlando): We should be catching
# NvpApiClient.ResourceNotFound here instead
# of PortNotFoundOnNetwork when the id exists but
# the logical switch port was not found
LOG.warning(_("Logical switch port for neutron port %s "
"not found on NVP."), neutron_port_data['id'])
lswitchport = None
else:
# If lswitchport is not None, update the cache.
# It could be none if the port was deleted from the backend
if lswitchport:
self._nvp_cache.update_lswitchport(lswitchport)
# Note(salv-orlando): It might worth adding a check to verify neutron
# resource tag in nvp entity matches Neutron id.
# By default assume things go wrong
status = constants.PORT_STATUS_ERROR
if lswitchport:
lp_status = (lswitchport['_relations']
['LogicalPortStatus']
['link_status_up'])
status = (lp_status and
constants.PORT_STATUS_ACTIVE
or constants.PORT_STATUS_DOWN)
# Update db object
self._update_neutron_object(context, neutron_port_data, status)
def _synchronize_lswitchports(self, ctx, lp_uuids, scan_missing=False):
if not lp_uuids and not scan_missing:
return
# Find Neutron port id by tag - the tag is already
# loaded in memory, no reason for doing a db query
# TODO(salvatore-orlando): Deal with the case the tag
# has been tampered with
neutron_port_mappings = {}
for lp_uuid in lp_uuids:
lport = (self._nvp_cache[lp_uuid].get('data') or
self._nvp_cache[lp_uuid].get('data_bk'))
tags = self._get_tag_dict(lport['tags'])
neutron_port_id = tags.get('q_port_id')
if neutron_port_id:
neutron_port_mappings[neutron_port_id] = (
self._nvp_cache[lp_uuid])
with ctx.session.begin(subtransactions=True):
# Fetch neutron ports from database
# At the first sync we need to fetch all ports
filters = ({} if scan_missing else
{'id': neutron_port_mappings.keys()})
# TODO(salv-orlando): Work out a solution for avoiding
# this query
ext_nets = [net['id'] for net in ctx.session.query(
models_v2.Network).join(
external_net_db.ExternalNetwork,
(models_v2.Network.id ==
external_net_db.ExternalNetwork.network_id))]
for port in self._plugin._get_collection_query(
ctx, models_v2.Port, filters=filters):
lswitchport = neutron_port_mappings.get(port['id'])
self.synchronize_port(
ctx, port, lswitchport and lswitchport.get('data'),
ext_networks=ext_nets)
def _get_chunk_size(self, sp):
# NOTE(salv-orlando): Try to use __future__ for this routine only?
ratio = ((float(sp.total_size) / float(sp.chunk_size)) /
(float(self._sync_interval) / float(self._req_delay)))
new_size = max(1.0, ratio) * float(sp.chunk_size)
return int(new_size) + (new_size - int(new_size) > 0)
def _fetch_data(self, uri, cursor, page_size):
# If not cursor there is nothing to retrieve
if cursor:
if cursor == 'start':
cursor = None
# Chunk size tuning might, in some conditions, make it larger
# than 5,000, which is the maximum page size allowed by the NVP
# API. In this case the request should be split in multiple
# requests. This is not ideal, and therefore a log warning will
# be emitted.
num_requests = page_size / (nvplib.MAX_PAGE_SIZE + 1) + 1
if num_requests > 1:
LOG.warn(_("Requested page size is %(cur_chunk_size)d."
"It might be necessary to do %(num_requests)d "
"round-trips to NVP for fetching data. Please "
"tune sync parameters to ensure chunk size "
"is less than %(max_page_size)d"),
{'cur_chunk_size': page_size,
'num_requests': num_requests,
'max_page_size': nvplib.MAX_PAGE_SIZE})
# Only the first request might return the total size,
# subsequent requests will definetely not
results, cursor, total_size = nvplib.get_single_query_page(
uri, self._cluster, cursor,
min(page_size, nvplib.MAX_PAGE_SIZE))
for _req in range(0, num_requests - 1):
# If no cursor is returned break the cycle as there is no
# actual need to perform multiple requests (all fetched)
# This happens when the overall size of resources exceeds
# the maximum page size, but the number for each single
# resource type is below this threshold
if not cursor:
break
req_results, cursor = nvplib.get_single_query_page(
uri, self._cluster, cursor,
min(page_size, nvplib.MAX_PAGE_SIZE))[:2]
results.extend(req_results)
# reset cursor before returning if we queried just to
# know the number of entities
return results, cursor if page_size else 'start', total_size
return [], cursor, None
def _fetch_nvp_data_chunk(self, sp):
base_chunk_size = sp.chunk_size
chunk_size = base_chunk_size + sp.extra_chunk_size
LOG.info(_("Fetching up to %s resources "
"from NVP backend"), chunk_size)
fetched = ls_count = lr_count = lp_count = 0
lswitches = lrouters = lswitchports = []
if sp.ls_cursor or sp.ls_cursor == 'start':
(lswitches, sp.ls_cursor, ls_count) = self._fetch_data(
self.LS_URI, sp.ls_cursor, chunk_size)
fetched = len(lswitches)
if fetched < chunk_size and sp.lr_cursor or sp.lr_cursor == 'start':
(lrouters, sp.lr_cursor, lr_count) = self._fetch_data(
self.LR_URI, sp.lr_cursor, max(chunk_size - fetched, 0))
fetched += len(lrouters)
if fetched < chunk_size and sp.lp_cursor or sp.lp_cursor == 'start':
(lswitchports, sp.lp_cursor, lp_count) = self._fetch_data(
self.LP_URI, sp.lp_cursor, max(chunk_size - fetched, 0))
fetched += len(lswitchports)
if sp.current_chunk == 0:
# No cursors were provided. Then it must be possible to
# calculate the total amount of data to fetch
sp.total_size = ls_count + lr_count + lp_count
LOG.debug(_("Total data size: %d"), sp.total_size)
sp.chunk_size = self._get_chunk_size(sp)
# Calculate chunk size adjustment
sp.extra_chunk_size = sp.chunk_size - base_chunk_size
LOG.debug(_("Fetched %(num_lswitches)d logical switches, "
"%(num_lswitchports)d logical switch ports,"
"%(num_lrouters)d logical routers"),
{'num_lswitches': len(lswitches),
'num_lswitchports': len(lswitchports),
'num_lrouters': len(lrouters)})
return (lswitches, lrouters, lswitchports)
def _synchronize_state(self, sp):
# If the plugin has been destroyed, stop the LoopingCall
if not self._plugin:
raise loopingcall.LoopingCallDone
start = timeutils.utcnow()
# Reset page cursor variables if necessary
if sp.current_chunk == 0:
sp.ls_cursor = sp.lr_cursor = sp.lp_cursor = 'start'
LOG.info(_("Running state synchronization task. Chunk: %s"),
sp.current_chunk)
# Fetch chunk_size data from NVP
try:
(lswitches, lrouters, lswitchports) = (
self._fetch_nvp_data_chunk(sp))
except (NvpApiClient.RequestTimeout, NvpApiClient.NvpApiException):
sleep_interval = self._sync_backoff
# Cap max back off to 64 seconds
self._sync_backoff = min(self._sync_backoff * 2, 64)
LOG.exception(_("An error occured while communicating with "
"NVP backend. Will retry synchronization "
"in %d seconds"), sleep_interval)
return sleep_interval
LOG.debug(_("Time elapsed querying NVP: %s"),
timeutils.utcnow() - start)
if sp.total_size:
num_chunks = ((sp.total_size / sp.chunk_size) +
(sp.total_size % sp.chunk_size != 0))
else:
num_chunks = 1
LOG.debug(_("Number of chunks: %d"), num_chunks)
# Find objects which have changed on NVP side and need
# to be synchronized
(ls_uuids, lr_uuids, lp_uuids) = self._nvp_cache.process_updates(
lswitches, lrouters, lswitchports)
# Process removed objects only at the last chunk
scan_missing = (sp.current_chunk == num_chunks - 1 and
not sp.init_sync_performed)
if sp.current_chunk == num_chunks - 1:
self._nvp_cache.process_deletes()
ls_uuids = self._nvp_cache.get_lswitches(
changed_only=not scan_missing)
lr_uuids = self._nvp_cache.get_lrouters(
changed_only=not scan_missing)
lp_uuids = self._nvp_cache.get_lswitchports(
changed_only=not scan_missing)
LOG.debug(_("Time elapsed hashing data: %s"),
timeutils.utcnow() - start)
# Get an admin context
ctx = context.get_admin_context()
# Synchronize with database
with ctx.session.begin(subtransactions=True):
self._synchronize_lswitches(ctx, ls_uuids,
scan_missing=scan_missing)
self._synchronize_lrouters(ctx, lr_uuids,
scan_missing=scan_missing)
self._synchronize_lswitchports(ctx, lp_uuids,
scan_missing=scan_missing)
# Increase chunk counter
LOG.info(_("Synchronization for chunk %(chunk_num)d of "
"%(total_chunks)d performed"),
{'chunk_num': sp.current_chunk + 1,
'total_chunks': num_chunks})
sp.current_chunk = (sp.current_chunk + 1) % num_chunks
added_delay = 0
if sp.current_chunk == 0:
# Ensure init_sync_performed is True
if not sp.init_sync_performed:
sp.init_sync_performed = True
# Add additional random delay
added_delay = random.randint(0, self._max_rand_delay)
LOG.debug(_("Time elapsed at end of sync: %s"),
timeutils.utcnow() - start)
return self._sync_interval / num_chunks + added_delay
| {
"content_hash": "7891ddde5f31b56096a5c81df0e71e52",
"timestamp": "",
"source": "github",
"line_count": 587,
"max_line_length": 79,
"avg_line_length": 46.620102214650764,
"alnum_prop": 0.57564130673098,
"repo_name": "citrix-openstack-build/neutron",
"id": "dfbc79afa91d3f4e0bb3ad65e6a58e452c335856",
"size": "27993",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "neutron/plugins/nicira/common/sync.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "37307"
},
{
"name": "JavaScript",
"bytes": "67928"
},
{
"name": "Python",
"bytes": "6817315"
},
{
"name": "Shell",
"bytes": "8983"
},
{
"name": "XSLT",
"bytes": "50907"
}
],
"symlink_target": ""
} |
{% extends 'bs1/base/base.html' %}
{% block header %}
<title>containers detail</title>
{% endblock %}
{% block body %}
<button type="button" class="btn btn-success btn-lg" onclick='location.href="/containers/start/{{all.Config.Hostname}}/{{engine}}"'>
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>start
</button>
<button type="button" class="btn btn-info btn-lg" onclick='location.href="/containers/stop/{{all.Config.Hostname}}/{{engine}}"' >
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>stop
</button>
<button type="button" class="btn btn-primary btn-lg" onclick='location.href="/containers/restart/{{all.Config.Hostname}}/{{engine}}"'>
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>restart
</button>
<button type="button" class="btn btn-success btn-lg" onclick='location.href="{% url 'create' %}"'>
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>create
</button>
<button type="button" class="btn btn-danger btn-lg" onclick='location.href="/containers/destroy/{{all.Config.Hostname}}/{{engine}}"'>
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>destroy
</button>
{% if all%}
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>key</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<th> </th>
<th> Name </th>
<th> {{ all.Name|slice:"1:" }} </th>
</tr>
<th> </th>
<th> Hostname </th>
<th> {{ all.Config.Hostname }} </th>
</tr>
<th> </th>
<th> Image </th>
<th> {{ all.Config.Image }} </th>
</tr>
<th> </th>
<th> IP Address </th>
<th> {{ all.NetworkSettings.IPAddress }} </th>
</tr>
<th> </th>
<th> MacAddress </th>
<th> {{ all.NetworkSettings.MacAddress }} </th>
</tr>
<th> </th>
<th> Running </th>
<th> {{ all.State.Running }} </th>
</tr>
<th> </th>
<th> Ports </th>
<th> {{ all.NetworkSettings.Ports }} </th>
</tr>
<th> </th>
<th> start time </th>
<th> {{ all.State.StartedAt }} </th>
</tr>
</tbody>
</table>
{% endif %}
{% endblock %}
| {
"content_hash": "220b00a5f6c969dd015ea649d9dc90f6",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 134,
"avg_line_length": 28.066666666666666,
"alnum_prop": 0.5933491686460808,
"repo_name": "gregorianzhang/octopus",
"id": "9ccb16c968fd1dd83345ec0b8dfb46d2c047b352",
"size": "2105",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "templates/bs1/containers/detail.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "10595"
},
{
"name": "Python",
"bytes": "13662"
}
],
"symlink_target": ""
} |
#include <algorithm>
#include <vector>
using namespace std;
/*
Time complexity: O(n) [where n is the length of flips]
Space complexity: O(1)
*/
class Solution
{
public:
int numTimesAllBlue(vector<int> & flips)
{
int result=0;
int n=flips.size();
int minValue=-1;
int maxValue=-1;
//As we iterate through the flips vector, we will use minValue and maxValue to represent
//the inclusive range of indices that have been flipped from zeros to ones [minValue, maxValue]
for(int i=0;i<n;i++)
{
int flip=flips[i];
if(minValue==-1 and maxValue==-1)
{
minValue=flip;
maxValue=flip;
}
else
{
minValue=min(minValue, flip);
maxValue=max(maxValue, flip);
}
//If the range [minValue, maxValue] equals [1, i], then we know that the bits in the range [1, i] are prefix-aligned
if(minValue==1 and maxValue==i+1)
{
result+=1;
}
}
return result;
}
}; | {
"content_hash": "6b2ef250e6547d776a10f147d67e193f",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 132,
"avg_line_length": 27.41176470588235,
"alnum_prop": 0.42560801144492133,
"repo_name": "busebd12/InterviewPreparation",
"id": "45553a1e0327cfdeba041909e599b7b03092a2a3",
"size": "1398",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LeetCode/C++/General/Medium/NumberOfTimesBinaryStringIsPrefixAligned/solution.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "9011022"
},
{
"name": "C++",
"bytes": "14785379"
},
{
"name": "CMake",
"bytes": "10099860"
},
{
"name": "Java",
"bytes": "54365"
},
{
"name": "Makefile",
"bytes": "5154401"
},
{
"name": "TeX",
"bytes": "41241"
}
],
"symlink_target": ""
} |
Moodle - Sanity Checker
=======================
This plugin provides an interface to implement sanity checks on moodle.
Moodle version
--------------
\>= 2.3
Installation
------------
### go to the right directory
Before all, change your working directory to `YOUR_MOODLE_DIRROOT/local` where :
*YOUR_MOODLE_DIRROOT* represents the root directory of your moodle site.
### get the plugin
#### using git
Clone the plugin repository by running :
`git clone https://github.com/eviweb/moodle-local_sanitychecker.git sanitychecker`
#### using archive
Download the zip archive directly from github and uncompress under *sanitychecker* directory :
wget -c https://github.com/eviweb/moodle-local_sanitychecker/archive/master.zip
unzip master.zip && mv moodle-local_sanitychecker-master sanitychecker
### finalize the installation
Authenticate with an administrator account and go to the notifications page to
finish the install. This page is located under :
`http(s)://YOUR_MOODLE_SITE/admin/index.php` where :
*YOUR_MOODLE_SITE* is the domain of your moodle site.
How to use this feature
-----------------------
Once installed you will find a link under `Settings > Site administration` called
`Sanity checker` by clicking on it, you will be redirected to the plugin dashboard.
Its table lists all the available sanity checkers under four columns :
1. _Name :_ the implementation name
2. _Description :_ should describe what the checker is supposed to do
3. _Actions :_ here is displayed a dynamic link to run the actions to perform
> check : to run the tests
> resolve : in case a problem is found, apply the fix
4. _Information :_ displays contextual information about what is done
So choose which test you want to run and click on **Run test**.
If a problem is found the previous action link is renamed **Resolve issue**.
Click on it to apply the fix.
How create new sanity checker
-----------------------------
### implement the API
Create an implementation of the `SanityChecker`interface :
interface SanityChecker
{
/**
* get the sanity checker name
*
* @return string returns the name of this implementation
*/
public function getName();
/**
* get the description of what this sanity check does
*
* @return string returns the description of this implementation
*/
public function getDescription();
/**
* perform the test
*
* @return boolean returns true if the test succeeds, false if it fails
*/
public function doCheck();
/**
* get information on the problem detected
*
* @return string returns information related to the detected problem
* or an empty string if there is no issue
*/
public function getInformationOnIssue();
/**
* resolve the problem
*/
public function resolveIssue();
}
or extends the abstract `DatabaseSanityChecker` which is a class helper to perform
sanity checks on database records.
### register the service implementation
Add the class full name of your implementation on a new line in the
`./classes/META-INF/services/evidev.moodle.plugins.sanitychecker` file.
**For now, you add to take care about providing a way to load your class by your own
or to install it under the `./classes` directory.**
Each folder under the subtree of this directory, except `META-INF`, represents
a part of the class namespace.
To illustrate this, the `SanityChecker` interface is declared under the namespace
`\evidev\moodle\plugins` and is located at `./classes/evidev/moodle/plugins/SanityChecker.php`
Sanity Checker List
-------------------
Please refer to the [related wiki page](https://github.com/eviweb/moodle-local_sanitychecker/wiki)
| {
"content_hash": "66005d9ed9b389d28887e6de5a023c9b",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 102,
"avg_line_length": 37.648148148148145,
"alnum_prop": 0.6549434333497295,
"repo_name": "eviweb/moodle-local_sanitychecker",
"id": "4f3da4786ab0eeeb50d6da0afadeeddc0a37161a",
"size": "4066",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "40443"
}
],
"symlink_target": ""
} |
/* eslint-disable object-curly-spacing */
export virtualRootBuilder from './virtualRootBuilder';
| {
"content_hash": "d90246cef814e93369128c01d4529a40",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 54,
"avg_line_length": 48.5,
"alnum_prop": 0.7938144329896907,
"repo_name": "knyga/react-router-access",
"id": "f73fc3b0b9a2211fe62a74451511c55454907eee",
"size": "97",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "__mocks__/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "36382"
}
],
"symlink_target": ""
} |
/*
* testThinClientPdxTests.cpp
*
* Created on: Sep 30, 2011
* Author: npatel
*/
//#include "ThinClientPdxTests.hpp"
/*DUNIT_MAIN
{
//LOG("NIL:DUNIT_MAIN:PDXTests function called");
runPdxTests(true, false);
}
END_MAIN*/
#include <string>
#include "fw_dunit.hpp"
#include <ace/OS.h>
#include <ace/High_Res_Timer.h>
#include <geode/PdxInstance.hpp>
#include <geode/UserFunctionExecutionException.hpp>
#include <geode/FunctionService.hpp>
#define ROOT_NAME "testThinClientPdxTests"
#define ROOT_SCOPE DISTRIBUTED_ACK
#include "ThinClientHelper.hpp"
#include "testobject/PdxClassV1.hpp"
#include "testobject/PdxClassV2.hpp"
#include "testobject/VariousPdxTypes.hpp"
#include "testobject/InvalidPdxUsage.hpp"
#include "QueryStrings.hpp"
#include "QueryHelper.hpp"
#include <Utils.hpp>
#include <geode/Query.hpp>
#include <geode/QueryService.hpp>
#include "CachePerfStats.hpp"
#include <LocalRegion.hpp>
using namespace apache::geode::client;
using namespace test;
using namespace testData;
using namespace PdxTests;
#define CLIENT1 s1p1
#define CLIENT2 s1p2
#define CLIENT3 s2p2
#define LOCATOR s2p2
#define SERVER1 s2p1
bool isLocator = false;
bool isLocalServer = false;
const char* poolNames[] = {"Pool1", "Pool2", "Pool3"};
const char* locHostPort =
CacheHelper::getLocatorHostPort(isLocator, isLocalServer, 1);
bool isPoolConfig = false; // To track if pool case is running
// const char * qRegionNames[] = { "Portfolios", "Positions", "Portfolios2",
// "Portfolios3" };
static bool m_useWeakHashMap = false;
template <typename T1, typename T2>
bool genericValCompare(T1 value1, T2 value2) /*const*/
{
if (value1 != value2) return false;
return true;
}
void initClient(const bool isthinClient, bool isPdxIgnoreUnreadFields,
const std::shared_ptr<Properties>& configPtr = nullptr) {
LOGINFO("isPdxIgnoreUnreadFields = %d ", isPdxIgnoreUnreadFields);
if (cacheHelper == nullptr) {
cacheHelper = new CacheHelper(isthinClient, isPdxIgnoreUnreadFields, false,
configPtr, false);
}
ASSERT(cacheHelper, "Failed to create a CacheHelper client instance.");
}
//////////
void initClientN(const bool isthinClient, bool isPdxIgnoreUnreadFields,
bool isPdxReadSerialized = false,
const std::shared_ptr<Properties>& configPtr = nullptr) {
LOGINFO("isPdxIgnoreUnreadFields = %d ", isPdxIgnoreUnreadFields);
if (cacheHelper == nullptr) {
cacheHelper = new CacheHelper(isthinClient, isPdxIgnoreUnreadFields,
isPdxReadSerialized, configPtr, false);
}
ASSERT(cacheHelper, "Failed to create a CacheHelper client instance.");
}
void stepOneN(bool isPdxIgnoreUnreadFields = false,
bool isPdxReadSerialized = false,
std::shared_ptr<Properties> config = nullptr) {
try {
// serializationRegistry->addType(Position::createDeserializable);
// serializationRegistry->addType(Portfolio::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
// Create just one pool and attach all regions to that.
initClientN(true, isPdxIgnoreUnreadFields, isPdxReadSerialized, config);
isPoolConfig = true;
createPool(poolNames[0], locHostPort, nullptr, 0, true);
createRegionAndAttachPool("DistRegionAck", USE_ACK, poolNames[0],
false /*Caching disabled*/);
LOG("StepOne complete.");
}
DUNIT_TASK_DEFINITION(CLIENT1, StepOnePoolLoc1)
{
LOG("Starting Step One with Pool + Locator lists");
stepOneN(false, true, nullptr);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, StepTwoPoolLoc1)
{
LOG("Starting Step Two with Pool + Locator");
stepOneN(false, true, nullptr);
}
END_TASK_DEFINITION
///////////////
void initClient1WithClientName(
const bool isthinClient,
const std::shared_ptr<Properties>& configPtr = nullptr) {
if (cacheHelper == nullptr) {
auto config = configPtr;
if (config == nullptr) {
config = Properties::create();
}
config->insert("name", "Client-1");
cacheHelper = new CacheHelper(isthinClient, config);
}
ASSERT(cacheHelper, "Failed to create a CacheHelper client instance.");
}
void initClient2WithClientName(
const bool isthinClient,
const std::shared_ptr<Properties>& configPtr = nullptr) {
if (cacheHelper == nullptr) {
auto config = configPtr;
if (config == nullptr) {
config = Properties::create();
}
config->insert("name", "Client-2");
cacheHelper = new CacheHelper(isthinClient, config);
}
ASSERT(cacheHelper, "Failed to create a CacheHelper client instance.");
}
void stepOneForClient1(bool isPdxIgnoreUnreadFields = false) {
// Create just one pool and attach all regions to that.
initClient1WithClientName(true);
isPoolConfig = true;
createPool(poolNames[0], locHostPort, nullptr, 0, true);
createRegionAndAttachPool("DistRegionAck", USE_ACK, poolNames[0],
false /*Caching disabled*/);
LOG("StepOne complete.");
}
void stepOneForClient2(bool isPdxIgnoreUnreadFields = false) {
// Create just one pool and attach all regions to that.
initClient2WithClientName(true);
isPoolConfig = true;
createPool(poolNames[0], locHostPort, nullptr, 0, true);
createRegionAndAttachPool("DistRegionAck", USE_ACK, poolNames[0],
false /*Caching disabled*/);
LOG("StepOne complete.");
}
void stepOne(bool isPdxIgnoreUnreadFields = false,
std::shared_ptr<Properties> config = nullptr) {
try {
// serializationRegistry->addType(Position::createDeserializable);
// serializationRegistry->addType(Portfolio::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
// Create just one pool and attach all regions to that.
initClient(true, isPdxIgnoreUnreadFields, config);
isPoolConfig = true;
createPool(poolNames[0], locHostPort, nullptr, 0, true);
createRegionAndAttachPool("DistRegionAck", USE_ACK, poolNames[0],
false /*Caching disabled*/);
LOG("StepOne complete.");
}
void initClient1(bool isPdxIgnoreUnreadFields = false) {
// Create just one pool and attach all regions to that.
initClient(true, isPdxIgnoreUnreadFields);
isPoolConfig = true;
createPool(poolNames[0], locHostPort, nullptr, 0, false);
createRegionAndAttachPool("DistRegionAck", USE_ACK, poolNames[0],
true /*Caching enabled*/);
LOG("StepOne complete.");
}
void initClient2(bool isPdxIgnoreUnreadFields = false) {
// Create just one pool and attach all regions to that.
initClient(true, isPdxIgnoreUnreadFields);
isPoolConfig = true;
createPool(poolNames[0], locHostPort, nullptr, 0,
true /*ClientNotification enabled*/);
createRegionAndAttachPool("DistRegionAck", USE_ACK, poolNames[0],
true /*Caching enabled*/);
LOG("StepOne complete.");
}
void initClient3(bool isPdxIgnoreUnreadFields = false) {
// Create just one pool and attach all regions to that.
initClient(true, isPdxIgnoreUnreadFields);
isPoolConfig = true;
createPool(poolNames[0], locHostPort, nullptr, 0,
true /*ClientNotification enabled*/);
createRegionAndAttachPool("DistRegionAck", USE_ACK, poolNames[0],
true /*Caching enabled*/);
LOG("StepOne complete.");
}
DUNIT_TASK_DEFINITION(SERVER1, StartLocator)
{
// starting locator 1 2
if (isLocator) {
CacheHelper::initLocator(1);
}
LOG("Locator started");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, StepOnePoolLoc_PDX)
{
LOG("Starting Step One with Pool + Locator lists");
stepOne(true);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, StepOnePoolLoc)
{
LOG("Starting Step One with Pool + Locator lists");
stepOne();
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, StepOnePoolLocSysConfig)
{
LOG("Starting Step One with Pool + Locator lists");
auto config = Properties::create();
config->insert("on-client-disconnect-clear-pdxType-Ids", "true");
stepOne(false, config);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, StepTwoPoolLocSysConfig)
{
LOG("Starting Step One with Pool + Locator lists");
auto config = Properties::create();
config->insert("on-client-disconnect-clear-pdxType-Ids", "true");
stepOne(false, config);
}
END_TASK_DEFINITION
// StepOnePoolLoc_PdxMetadataTest
DUNIT_TASK_DEFINITION(CLIENT1, StepOnePoolLoc_PdxMetadataTest)
{
LOG("Starting Step One with Pool + Locator lists");
initClient1();
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(SERVER1, CreateServer)
{
LOG("Starting SERVER1...");
if (isLocalServer) CacheHelper::initServer(1, "cacheserverPdx.xml");
LOG("SERVER1 started");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(SERVER1, CreateServerWithLocator)
{
LOG("Starting SERVER1...");
if (isLocalServer) {
CacheHelper::initServer(1, "cacheserverPdx.xml", locHostPort);
}
LOG("SERVER1 started");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(SERVER1, CreateServer_PdxMetadataTest)
{
LOG("Starting SERVER1...");
if (isLocalServer) CacheHelper::initServer(1, "cacheserverPdx2.xml");
LOG("SERVER1 started");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(SERVER1, CreateServerWithLocator_PdxMetadataTest)
{
LOG("Starting SERVER1...");
if (isLocalServer) {
CacheHelper::initServer(1, "cacheserverPdx2.xml", locHostPort);
}
LOG("SERVER1 started");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(SERVER1, CreateServerWithLocator1)
{
LOG("Starting SERVER1...");
if (isLocalServer) {
CacheHelper::initServer(1, "cacheserver.xml", locHostPort);
}
LOG("SERVER1 started");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(SERVER1, CreateServerWithLocator2)
{
LOG("Starting SERVER1...");
if (isLocalServer) {
CacheHelper::initServer(1, "cacheserverForPdx.xml", locHostPort);
}
LOG("SERVER1 started");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, StepOnePoolLocBug866)
{
LOG("Starting Step One with Pool + Locator lists");
stepOneForClient1();
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, StepTwoPoolLocBug866)
{
LOG("Starting Step Two with Pool + Locator");
stepOneForClient2();
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, StepTwoPoolLoc)
{
LOG("Starting Step Two with Pool + Locator");
stepOne();
}
END_TASK_DEFINITION
// StepTwoPoolLoc_PdxMetadataTest
DUNIT_TASK_DEFINITION(CLIENT2, StepTwoPoolLoc_PdxMetadataTest)
{
LOG("Starting Step Two with Pool + Locator");
initClient2();
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT3, StepThreePoolLoc_PdxMetadataTest)
{
LOG("Starting Step Two with Pool + Locator");
initClient3();
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, StepTwoPoolLoc_PDX)
{
LOG("Starting Step Two with Pool + Locator");
stepOne(true);
}
END_TASK_DEFINITION
void checkPdxInstanceToStringAtServer(std::shared_ptr<Region> regionPtr) {
auto keyport = CacheableKey::create("success");
auto boolPtr =
std::dynamic_pointer_cast<CacheableBoolean>(regionPtr->get(keyport));
bool val = boolPtr->value();
// TODO::Enable asser and disable LOGINFO
ASSERT(val == true, "checkPdxInstanceToStringAtServer: Val should be true");
LOGINFO("NIL::checkPdxInstanceToStringAtServer:139: val = %d", val);
}
// testPdxWriterAPIsWithInvalidArgs
DUNIT_TASK_DEFINITION(CLIENT1, testPdxWriterAPIsWithInvalidArgs)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(InvalidPdxUsage::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(
AddressWithInvalidAPIUsage::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
int expectedExceptionCount = 0;
// Put operation
auto keyport = CacheableKey::create(1);
auto pdxobj = std::make_shared<PdxTests::InvalidPdxUsage>();
regPtr0->put(keyport, pdxobj);
// Check the exception count:: expected is 41.
expectedExceptionCount =
(std::dynamic_pointer_cast<PdxTests::InvalidPdxUsage>(pdxobj))
->gettoDataExceptionCount();
// LOGINFO("TASK::testPdxWriterAPIsWithInvalidArgs:: toData ExceptionCount
// ::
// %d ", expectedExceptionCount);
ASSERT(expectedExceptionCount == 41,
"Task testPdxWriterAPIsWithInvalidArgs:Did not get expected "
"toDataExceptionCount");
// Get Operation and check fromDataExceptionCount, Expected is 41.
auto obj2 = std::dynamic_pointer_cast<PdxTests::InvalidPdxUsage>(
regPtr0->get(keyport));
// LOGINFO("TASK::testPdxWriterAPIsWithInvalidArgs:: fromData ExceptionCOunt
// :: %d ", obj2->getfromDataExceptionCount());
expectedExceptionCount = obj2->getfromDataExceptionCount();
ASSERT(expectedExceptionCount == 41,
"Task testPdxWriterAPIsWithInvalidArgs:Did not get expected "
"fromDataExceptionCount");
LOGINFO("TASK::testPdxWriterAPIsWithInvalidArgs completed Successfully");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, testPdxReaderAPIsWithInvalidArgs)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(InvalidPdxUsage::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(
AddressWithInvalidAPIUsage::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
int expectedExceptionCount = 0;
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
// Get Operation. Check fromDataExceptionCount. Expected is 41.
auto keyport1 = CacheableKey::create(1);
auto obj1 = std::dynamic_pointer_cast<PdxTests::InvalidPdxUsage>(
regPtr0->get(keyport1));
// Check the exception count:: expected is 41.
// LOGINFO("TASK::testPdxReaderAPIsWithInvalidArgs:: fromDataExceptionCount
// ::
// %d ", obj1->getfromDataExceptionCount());
expectedExceptionCount = obj1->getfromDataExceptionCount();
ASSERT(expectedExceptionCount == 41,
"Task testPdxReaderAPIsWithInvalidArgs:Did not get expected "
"fromDataExceptionCount");
LOGINFO("TASK::testPdxReaderAPIsWithInvalidArgs completed Successfully");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, testPutWithMultilevelInheritance)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(PdxTests::Child::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
int expectedExceptionCount ATTR_UNUSED = 0;
// Put operation
auto keyport = CacheableKey::create(1);
auto pdxobj = std::make_shared<PdxTests::Child>();
regPtr0->put(keyport, pdxobj);
LOGINFO("TASK::testPutWithMultilevelInheritance:: Put successful");
// Get Operation and check fromDataExceptionCount, Expected is 41.
auto obj2 =
std::dynamic_pointer_cast<PdxTests::Child>(regPtr0->get(keyport));
// LOGINFO("Task: testPutWithMultilevelInheritance: got members :: %d %d %d
// %d
// %d %d ", obj2->getMember_a(), obj2->getMember_b(), obj2->getMember_c(),
// obj2->getMember_d(), obj2->getMember_e(), obj2->getMember_f());
bool isEqual =
(std::dynamic_pointer_cast<PdxTests::Child>(pdxobj))->equals(obj2);
LOGINFO("testPutWithMultilevelInheritance:.. isEqual = %d", isEqual);
ASSERT(isEqual == true, "Objects of type class Child should be equal");
LOGINFO("TASK::testPutWithMultilevelInheritance:: Get successful");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, testGetWithMultilevelInheritance)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(PdxTests::Child::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport1 = CacheableKey::create(1);
auto obj1 =
std::dynamic_pointer_cast<PdxTests::Child>(regPtr0->get(keyport1));
auto pdxobj = std::make_shared<PdxTests::Child>();
bool isEqual =
(std::dynamic_pointer_cast<PdxTests::Child>(pdxobj))->equals(obj1);
LOGINFO("testPutWithMultilevelInheritance:.. isEqual = %d", isEqual);
ASSERT(isEqual == true, "Objects of type class Child should be equal");
// LOGINFO("Task: testGetWithMultilevelInheritance: got members :: %d %d %d
// %d
// %d %d ", obj1->getMember_a(), obj1->getMember_b(), obj1->getMember_c(),
// obj1->getMember_d(), obj1->getMember_e(), obj1->getMember_f());
LOGINFO(
"TASK::testGetWithMultilevelInheritance GET completed Successfully");
}
END_TASK_DEFINITION
// Added for the LinkedList testcase
DUNIT_TASK_DEFINITION(CLIENT1, JavaPutGet1)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto valPtr = CacheableInt32::create(123);
regPtr0->put(keyport, valPtr);
auto getVal =
std::dynamic_pointer_cast<CacheableInt32>(regPtr0->get(keyport));
auto boolPtr =
std::dynamic_pointer_cast<CacheableBoolean>(regPtr0->get("success"));
bool isEqual = boolPtr.get()->value();
ASSERT(isEqual == true,
"Task JavaPutGet:Objects of type PdxType should be equal");
LOGINFO("Task:JavaPutGet PDX-ON read-serialized = %d",
cacheHelper->getCache()->getPdxReadSerialized());
auto jsonDoc =
std::dynamic_pointer_cast<PdxInstance>(regPtr0->get("jsondoc1"));
auto toString = jsonDoc->toString();
LOGINFO("Task:JavaPutGet: Result = %s ", toString->asChar());
/*
int16_t age = 0;
jsonDoc->getField("age", age);
char* stringVal = nullptr;
jsonDoc->getField("firstName", &stringVal);
char* stringVal1 = nullptr;
jsonDoc->getField("lastName", &stringVal1);
*/
auto object2 = jsonDoc->getCacheableField("kids");
auto listPtr = std::dynamic_pointer_cast<CacheableLinkedList>(object2);
LOGINFO("Task:JavaPutGet: list size = %d", listPtr->size());
auto m_linkedlist = CacheableLinkedList::create();
m_linkedlist->push_back(CacheableString::create("Manan"));
m_linkedlist->push_back(CacheableString::create("Nishka"));
ASSERT(genericValCompare(m_linkedlist->size(), listPtr->size()) == true,
"LinkedList size should be equal");
for (int j = 0; j < m_linkedlist->size(); j++) {
genericValCompare(m_linkedlist->at(j), listPtr->at(j));
}
LOGINFO("Task:JavaPutGet Tese-cases completed successfully!");
}
END_TASK_DEFINITION
// END
DUNIT_TASK_DEFINITION(CLIENT1, JavaPutGet)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxType::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(Address::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto pdxobj = std::make_shared<PdxTests::PdxType>();
regPtr0->put(keyport, pdxobj);
auto obj2 =
std::dynamic_pointer_cast<PdxTests::PdxType>(regPtr0->get(keyport));
auto boolPtr =
std::dynamic_pointer_cast<CacheableBoolean>(regPtr0->get("success"));
bool isEqual = boolPtr.get()->value();
LOGDEBUG("Task:JavaPutGet: isEqual = %d", isEqual);
ASSERT(isEqual == true,
"Task JavaPutGet:Objects of type PdxType should be equal");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, JavaGet)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxType::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(Address::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
LOGDEBUG("JavaGet-1 Line_309");
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport1 = CacheableKey::create(1);
auto pdxobj = std::make_shared<PdxTests::PdxType>();
LOGDEBUG("JavaGet-2 Line_314");
auto obj1 =
std::dynamic_pointer_cast<PdxTests::PdxType>(regPtr0->get(keyport1));
LOGDEBUG("JavaGet-3 Line_316");
auto keyport2 = CacheableKey::create("putFromjava");
LOGDEBUG("JavaGet-4 Line_316");
auto obj2 =
std::dynamic_pointer_cast<PdxTests::PdxType>(regPtr0->get(keyport2));
LOGDEBUG("JavaGet-5 Line_320");
}
END_TASK_DEFINITION
/***************************************************************/
DUNIT_TASK_DEFINITION(CLIENT2, putAtVersionTwoR21)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypesR2V2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto np = std::make_shared<PdxTypesR2V2>();
regPtr0->put(keyport, np);
auto pRet = std::dynamic_pointer_cast<PdxTypesR2V2>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("putAtVersionTwoR21:.. isEqual = %d", isEqual);
ASSERT(
isEqual == true,
"Objects of type PdxTypesR2V2 should be equal at putAtVersionTwoR21");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, getPutAtVersionOneR22)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypesV1R2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto np = std::make_shared<PdxTypesV1R2>();
auto pRet = std::dynamic_pointer_cast<PdxTypesV1R2>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("getPutAtVersionOneR22:.. isEqual = %d", isEqual);
ASSERT(isEqual == true,
"Objects of type PdxTypesV1R2 should be equal at "
"getPutAtVersionOneR22");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, getPutAtVersionTwoR23)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto np = std::make_shared<PdxTypesR2V2>();
auto pRet = std::dynamic_pointer_cast<PdxTypesR2V2>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("getPutAtVersionTwoR23:.. isEqual = %d", isEqual);
ASSERT(isEqual == true,
"Objects of type PdxTypesR2V2 should be equal at "
"getPutAtVersionTwoR23");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, getPutAtVersionOneR24)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto np = std::make_shared<PdxTypesV1R2>();
auto pRet = std::dynamic_pointer_cast<PdxTypesV1R2>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("getPutAtVersionOneR24:.. isEqual = %d", isEqual);
ASSERT(isEqual == true,
"Objects of type PdxTypesV1R2 should be equal at "
"getPutAtVersionOneR24");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, putAtVersionOne31)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxType3V1::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto np = std::make_shared<PdxType3V1>();
regPtr0->put(keyport, np);
auto pRet = std::dynamic_pointer_cast<PdxType3V1>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("Task:putAtVersionOne31: isEqual = %d", isEqual);
ASSERT(isEqual == true,
"Objects of type PdxType3V1 should be equal at putAtVersionOne31");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, getPutAtVersionTwo32)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypes3V2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxTypes3V2>();
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxTypes3V2>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("Task:getPutAtVersionTwo32.. isEqual = %d", isEqual);
ASSERT(
isEqual == true,
"Objects of type PdxTypes3V2 should be equal at getPutAtVersionTwo32");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, getPutAtVersionOne33)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto np = std::make_shared<PdxType3V1>();
auto pRet = std::dynamic_pointer_cast<PdxType3V1>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("getPutAtVersionOne33:.. isEqual = %d", isEqual);
ASSERT(
isEqual == true,
"Objects of type PdxType3V1 should be equal at getPutAtVersionOne33");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, getPutAtVersionTwo34)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxTypes3V2>();
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxTypes3V2>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("Task:getPutAtVersionTwo34: isEqual = %d", isEqual);
ASSERT(
isEqual == true,
"Objects of type PdxType3V1 should be equal at getPutAtVersionTwo34");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, putAtVersionOne21)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxType2V1::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto np = std::make_shared<PdxType2V1>();
regPtr0->put(keyport, np);
auto pRet = std::dynamic_pointer_cast<PdxType2V1>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("Task:putAtVersionOne21:.. isEqual = %d", isEqual);
ASSERT(isEqual == true,
"Objects of type PdxType2V1 should be equal at putAtVersionOne21");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, getPutAtVersionTwo22)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypes2V2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxTypes2V2>();
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxTypes2V2>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("Task:getPutAtVersionTwo22.. isEqual = %d", isEqual);
ASSERT(
isEqual == true,
"Objects of type PdxTypes2V2 should be equal at getPutAtVersionTwo22");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, getPutAtVersionOne23)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxType2V1>();
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxType2V1>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("Task:getPutAtVersionOne23: isEqual = %d", isEqual);
ASSERT(
isEqual == true,
"Objects of type PdxType2V1 should be equal at getPutAtVersionOne23");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, getPutAtVersionTwo24)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxTypes2V2>();
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxTypes2V2>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("Task:getPutAtVersionTwo24.. isEqual = %d", isEqual);
ASSERT(
isEqual == true,
"Objects of type PdxTypes2V2 should be equal at getPutAtVersionTwo24");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, putAtVersionOne11)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxType1V1::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto np = std::make_shared<PdxTests::PdxType1V1>();
regPtr0->put(keyport, np);
auto pRet =
std::dynamic_pointer_cast<PdxTests::PdxType1V1>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("NIL:putAtVersionOne11:.. isEqual = %d", isEqual);
ASSERT(isEqual == true,
"Objects of type PdxType1V1 should be equal at putAtVersionOne11 "
"Line_170");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, putAtVersionTwo1)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypesR1V2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
PdxTests::PdxTypesR1V2::reset(false);
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto np = std::make_shared<PdxTypesR1V2>();
regPtr0->put(keyport, np);
auto pRet = std::dynamic_pointer_cast<PdxTypesR1V2>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("NIL:putAtVersionTwo1:.. isEqual = %d", isEqual);
ASSERT(isEqual == true,
"Objects of type PdxTypesR1V2 should be equal at putAtVersionTwo1");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, getPutAtVersionOne2)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypesV1R1::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxTypesV1R1>();
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxTypesV1R1>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("NIL:getPutAtVersionOne2:.. isEqual = %d", isEqual);
ASSERT(
isEqual == true,
"Objects of type PdxTypesV1R1 should be equal at getPutAtVersionOne2");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, getPutAtVersionTwo3)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxTypesR1V2>();
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxTypesR1V2>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("NIL:getPutAtVersionTwo3.. isEqual = %d", isEqual);
ASSERT(
isEqual == true,
"Objects of type PdxTypesR1V2 should be equal at getPutAtVersionTwo3");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, getPutAtVersionOne4)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxTypesV1R1>();
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxTypesV1R1>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("getPutAtVersionOne4: isEqual = %d", isEqual);
ASSERT(
isEqual == true,
"Objects of type PdxTypesV1R1 should be equal at getPutAtVersionOne4");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, getPutAtVersionTwo5)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxTypesR1V2>();
// GET
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxTypesR1V2>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("Task:getPutAtVersionTwo5.. isEqual = %d", isEqual);
ASSERT(
isEqual == true,
"Objects of type PdxTypesR1V2 should be equal at getPutAtVersionTwo5");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, getPutAtVersionOne6)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxTypesV1R1>();
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxTypesV1R1>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("Task getPutAtVersionOne6:.. isEqual = %d", isEqual);
ASSERT(
isEqual == true,
"Objects of type PdxTypesV1R1 should be equal at getPutAtVersionOne6");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, putV2PdxUI)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypesIgnoreUnreadFieldsV2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
// PdxTests::PdxTypesIgnoreUnreadFieldsV2::reset(false);
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxTypesIgnoreUnreadFieldsV2>();
auto keyport = CacheableKey::create(1);
regPtr0->put(keyport, np);
auto pRet = std::dynamic_pointer_cast<PdxTypesIgnoreUnreadFieldsV2>(
regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("NIL:putV2PdxUI:.. isEqual = %d", isEqual);
ASSERT(isEqual == true,
"Objects of type PdxTypesIgnoreUnreadFieldsV2 should be equal at "
"putV2PdxUI ");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, putV1PdxUI)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypesIgnoreUnreadFieldsV1::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
// PdxTests::PdxTypesIgnoreUnreadFieldsV1::reset(false);
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxTypesIgnoreUnreadFieldsV1>(
regPtr0->get(keyport));
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, getV2PdxUI)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxTypesIgnoreUnreadFieldsV2>();
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxTypesIgnoreUnreadFieldsV2>(
regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("Task:getV2PdxUI:.. isEqual = %d", isEqual);
ASSERT(isEqual == true,
"Objects of type PdxTypesIgnoreUnreadFieldsV2 should be equal at "
"getV2PdxUI ");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, getPutAtVersionTwo12)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypes1V2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxTypes1V2>();
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxTypes1V2>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("NIL:getPutAtVersionTwo12:.. isEqual = %d", isEqual);
ASSERT(isEqual == true,
"Objects of type PdxType1V2 should be equal at getPutAtVersionTwo12 "
"Line_197");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, getPutAtVersionOne13)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxType1V1>();
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxType1V1>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("NIL:getPutAtVersionOne13:221.. isEqual = %d", isEqual);
ASSERT(isEqual == true,
"Objects of type PdxType1V2 should be equal at getPutAtVersionOne13 "
"Line_215");
LOGDEBUG("NIL:getPutAtVersionOne13: PUT remote object -1");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, getPutAtVersionTwo14)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxTypes1V2>();
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxTypes1V2>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("NIL:getPutAtVersionTwo14:241.. isEqual = %d", isEqual);
ASSERT(
isEqual == true,
"Objects of type PdxTypes1V2 should be equal at getPutAtVersionTwo14 "
"Line_242");
regPtr0->put(keyport, pRet);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, getPutAtVersionOne15)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxType1V1>();
// GET
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxType1V1>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("NIL:getPutAtVersionOne15:784.. isEqual = %d", isEqual);
ASSERT(isEqual == true,
"Objects of type PdxType1V2 should be equal at getPutAtVersionOne15 "
"Line_272");
regPtr0->put(keyport, pRet);
auto testNumberOfPreservedData =
TestUtils::testNumberOfPreservedData(*CacheRegionHelper::getCacheImpl(
CacheHelper::getHelper().getCache().get()));
LOGDEBUG(
"NIL:getPutAtVersionOne15 m_useWeakHashMap = %d and "
"TestUtils::testNumberOfPreservedData() = %d",
m_useWeakHashMap, testNumberOfPreservedData);
if (m_useWeakHashMap == false) {
ASSERT(testNumberOfPreservedData == 0,
"testNumberOfPreservedData should be zero at Line_288");
} else {
ASSERT(
testNumberOfPreservedData > 0,
"testNumberOfPreservedData should be Greater than zero at Line_292");
}
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, getPutAtVersionTwo16)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxTypes1V2>();
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxTypes1V2>(regPtr0->get(keyport));
bool isEqual = np->equals(pRet);
LOGDEBUG("NIL:getPutAtVersionTwo14:.. isEqual = %d", isEqual);
ASSERT(
isEqual == true,
"Objects of type PdxTypes1V2 should be equal at getPutAtVersionTwo14");
regPtr0->put(keyport, pRet);
auto testNumberOfPreservedData =
TestUtils::testNumberOfPreservedData(*CacheRegionHelper::getCacheImpl(
CacheHelper::getHelper().getCache().get()));
if (m_useWeakHashMap == false) {
ASSERT(testNumberOfPreservedData == 0,
"getPutAtVersionTwo16:testNumberOfPreservedData should be zero");
} else {
// it has extra fields, so no need to preserve data
ASSERT(testNumberOfPreservedData == 0,
"getPutAtVersionTwo16:testNumberOfPreservedData should be zero");
}
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, Puts2)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypes1::createDeserializable);
serializationRegistry->addPdxType(
PdxTests::PdxTypes2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto pdxobj = std::make_shared<PdxTests::PdxTypes1>();
regPtr0->put(keyport, pdxobj);
auto keyport2 = CacheableKey::create(2);
auto pdxobj2 = std::make_shared<PdxTests::PdxTypes2>();
regPtr0->put(keyport2, pdxobj2);
// ASSERT(lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializationBytes()
// ==
// lregPtr->getCacheImpl()->getCachePerfStats().getPdxDeSerializationBytes(),
//"Total pdxDeserializationBytes should be equal to Total
// pdxSerializationsBytes.");
LOG("Stepone two puts complete.\n");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, forCleanup)
{
LOGINFO("Do put to clean the pdxtype registry");
try {
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto pdxobj = std::make_shared<PdxTests::PdxTypes1>();
regPtr0->put(keyport, pdxobj);
} catch (...) {
// ignore
}
LOGINFO("Wake up");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, Puts22)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto pdxobj = std::make_shared<PdxTests::PdxTypes1>();
regPtr0->put(keyport, pdxobj);
auto keyport2 = CacheableKey::create(2);
auto pdxobj2 = std::make_shared<PdxTests::PdxTypes2>();
regPtr0->put(keyport2, pdxobj2);
// ASSERT(lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializationBytes()
// ==
// lregPtr->getCacheImpl()->getCachePerfStats().getPdxDeSerializationBytes(),
//"Total pdxDeserializationBytes should be equal to Total
// pdxSerializationsBytes.");
LOG("Puts22 complete.\n");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, Get2)
{
try {
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
serializationRegistry->addPdxType(
PdxTests::PdxTypes1::createDeserializable);
serializationRegistry->addPdxType(
PdxTests::PdxTypes2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(2);
auto obj2 =
std::dynamic_pointer_cast<PdxTests::PdxTypes2>(regPtr0->get(keyport));
LOG("Get2 complete.\n");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, PutAndVerifyPdxInGet)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxType::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(Address::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto pdxobj = std::make_shared<PdxTests::PdxType>();
regPtr0->put(keyport, pdxobj);
auto obj2 =
std::dynamic_pointer_cast<PdxTests::PdxType>(regPtr0->get(keyport));
checkPdxInstanceToStringAtServer(regPtr0);
ASSERT(cacheHelper->getCache()->getPdxReadSerialized() == false,
"Pdx read serialized property should be false.");
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO(
"PdxDeSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be equal to Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be equal to Total "
"pdxSerializationsBytes.");
LOG("StepThree complete.\n");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, PutAndVerifyNestedPdxInGet)
{
LOG("PutAndVerifyNestedPdxInGet started.");
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(NestedPdx::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypes1::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypes2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto p1 = std::make_shared<NestedPdx>();
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
regPtr0->put(keyport, p1);
auto obj2 = std::dynamic_pointer_cast<NestedPdx>(regPtr0->get(keyport));
ASSERT(obj2->equals(p1) == true, "Nested pdx objects should be equal");
LOG("PutAndVerifyNestedPdxInGet complete.");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, PutMixedVersionNestedPdx)
{
LOG("PutMixedVersionNestedPdx started.");
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
MixedVersionNestedPdx::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypes1::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypes2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
LOG("auto p1 = std::make_shared<MixedVersionNestedPdx>(); ");
auto p1 = std::make_shared<MixedVersionNestedPdx>();
auto p2 = std::make_shared<MixedVersionNestedPdx>();
auto p3 = std::make_shared<MixedVersionNestedPdx>();
LOG("RegionPtr regPtr0 = getHelper()->getRegion(\"DistRegionAck\");");
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
LOG("std::shared_ptr<CacheableKey> keyport1 = CacheableKey::create(1);");
auto keyport1 = CacheableKey::create(1);
auto keyport2 = CacheableKey::create(2);
auto keyport3 = CacheableKey::create(3);
LOG("regPtr0->put(keyport1, p1 );");
regPtr0->put(keyport1, p1);
LOG("regPtr0->put(keyport2, p2 );");
regPtr0->put(keyport2, p2);
LOG("regPtr0->put(keyport3, p3 );");
regPtr0->put(keyport3, p3);
LOG("PutMixedVersionNestedPdx complete.");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, PutAndVerifyPdxInGFSInGet)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addType(
PdxInsideIGeodeSerializable::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(NestedPdx::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes1::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes3::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes4::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes5::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes6::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes7::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes8::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto np = std::make_shared<PdxInsideIGeodeSerializable>();
auto keyport = CacheableKey::create(1);
regPtr0->put(keyport, np);
// GET
auto pRet = std::dynamic_pointer_cast<PdxInsideIGeodeSerializable>(
regPtr0->get(keyport));
ASSERT(
pRet->equals(np) == true,
"TASK PutAndVerifyPdxInIGFSInGet: PdxInsideIGeodeSerializable objects "
"should be equal");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, VerifyPdxInGFSGetOnly)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addType(
PdxInsideIGeodeSerializable::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(NestedPdx::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes1::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes3::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes4::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes5::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes6::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes7::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes8::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto orig = std::make_shared<PdxInsideIGeodeSerializable>();
// GET
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxInsideIGeodeSerializable>(
regPtr0->get(keyport));
ASSERT(pRet->equals(orig) == true,
"TASK:VerifyPdxInIGFSGetOnly, PdxInsideIGeodeSerializable objects "
"should "
"be equal");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, VerifyMixedVersionNestedGetOnly)
{
LOG("VerifyMixedVersionNestedGetOnly started.");
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
MixedVersionNestedPdx::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypes1::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypes2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto p1 = std::make_shared<MixedVersionNestedPdx>();
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport1 = CacheableKey::create(1);
auto keyport2 = CacheableKey::create(2);
auto keyport3 = CacheableKey::create(3);
auto obj1 = std::dynamic_pointer_cast<MixedVersionNestedPdx>(
regPtr0->get(keyport1));
auto obj2 = std::dynamic_pointer_cast<MixedVersionNestedPdx>(
regPtr0->get(keyport2));
auto obj3 = std::dynamic_pointer_cast<MixedVersionNestedPdx>(
regPtr0->get(keyport3));
ASSERT(obj1->equals(p1) == true, "Nested pdx objects should be equal");
LOG("VerifyMixedVersionNestedGetOnly complete.");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, VerifyNestedGetOnly)
{
LOG("VerifyNestedGetOnly started.");
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(NestedPdx::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypes1::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypes2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto p1 = std::make_shared<NestedPdx>();
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto obj2 = std::dynamic_pointer_cast<NestedPdx>(regPtr0->get(keyport));
ASSERT(obj2->equals(p1) == true, "Nested pdx objects should be equal");
LOG("VerifyNestedGetOnly complete.");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, VerifyGetOnly)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxType::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(Address::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto obj2 =
std::dynamic_pointer_cast<PdxTests::PdxType>(regPtr0->get(keyport));
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO(
"PdxDeSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be less than Total "
"pdxSerializations.");
ASSERT(
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() < lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be less than Total "
"pdxSerializationsBytes.");
LOG("StepFour complete.\n");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, PutAndVerifyVariousPdxTypes)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(PdxTypes1::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes3::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes4::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes5::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes6::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes7::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes8::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes9::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes10::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
// TODO
// serializationRegistry->addPdxType(PdxTests.PortfolioPdx.CreateDeserializable);
// serializationRegistry->addPdxType(PdxTests.PositionPdx.CreateDeserializable);
// Region region0 = CacheHelper.GetVerifyRegion<object,
// object>(m_regionNames[0]);
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
bool flag = false;
{
auto p1 = std::make_shared<PdxTypes1>();
auto keyport = CacheableKey::create(11);
regPtr0->put(keyport, p1);
auto pRet = std::dynamic_pointer_cast<PdxTypes1>(regPtr0->get(keyport));
flag = p1->equals(pRet);
LOGDEBUG("PutAndVerifyVariousPdxTypes:.. flag = %d", flag);
ASSERT(flag == true, "Objects of type PdxTypes1 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be equal to Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be equal to Total "
"pdxSerializationsBytes.");
}
{
auto p2 = std::make_shared<PdxTypes2>();
auto keyport2 = CacheableKey::create(12);
regPtr0->put(keyport2, p2);
auto pRet2 = std::dynamic_pointer_cast<PdxTypes2>(regPtr0->get(keyport2));
flag = p2->equals(pRet2);
LOGDEBUG("PutAndVerifyVariousPdxTypes:.. flag = %d", flag);
ASSERT(flag == true, "Objects of type PdxTypes2 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be equal to Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be equal to Total "
"pdxSerializationsBytes.");
}
{
auto p3 = std::make_shared<PdxTypes3>();
auto keyport3 = CacheableKey::create(13);
regPtr0->put(keyport3, p3);
auto pRet3 = std::dynamic_pointer_cast<PdxTypes3>(regPtr0->get(keyport3));
flag = p3->equals(pRet3);
LOGDEBUG("PutAndVerifyVariousPdxTypes:.. flag = %d", flag);
ASSERT(flag == true, "Objects of type PdxTypes3 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be equal to Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be equal to Total "
"pdxSerializationsBytes.");
}
{
auto p4 = std::make_shared<PdxTypes4>();
auto keyport4 = CacheableKey::create(14);
regPtr0->put(keyport4, p4);
auto pRet4 = std::dynamic_pointer_cast<PdxTypes4>(regPtr0->get(keyport4));
flag = p4->equals(pRet4);
LOGDEBUG("PutAndVerifyVariousPdxTypes:.. flag = %d", flag);
ASSERT(flag == true, "Objects of type PdxTypes4 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be equal to Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be equal to Total "
"pdxSerializationsBytes.");
}
{
auto p5 = std::make_shared<PdxTypes5>();
auto keyport5 = CacheableKey::create(15);
regPtr0->put(keyport5, p5);
auto pRet5 = std::dynamic_pointer_cast<PdxTypes5>(regPtr0->get(keyport5));
flag = p5->equals(pRet5);
LOGDEBUG("PutAndVerifyVariousPdxTypes:.. flag = %d", flag);
ASSERT(flag == true, "Objects of type PdxTypes5 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be equal to Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be equal to Total "
"pdxSerializationsBytes.");
}
{
auto p6 = std::make_shared<PdxTypes6>();
auto keyport6 = CacheableKey::create(16);
regPtr0->put(keyport6, p6);
auto pRet6 = std::dynamic_pointer_cast<PdxTypes6>(regPtr0->get(keyport6));
flag = p6->equals(pRet6);
LOGDEBUG("PutAndVerifyVariousPdxTypes:.. flag = %d", flag);
ASSERT(flag == true, "Objects of type PdxTypes6 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be equal to Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be equal to Total "
"pdxSerializationsBytes.");
}
{
auto p7 = std::make_shared<PdxTypes7>();
auto keyport7 = CacheableKey::create(17);
regPtr0->put(keyport7, p7);
auto pRet7 = std::dynamic_pointer_cast<PdxTypes7>(regPtr0->get(keyport7));
flag = p7->equals(pRet7);
LOGDEBUG("PutAndVerifyVariousPdxTypes:.. flag = %d", flag);
ASSERT(flag == true, "Objects of type PdxTypes7 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be equal to Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be equal to Total "
"pdxSerializationsBytes.");
}
{
auto p8 = std::make_shared<PdxTypes8>();
auto keyport8 = CacheableKey::create(18);
regPtr0->put(keyport8, p8);
auto pRet8 = std::dynamic_pointer_cast<PdxTypes8>(regPtr0->get(keyport8));
flag = p8->equals(pRet8);
LOGDEBUG("PutAndVerifyVariousPdxTypes:.. flag = %d", flag);
ASSERT(flag == true, "Objects of type PdxTypes8 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be equal to Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be equal to Total "
"pdxSerializationsBytes.");
}
{
auto p9 = std::make_shared<PdxTypes9>();
auto keyport9 = CacheableKey::create(19);
regPtr0->put(keyport9, p9);
auto pRet9 = std::dynamic_pointer_cast<PdxTypes9>(regPtr0->get(keyport9));
flag = p9->equals(pRet9);
LOGDEBUG("PutAndVerifyVariousPdxTypes:.. flag = %d", flag);
ASSERT(flag == true, "Objects of type PdxTypes9 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be equal to Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be equal to Total "
"pdxSerializationsBytes.");
}
{
auto p10 = std::make_shared<PdxTypes10>();
auto keyport10 = CacheableKey::create(20);
regPtr0->put(keyport10, p10);
auto pRet10 =
std::dynamic_pointer_cast<PdxTypes10>(regPtr0->get(keyport10));
flag = p10->equals(pRet10);
LOGDEBUG("PutAndVerifyVariousPdxTypes:.. flag = %d", flag);
ASSERT(flag == true, "Objects of type PdxTypes10 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be equal to Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be equal to Total "
"pdxSerializationsBytes.");
}
LOG("NIL:329:StepFive complete.\n");
}
END_TASK_DEFINITION
// TestCase-1
// C1.generateJavaPdxType
DUNIT_TASK_DEFINITION(CLIENT1, generateJavaPdxType)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto args = CacheableKey::create("saveAllJavaPdxTypes");
auto key = CacheableKey::create(1);
auto routingObj = CacheableVector::create();
routingObj->push_back(key);
auto funcExec = FunctionService::onRegion(regPtr0);
auto collector = funcExec->withArgs(args)
->withFilter(routingObj)
->execute("ComparePdxTypes");
ASSERT(collector != nullptr, "onRegion collector nullptr");
auto result = collector->getResult();
LOGINFO("NIL:: testTCPDXTests: result->size = %d ", result->size());
if (result == nullptr) {
ASSERT(false, "echo String : result is nullptr");
} else {
//
bool gotResult = false;
for (int i = 0; i < result->size(); i++) {
try {
auto boolValue = std::dynamic_pointer_cast<CacheableBoolean>(
result->operator[](i));
LOGINFO("NIL:: boolValue is %d ", boolValue->value());
bool resultVal = boolValue->value();
ASSERT(resultVal == true,
"Function should return true NIL LINE_1508");
gotResult = true;
} catch (ClassCastException& ex) {
LOG("exFuncNameSendException casting to int for arrayList arguement "
"exception.");
std::string logmsg = "";
logmsg += ex.getName();
logmsg += ": ";
logmsg += ex.what();
LOG(logmsg.c_str());
LOG(ex.getStackTrace());
LOG("exFuncNameSendException now casting to "
"UserFunctionExecutionExceptionPtr for arrayList arguement "
"exception.");
auto uFEPtr =
std::dynamic_pointer_cast<UserFunctionExecutionException>(
result->operator[](i));
ASSERT(uFEPtr != nullptr, "uFEPtr exception is nullptr");
LOGINFO("Done casting to uFEPtr");
LOGINFO("Read expected uFEPtr exception %s ",
uFEPtr->getMessage()->asChar());
} catch (...) {
FAIL(
"exFuncNameSendException casting to string for bool arguement "
"Unknown exception.");
}
}
ASSERT(gotResult == true, "Function should (gotResult) return true ");
//
}
}
END_TASK_DEFINITION
// C1.putAllPdxTypes
DUNIT_TASK_DEFINITION(CLIENT1, putAllPdxTypes)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(PdxTypes1::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes3::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes4::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes5::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes6::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes7::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes8::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes9::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes10::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
// TODO::Uncomment it once PortfolioPdx/PositionPdx Classes are ready
// serializationRegistry->addPdxType(PdxTests.PortfolioPdx.CreateDeserializable);
// serializationRegistry->addPdxType(PdxTests.PositionPdx.CreateDeserializable);
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto p1 = std::make_shared<PdxTypes1>();
auto keyport1 = CacheableKey::create(p1->getClassName());
regPtr0->put(keyport1, p1);
auto p2 = std::make_shared<PdxTypes2>();
auto keyport2 = CacheableKey::create(p2->getClassName());
regPtr0->put(keyport2, p2);
auto p3 = std::make_shared<PdxTypes3>();
auto keyport3 = CacheableKey::create(p3->getClassName());
regPtr0->put(keyport3, p3);
auto p4 = std::make_shared<PdxTypes4>();
auto keyport4 = CacheableKey::create(p4->getClassName());
regPtr0->put(keyport4, p4);
auto p5 = std::make_shared<PdxTypes5>();
auto keyport5 = CacheableKey::create(p5->getClassName());
regPtr0->put(keyport5, p5);
auto p6 = std::make_shared<PdxTypes6>();
auto keyport6 = CacheableKey::create(p6->getClassName());
regPtr0->put(keyport6, p6);
auto p7 = std::make_shared<PdxTypes7>();
auto keyport7 = CacheableKey::create(p7->getClassName());
regPtr0->put(keyport7, p7);
auto p8 = std::make_shared<PdxTypes8>();
auto keyport8 = CacheableKey::create(p8->getClassName());
regPtr0->put(keyport8, p8);
auto p9 = std::make_shared<PdxTypes9>();
auto keyport9 = CacheableKey::create(p9->getClassName());
regPtr0->put(keyport9, p9);
auto p10 = std::make_shared<PdxTypes10>();
auto keyport10 = CacheableKey::create(p10->getClassName());
regPtr0->put(keyport10, p10);
//
}
END_TASK_DEFINITION
// C1.verifyDotNetPdxTypes
DUNIT_TASK_DEFINITION(CLIENT1, verifyDotNetPdxTypes)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto args = CacheableKey::create("compareDotNETPdxTypes");
auto key = CacheableKey::create(1);
auto routingObj = CacheableVector::create();
routingObj->push_back(key);
auto funcExec = FunctionService::onRegion(regPtr0);
auto collector = funcExec->withArgs(args)
->withFilter(routingObj)
->execute("ComparePdxTypes");
ASSERT(collector != nullptr, "onRegion collector nullptr");
auto result = collector->getResult();
LOGINFO("NIL:: testTCPDXTests:verifyDotNetPdxTypes result->size = %d ",
result->size());
if (result == nullptr) {
ASSERT(false, "echo String : result is nullptr");
} else {
bool gotResult = false;
for (int i = 0; i < result->size(); i++) {
try {
auto boolValue = std::dynamic_pointer_cast<CacheableBoolean>(
result->operator[](i));
LOGINFO("NIL::verifyDotNetPdxTypes boolValue is %d ",
boolValue->value());
bool resultVal = boolValue->value();
ASSERT(resultVal == true,
"Function should return true NIL LINE_1508");
gotResult = true;
} catch (ClassCastException& ex) {
LOG("exFuncNameSendException casting to int for arrayList arguement "
"exception.");
std::string logmsg = "";
logmsg += ex.getName();
logmsg += ": ";
logmsg += ex.what();
LOG(logmsg.c_str());
LOG(ex.getStackTrace());
LOG("exFuncNameSendException now casting to "
"UserFunctionExecutionExceptionPtr for arrayList arguement "
"exception.");
auto uFEPtr =
std::dynamic_pointer_cast<UserFunctionExecutionException>(
result->operator[](i));
ASSERT(uFEPtr != nullptr, "uFEPtr exception is nullptr");
LOGINFO("Done casting to uFEPtr");
LOGINFO("Read expected uFEPtr exception %s ",
uFEPtr->getMessage()->asChar());
} catch (...) {
FAIL(
"exFuncNameSendException casting to string for bool arguement "
"Unknown exception.");
}
}
ASSERT(gotResult == true, "Function should (gotResult) return true ");
}
}
END_TASK_DEFINITION
// END TestCase-1
// TestCase-2
// c1.client1PutsV1Object
DUNIT_TASK_DEFINITION(CLIENT1, client1PutsV1Object)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxType3V1::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
PdxTests::PdxType3V1::reset(false);
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto np = std::make_shared<PdxType3V1>();
regPtr0->put(keyport, np);
}
END_TASK_DEFINITION
// c2.client2GetsV1ObjectAndPutsV2Object
DUNIT_TASK_DEFINITION(CLIENT2, client2GetsV1ObjectAndPutsV2Object)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::PdxTypes3V2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
PdxTests::PdxTypes3V2::reset(false);
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
// get v1 object
auto keyport = CacheableKey::create(1);
auto pRet = std::dynamic_pointer_cast<PdxTypes3V2>(regPtr0->get(keyport));
// now put v2 object
auto np = std::make_shared<PdxTypes3V2>();
regPtr0->put(keyport, np);
LOGDEBUG("Task:client2GetsV1ObjectAndPutsV2Object Done successfully ");
}
END_TASK_DEFINITION
// c3.client3GetsV2Object
DUNIT_TASK_DEFINITION(CLIENT3, client3GetsV2Object)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto args = CacheableKey::create("compareDotNETPdxTypes");
auto key = CacheableKey::create(1);
auto routingObj = CacheableVector::create();
routingObj->push_back(key);
auto funcExec = FunctionService::onRegion(regPtr0);
auto collector = funcExec->execute("IterateRegion");
ASSERT(collector != nullptr, "onRegion collector nullptr");
auto result = collector->getResult();
LOGINFO("NIL:: testTCPDXTests:verifyDotNetPdxTypes result->size = %d ",
result->size());
if (result == nullptr) {
ASSERT(false, "echo String : result is nullptr");
} else {
bool gotResult = false;
for (int i = 0; i < result->size(); i++) {
try {
auto boolValue = std::dynamic_pointer_cast<CacheableBoolean>(
result->operator[](i));
LOGINFO("NIL::verifyDotNetPdxTypes boolValue is %d ",
boolValue->value());
bool resultVal = boolValue->value();
ASSERT(resultVal == true,
"Function should return true NIL LINE_1508");
gotResult = true;
} catch (ClassCastException& ex) {
LOG("exFuncNameSendException casting to int for arrayList arguement "
"exception.");
std::string logmsg = "";
logmsg += ex.getName();
logmsg += ": ";
logmsg += ex.what();
LOG(logmsg.c_str());
LOG(ex.getStackTrace());
LOG("exFuncNameSendException now casting to "
"UserFunctionExecutionExceptionPtr for arrayList arguement "
"exception.");
auto uFEPtr =
std::dynamic_pointer_cast<UserFunctionExecutionException>(
result->operator[](i));
ASSERT(uFEPtr != nullptr, "uFEPtr exception is nullptr");
LOGINFO("Done casting to uFEPtr");
LOGINFO("Read expected uFEPtr exception %s ",
uFEPtr->getMessage()->asChar());
} catch (...) {
FAIL(
"exFuncNameSendException casting to string for bool arguement "
"Unknown exception.");
}
}
ASSERT(gotResult == true, "Function should (gotResult) return true ");
}
}
END_TASK_DEFINITION
// END TestCase-2
DUNIT_TASK_DEFINITION(CLIENT2, VerifyVariousPdxGets)
{
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(PdxTypes1::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes2::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes3::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes4::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes5::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes6::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes7::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes8::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes9::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(PdxTypes10::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
// TODO::Uncomment it once PortfolioPdx/PositionPdx Classes are ready
// serializationRegistry->addPdxType(PdxTests.PortfolioPdx.CreateDeserializable);
// serializationRegistry->addPdxType(PdxTests.PositionPdx.CreateDeserializable);
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
bool flag = false;
{
auto p1 = std::make_shared<PdxTypes1>();
auto keyport = CacheableKey::create(11);
auto pRet = std::dynamic_pointer_cast<PdxTypes1>(regPtr0->get(keyport));
flag = p1->equals(pRet);
LOGDEBUG("VerifyVariousPdxGets:.. flag = %d", flag);
ASSERT(flag == true,
"VerifyVariousPdxGets:Objects of type PdxTypes1 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be less than Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be less than Total "
"pdxSerializationsBytes.");
}
{
auto p2 = std::make_shared<PdxTypes2>();
auto keyport2 = CacheableKey::create(12);
auto pRet2 = std::dynamic_pointer_cast<PdxTypes2>(regPtr0->get(keyport2));
flag = p2->equals(pRet2);
LOGDEBUG("VerifyVariousPdxGets:. flag = %d", flag);
ASSERT(flag == true,
"VerifyVariousPdxGets:Objects of type PdxTypes2 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be less than Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be less than Total "
"pdxSerializationsBytes.");
}
{
auto p3 = std::make_shared<PdxTypes3>();
auto keyport3 = CacheableKey::create(13);
auto pRet3 = std::dynamic_pointer_cast<PdxTypes3>(regPtr0->get(keyport3));
flag = p3->equals(pRet3);
LOGDEBUG("VerifyVariousPdxGets:.. flag = %d", flag);
ASSERT(flag == true,
"VerifyVariousPdxGets:Objects of type PdxTypes3 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be less than Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be less than Total "
"pdxSerializationsBytes.");
}
{
auto p4 = std::make_shared<PdxTypes4>();
auto keyport4 = CacheableKey::create(14);
auto pRet4 = std::dynamic_pointer_cast<PdxTypes4>(regPtr0->get(keyport4));
flag = p4->equals(pRet4);
LOGDEBUG("VerifyVariousPdxGets:.. flag = %d", flag);
ASSERT(flag == true,
"VerifyVariousPdxGets:Objects of type PdxTypes4 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be less than Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be less than Total "
"pdxSerializationsBytes.");
}
{
auto p5 = std::make_shared<PdxTypes5>();
auto keyport5 = CacheableKey::create(15);
auto pRet5 = std::dynamic_pointer_cast<PdxTypes5>(regPtr0->get(keyport5));
flag = p5->equals(pRet5);
LOGDEBUG("VerifyVariousPdxGets:.. flag = %d", flag);
ASSERT(flag == true,
"VerifyVariousPdxGets:Objects of type PdxTypes5 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be less than Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be less than Total "
"pdxSerializationsBytes.");
}
{
auto p6 = std::make_shared<PdxTypes6>();
auto keyport6 = CacheableKey::create(16);
auto pRet6 = std::dynamic_pointer_cast<PdxTypes6>(regPtr0->get(keyport6));
flag = p6->equals(pRet6);
LOGDEBUG("VerifyVariousPdxGets:.. flag = %d", flag);
ASSERT(flag == true,
"VerifyVariousPdxGets:Objects of type PdxTypes6 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be less than Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be less than Total "
"pdxSerializationsBytes.");
}
{
auto p7 = std::make_shared<PdxTypes7>();
auto keyport7 = CacheableKey::create(17);
auto pRet7 = std::dynamic_pointer_cast<PdxTypes7>(regPtr0->get(keyport7));
flag = p7->equals(pRet7);
LOGDEBUG("VerifyVariousPdxGets:.. flag = %d", flag);
ASSERT(flag == true,
"VerifyVariousPdxGets:Objects of type PdxTypes7 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be less than Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be less than Total "
"pdxSerializationsBytes.");
}
{
auto p8 = std::make_shared<PdxTypes8>();
auto keyport8 = CacheableKey::create(18);
auto pRet8 = std::dynamic_pointer_cast<PdxTypes8>(regPtr0->get(keyport8));
flag = p8->equals(pRet8);
LOGDEBUG("VerifyVariousPdxGets:.. flag = %d", flag);
ASSERT(flag == true,
"VerifyVariousPdxGets:Objects of type PdxTypes8 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be less than Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be less than Total "
"pdxSerializationsBytes.");
}
{
auto p9 = std::make_shared<PdxTypes9>();
auto keyport9 = CacheableKey::create(19);
auto pRet9 = std::dynamic_pointer_cast<PdxTypes9>(regPtr0->get(keyport9));
flag = p9->equals(pRet9);
LOGDEBUG("VerifyVariousPdxGets:. flag = %d", flag);
ASSERT(flag == true,
"VerifyVariousPdxGets:Objects of type PdxTypes9 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be less than Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be less than Total "
"pdxSerializationsBytes.");
}
{
auto p10 = std::make_shared<PdxTypes10>();
auto keyport10 = CacheableKey::create(20);
auto pRet10 =
std::dynamic_pointer_cast<PdxTypes10>(regPtr0->get(keyport10));
flag = p10->equals(pRet10);
LOGDEBUG("VerifyVariousPdxGets:.. flag = %d", flag);
ASSERT(flag == true,
"VerifyVariousPdxGets:Objects of type PdxTypes10 should be equal");
checkPdxInstanceToStringAtServer(regPtr0);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO("PdxDeSerializations = %d ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be less than Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() <
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be less than Total "
"pdxSerializationsBytes.");
}
LOG("NIL:436:StepSix complete.\n");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, putOperation)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
regPtr0->put(1, 1);
// Verify the CLientName.::putOperation
// auto testReg = getHelper()->getRegion("testregion");
auto valuePtr1 = regPtr0->get("clientName1");
const char* clientName1 =
(std::dynamic_pointer_cast<CacheableString>(valuePtr1))->asChar();
LOGINFO(" C1.putOperation Got ClientName1 = %s ", clientName1);
ASSERT(strcmp(clientName1, "Client-1") == 0,
"ClientName for Client-1 is not set");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, getOperation)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto keyport = CacheableKey::create(1);
auto value = regPtr0->get(keyport);
// Verify Client Name for C2
auto valuePtr2 = regPtr0->get("clientName2");
const char* clientName2 =
(std::dynamic_pointer_cast<CacheableString>(valuePtr2))->asChar();
LOGINFO(" C2.getOperation Got ClientName2 = %s ", clientName2);
ASSERT(strcmp(clientName2, "Client-2") == 0,
"ClientName for Client-2 is not set");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, putCharTypes)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
try {
serializationRegistry->addPdxType(
PdxTests::CharTypes::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
LOG("PdxTests::CharTypes Registered Successfully....");
LOG("Trying to populate PDX objects.....\n");
auto pdxobj = std::make_shared<PdxTests::CharTypes>();
auto keyport = CacheableKey::create(1);
// PUT Operation
regPtr0->put(keyport, pdxobj);
LOG("PdxTests::CharTypes: PUT Done successfully....");
// locally destroy PdxTests::PdxType
regPtr0->localDestroy(keyport);
LOG("localDestroy() operation....Done");
LOG("Done populating PDX objects.....Success\n");
LOG("STEP putCharTypes complete.\n");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, getCharTypes)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
LOG("Trying to GET PDX objects.....\n");
try {
serializationRegistry->addPdxType(
PdxTests::CharTypes::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
auto localPdxptr = std::make_shared<PdxTests::CharTypes>();
auto keyport = CacheableKey::create(1);
LOG("Client-2 PdxTests::CharTypes GET OP Start....");
auto remotePdxptr =
std::dynamic_pointer_cast<PdxTests::CharTypes>(regPtr0->get(keyport));
LOG("Client-2 PdxTests::CharTypes GET OP Done....");
PdxTests::CharTypes* localPdx = localPdxptr.get();
PdxTests::CharTypes* remotePdx =
dynamic_cast<PdxTests::CharTypes*>(remotePdxptr.get());
LOGINFO("testThinClientPdxTests:StepFour before equal() check");
ASSERT(remotePdx->equals(*localPdx) == true,
"PdxTests::PdxTypes should be equal.");
LOGINFO("testThinClientPdxTests:StepFour equal check done successfully");
// LOGINFO("GET OP Result: Char Val=%c", remotePdx->getChar());
// LOGINFO("NIL GET OP Result: Char[0] val=%c",
// remotePdx->getCharArray()[0]);
// LOGINFO("NIL GET OP Result: Char[1] val=%c",
// remotePdx->getCharArray()[1]);
LOG("STEP: getCharTypes complete.\n");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, StepThree)
{
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
// QueryHelper * qh = &QueryHelper::getHelper();
try {
serializationRegistry->addPdxType(
PdxTests::PdxType::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(Address::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
LOG("PdxClassV1 Registered Successfully....");
LOG("Trying to populate PDX objects.....\n");
auto pdxobj = std::make_shared<PdxTests::PdxType>();
auto keyport = CacheableKey::create(1);
// PUT Operation
regPtr0->put(keyport, pdxobj);
LOG("PdxTests::PdxType: PUT Done successfully....");
// PUT CacheableObjectArray as a Value
auto keyport2 = CacheableKey::create(2);
std::shared_ptr<CacheableObjectArray> m_objectArray;
m_objectArray = CacheableObjectArray::create();
m_objectArray->push_back(
std::shared_ptr<Address>(new Address(1, "street0", "city0")));
m_objectArray->push_back(
std::shared_ptr<Address>(new Address(2, "street1", "city1")));
m_objectArray->push_back(
std::shared_ptr<Address>(new Address(3, "street2", "city2")));
m_objectArray->push_back(
std::shared_ptr<Address>(new Address(4, "street3", "city3")));
m_objectArray->push_back(
std::shared_ptr<Address>(new Address(5, "street4", "city4")));
m_objectArray->push_back(
std::shared_ptr<Address>(new Address(6, "street5", "city5")));
m_objectArray->push_back(
std::shared_ptr<Address>(new Address(7, "street6", "city6")));
m_objectArray->push_back(
std::shared_ptr<Address>(new Address(8, "street7", "city7")));
m_objectArray->push_back(
std::shared_ptr<Address>(new Address(9, "street8", "city8")));
m_objectArray->push_back(
std::shared_ptr<Address>(new Address(10, "street9", "city9")));
// PUT Operation
regPtr0->put(keyport2, m_objectArray);
// locally destroy PdxTests::PdxType
regPtr0->localDestroy(keyport);
regPtr0->localDestroy(keyport2);
LOG("localDestroy() operation....Done");
// This is merely for asserting statistics
regPtr0->get(keyport);
regPtr0->get(keyport2);
LocalRegion* lregPtr = (dynamic_cast<LocalRegion*>(regPtr0.get()));
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO(
"PdxDeSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
ASSERT(
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be equal to Total "
"pdxSerializations.");
ASSERT(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes() ==
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be equal to Total "
"pdxSerializationsBytes.");
// Now update new keys with updated stats values, so that other client can
// verify these values with its stats.
auto keyport3 = CacheableKey::create(3);
auto keyport4 = CacheableKey::create(4);
regPtr0->put(keyport3,
CacheableInt32::create(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations()));
regPtr0->put(keyport4,
CacheableInt64::create(lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes()));
LOG("Done populating PDX objects.....Success\n");
LOG("StepThree complete.\n");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, StepFour)
{
// initClient(true);
auto regPtr0 = getHelper()->getRegion("DistRegionAck");
// QueryHelper * qh = &QueryHelper::getHelper();
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
LOG("Trying to GET PDX objects.....\n");
try {
serializationRegistry->addPdxType(
PdxTests::PdxType::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
try {
serializationRegistry->addPdxType(Address::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
// Create local CacheableObjectArray
std::shared_ptr<CacheableObjectArray> m_localObjectArray;
m_localObjectArray = CacheableObjectArray::create();
m_localObjectArray->push_back(
std::shared_ptr<Address>(new Address(1, "street0", "city0")));
m_localObjectArray->push_back(
std::shared_ptr<Address>(new Address(2, "street1", "city1")));
m_localObjectArray->push_back(
std::shared_ptr<Address>(new Address(3, "street2", "city2")));
m_localObjectArray->push_back(
std::shared_ptr<Address>(new Address(4, "street3", "city3")));
m_localObjectArray->push_back(
std::shared_ptr<Address>(new Address(5, "street4", "city4")));
m_localObjectArray->push_back(
std::shared_ptr<Address>(new Address(6, "street5", "city5")));
m_localObjectArray->push_back(
std::shared_ptr<Address>(new Address(7, "street6", "city6")));
m_localObjectArray->push_back(
std::shared_ptr<Address>(new Address(8, "street7", "city7")));
m_localObjectArray->push_back(
std::shared_ptr<Address>(new Address(9, "street8", "city8")));
m_localObjectArray->push_back(
std::shared_ptr<Address>(new Address(10, "street9", "city9")));
// Get remote CacheableObjectArray on key 2
auto keyport2 = CacheableKey::create(2);
LOGINFO("Client-2 PdxTests::PdxType GET OP Start....");
auto remoteCObjArray =
std::dynamic_pointer_cast<CacheableObjectArray>(regPtr0->get(keyport2));
LOGINFO(
"Client-2 PdxTests::PdxType GET OP Done.. Received CObjeArray Size = "
"%d",
remoteCObjArray->size());
ASSERT(
remoteCObjArray->size() == 10,
"PdxTests StepFour: CacheableObjectArray Size should be equal to 10");
// Compare local vs remote CacheableObjectArray elements.
bool isEqual = true;
for (int i = 0; i < remoteCObjArray->size(); i++) {
Address* rAddr1 = dynamic_cast<Address*>(remoteCObjArray->at(i).get());
Address* lAddr1 = dynamic_cast<Address*>(m_localObjectArray->at(i).get());
LOGINFO("Remote Address:: %d th element AptNum=%d street=%s city=%s ",
i, rAddr1->getAptNum(), rAddr1->getStreet(), rAddr1->getCity());
if (!rAddr1->equals(*lAddr1)) {
isEqual = false;
break;
}
}
ASSERT(isEqual == true,
"PdxTests StepFour: CacheableObjectArray elements are not matched");
auto localPdxptr = std::make_shared<PdxTests::PdxType>();
auto keyport = CacheableKey::create(1);
LOG("Client-2 PdxTests::PdxType GET OP Start....");
auto remotePdxptr =
std::dynamic_pointer_cast<PdxTests::PdxType>(regPtr0->get(keyport));
LOG("Client-2 PdxTests::PdxType GET OP Done....");
//
PdxTests::PdxType* localPdx = localPdxptr.get();
PdxTests::PdxType* remotePdx =
dynamic_cast<PdxTests::PdxType*>(remotePdxptr.get());
// ToDo open this equals check
LOGINFO("testThinClientPdxTests:StepFour before equal() check");
ASSERT(remotePdx->equals(*localPdx, false) == true,
"PdxTests::PdxTypes should be equal.");
LOGINFO("testThinClientPdxTests:StepFour equal check done successfully");
LOGINFO("GET OP Result: Char Val=%c", remotePdx->getChar());
LOGINFO("NIL GET OP Result: Char[0] val=%c", remotePdx->getCharArray()[0]);
LOGINFO("NIL GET OP Result: Char[1] val=%c", remotePdx->getCharArray()[1]);
LOGINFO("GET OP Result: Array of byte arrays [0]=%x",
remotePdx->getArrayOfByteArrays()[0][0]);
LOGINFO("GET OP Result: Array of byte arrays [1]=%x",
remotePdx->getArrayOfByteArrays()[1][0]);
LOGINFO("GET OP Result: Array of byte arrays [2]=%x",
remotePdx->getArrayOfByteArrays()[1][1]);
CacheableInt32* element =
dynamic_cast<CacheableInt32*>(remotePdx->getArrayList()->at(0).get());
LOGINFO("GET OP Result_1233: Array List element Value =%d",
element->value());
for (const auto& iter : *(remotePdx->getHashTable())) {
const auto remoteKey =
std::dynamic_pointer_cast<CacheableInt32>(iter.first);
const auto remoteVal =
std::dynamic_pointer_cast<CacheableString>(iter.second);
LOGINFO("HashTable Key Val = %d", remoteKey->value());
LOGINFO("HashTable Val = %s", remoteVal->asChar());
//(*iter1).first.value();
// output.writeObject( *iter );
}
// Now get values for key3 and 4 to asset against stats of this client
const auto lregPtr = std::dynamic_pointer_cast<LocalRegion>(regPtr0);
LOGINFO(
"PdxSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxSerializations());
LOGINFO(
"PdxDeSerializations = %d ",
lregPtr->getCacheImpl()->getCachePerfStats().getPdxDeSerializations());
LOGINFO("PdxSerializationBytes = %ld ", lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxSerializationBytes());
LOGINFO("PdxDeSerializationBytes = %ld ",
lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes());
auto keyport3 = CacheableKey::create(3);
auto keyport4 = CacheableKey::create(4);
auto int32Ptr =
std::dynamic_pointer_cast<CacheableInt32>(regPtr0->get(keyport3));
auto int64Ptr =
std::dynamic_pointer_cast<CacheableInt64>(regPtr0->get(keyport4));
ASSERT(int32Ptr->value() == lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializations(),
"Total pdxDeserializations should be equal to Total "
"pdxSerializations.");
ASSERT(int64Ptr->value() == lregPtr->getCacheImpl()
->getCachePerfStats()
.getPdxDeSerializationBytes(),
"Total pdxDeserializationBytes should be equal to Total "
"pdxSerializationsBytes.");
// LOGINFO("GET OP Result: IntVal1=%d", obj2->getInt1());
// LOGINFO("GET OP Result: IntVal2=%d", obj2->getInt2());
// LOGINFO("GET OP Result: IntVal3=%d", obj2->getInt3());
// LOGINFO("GET OP Result: IntVal4=%d", obj2->getInt4());
// LOGINFO("GET OP Result: IntVal5=%d", obj2->getInt5());
// LOGINFO("GET OP Result: IntVal6=%d", obj2->getInt6());
// LOGINFO("GET OP Result: BoolVal=%d", obj2->getBool());
// LOGINFO("GET OP Result: ByteVal=%d", obj2->getByte());
// LOGINFO("GET OP Result: ShortVal=%d", obj2->getShort());
// LOGINFO("GET OP Result: IntVal=%d", obj2->getInt());
// LOGINFO("GET OP Result: LongVal=%ld", obj2->getLong());
// LOGINFO("GET OP Result: FloatVal=%f", obj2->getFloat());
// LOGINFO("GET OP Result: DoubleVal=%lf", obj2->getDouble());
// LOGINFO("GET OP Result: StringVal=%s", obj2->getString());
// LOGINFO("GET OP Result: BoolArray[0]=%d", obj2->getBoolArray()[0]);
// LOGINFO("GET OP Result: BoolArray[1]=%d", obj2->getBoolArray()[1]);
// LOGINFO("GET OP Result: BoolArray[2]=%d", obj2->getBoolArray()[2]);
// LOGINFO("GET OP Result: ByteArray[0]=%d", obj2->getByteArray()[0]);
// LOGINFO("GET OP Result: ByteArray[1]=%d", obj2->getByteArray()[1]);
// LOGINFO("GET OP Result: ShortArray[0]=%d", obj2->getShortArray()[0]);
// LOGINFO("GET OP Result: IntArray[0]=%d", obj2->getIntArray()[0]);
// LOGINFO("GET OP Result: LongArray[1]=%lld", obj2->getLongArray()[1]);
// LOGINFO("GET OP Result: FloatArray[0]=%f", obj2->getFloatArray()[0]);
// LOGINFO("GET OP Result: DoubleArray[1]=%lf", obj2->getDoubleArray()[1]);
LOG("Done Getting PDX objects.....Success\n");
LOG("StepFour complete.\n");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, CloseCache1)
{
LOG("cleanProc 1...");
isPoolConfig = false;
cleanProc();
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, CloseCache2)
{
LOG("cleanProc 2...");
isPoolConfig = false;
cleanProc();
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT3, CloseCache3)
{
LOG("cleanProc 2...");
isPoolConfig = false;
cleanProc();
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(SERVER1, CloseServer)
{
LOG("closing Server1...");
if (isLocalServer) {
CacheHelper::closeServer(1);
LOG("SERVER1 stopped");
}
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(LOCATOR, CloseLocator)
{
if (isLocator) {
CacheHelper::closeLocator(1);
LOG("Locator1 stopped");
}
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, SetWeakHashMapToTrueC1)
{
m_useWeakHashMap = true;
PdxTests::PdxTypesIgnoreUnreadFieldsV1::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, SetWeakHashMapToTrueC2)
{
m_useWeakHashMap = true;
PdxTests::PdxTypesIgnoreUnreadFieldsV2::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, setWeakHashMapToFlaseC1)
{
m_useWeakHashMap = false;
PdxTests::PdxTypesIgnoreUnreadFieldsV1::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, SetWeakHashMapToFalseC2)
{
m_useWeakHashMap = false;
PdxTests::PdxTypesIgnoreUnreadFieldsV2::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
///
DUNIT_TASK_DEFINITION(CLIENT1, SetWeakHashMapToTrueC1BM)
{
m_useWeakHashMap = true;
PdxTests::PdxType1V1::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, SetWeakHashMapToTrueC2BM)
{
m_useWeakHashMap = true;
PdxTests::PdxTypes1V2::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, setWeakHashMapToFlaseC1BM)
{
m_useWeakHashMap = false;
PdxTests::PdxType1V1::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, SetWeakHashMapToFalseC2BM)
{
m_useWeakHashMap = false;
PdxTests::PdxTypes1V2::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
///
DUNIT_TASK_DEFINITION(CLIENT1, SetWeakHashMapToTrueC1BM2)
{
m_useWeakHashMap = true;
PdxTests::PdxType2V1::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, SetWeakHashMapToTrueC2BM2)
{
m_useWeakHashMap = true;
PdxTests::PdxTypes2V2::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, setWeakHashMapToFlaseC1BM2)
{
m_useWeakHashMap = false;
PdxTests::PdxType2V1::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, SetWeakHashMapToFalseC2BM2)
{
m_useWeakHashMap = false;
PdxTests::PdxTypes2V2::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
///
DUNIT_TASK_DEFINITION(CLIENT1, SetWeakHashMapToTrueC1BM3)
{
m_useWeakHashMap = true;
PdxTests::PdxType3V1::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, SetWeakHashMapToTrueC2BM3)
{
m_useWeakHashMap = true;
PdxTests::PdxTypes3V2::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, setWeakHashMapToFlaseC1BM3)
{
m_useWeakHashMap = false;
PdxTests::PdxType3V1::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, SetWeakHashMapToFalseC2BM3)
{
m_useWeakHashMap = false;
PdxTests::PdxTypes3V2::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
///
DUNIT_TASK_DEFINITION(CLIENT1, SetWeakHashMapToTrueC1BMR1)
{
m_useWeakHashMap = true;
PdxTests::PdxTypesV1R1::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, SetWeakHashMapToTrueC2BMR1)
{
m_useWeakHashMap = true;
PdxTests::PdxTypesR1V2::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, setWeakHashMapToFlaseC1BMR1)
{
m_useWeakHashMap = false;
PdxTests::PdxTypesV1R1::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, SetWeakHashMapToFalseC2BMR1)
{
m_useWeakHashMap = false;
PdxTests::PdxTypesR1V2::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
///
DUNIT_TASK_DEFINITION(CLIENT1, SetWeakHashMapToTrueC1BMR2)
{
m_useWeakHashMap = true;
PdxTests::PdxTypesV1R2::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, SetWeakHashMapToTrueC2BMR2)
{
m_useWeakHashMap = true;
PdxTests::PdxTypesR2V2::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, setWeakHashMapToFlaseC1BMR2)
{
m_useWeakHashMap = false;
PdxTests::PdxTypesV1R2::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT2, SetWeakHashMapToFalseC2BMR2)
{
m_useWeakHashMap = false;
PdxTests::PdxTypesR2V2::reset(m_useWeakHashMap);
}
END_TASK_DEFINITION
///
void runPdxLongRunningClientTest(bool poolConfig = false,
bool withLocators = false) {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator)
CALL_TASK(StepOnePoolLocSysConfig)
CALL_TASK(StepTwoPoolLocSysConfig)
// StepThree: Put some portfolio/Position objects
CALL_TASK(Puts2)
// now close server
CALL_TASK(CloseServer)
CALL_TASK(forCleanup)
// now start server
CALL_TASK(CreateServerWithLocator)
// do put again
CALL_TASK(Puts22)
CALL_TASK(Get2)
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
void runPdxDistOps() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator)
CALL_TASK(StepOnePoolLoc)
CALL_TASK(StepTwoPoolLoc)
// StepThree: Put some portfolio/Position objects
CALL_TASK(PutAndVerifyPdxInGet)
CALL_TASK(VerifyGetOnly)
CALL_TASK(PutAndVerifyVariousPdxTypes)
CALL_TASK(VerifyVariousPdxGets)
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
void runPdxTestForCharTypes(bool poolConfig = false,
bool withLocators = false) {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator)
CALL_TASK(StepOnePoolLoc)
CALL_TASK(StepTwoPoolLoc)
// StepThree: Put some portfolio/Position objects
CALL_TASK(putCharTypes)
CALL_TASK(getCharTypes)
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
void testBug866() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator)
CALL_TASK(StepOnePoolLocBug866)
CALL_TASK(StepTwoPoolLocBug866)
// StepThree: Put some portfolio/Position objects
CALL_TASK(putOperation)
CALL_TASK(getOperation)
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
void runPdxPutGetTest() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator)
CALL_TASK(StepOnePoolLoc)
CALL_TASK(StepTwoPoolLoc)
// StepThree: Put some portfolio/Position objects
CALL_TASK(StepThree)
CALL_TASK(StepFour)
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
void runBasicMergeOpsR2() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator1)
CALL_TASK(StepOnePoolLoc)
CALL_TASK(StepTwoPoolLoc)
CALL_TASK(putAtVersionTwoR21)
CALL_TASK(getPutAtVersionOneR22)
for (int i = 0; i < 10; i++) {
CALL_TASK(getPutAtVersionTwoR23);
CALL_TASK(getPutAtVersionOneR24);
}
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
void runBasicMergeOpsR1() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator1)
CALL_TASK(StepOnePoolLoc)
CALL_TASK(StepTwoPoolLoc)
CALL_TASK(putAtVersionTwo1)
CALL_TASK(getPutAtVersionOne2)
CALL_TASK(getPutAtVersionTwo3)
CALL_TASK(getPutAtVersionOne4)
for (int i = 0; i < 10; i++) {
CALL_TASK(getPutAtVersionTwo5);
CALL_TASK(getPutAtVersionOne6);
}
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
void runBasicMergeOps() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator1)
CALL_TASK(StepOnePoolLoc)
CALL_TASK(StepTwoPoolLoc)
CALL_TASK(putAtVersionOne11)
CALL_TASK(getPutAtVersionTwo12)
CALL_TASK(getPutAtVersionOne13)
CALL_TASK(getPutAtVersionTwo14)
for (int i = 0; i < 10; i++) {
CALL_TASK(getPutAtVersionOne15);
CALL_TASK(getPutAtVersionTwo16);
}
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
void runBasicMergeOps2() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator1)
CALL_TASK(StepOnePoolLoc)
CALL_TASK(StepTwoPoolLoc)
CALL_TASK(putAtVersionOne21)
CALL_TASK(getPutAtVersionTwo22)
for (int i = 0; i < 10; i++) {
CALL_TASK(getPutAtVersionOne23);
CALL_TASK(getPutAtVersionTwo24);
}
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
void runBasicMergeOps3() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator1)
CALL_TASK(StepOnePoolLoc)
CALL_TASK(StepTwoPoolLoc)
CALL_TASK(putAtVersionOne31)
CALL_TASK(getPutAtVersionTwo32)
for (int i = 0; i < 10; i++) {
CALL_TASK(getPutAtVersionOne33);
CALL_TASK(getPutAtVersionTwo34);
}
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
void runJavaInteroperableOps() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator2)
CALL_TASK(StepOnePoolLoc)
CALL_TASK(StepTwoPoolLoc)
CALL_TASK(JavaPutGet) // c1
CALL_TASK(JavaGet) // c2
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
// runJavaInterOpsUsingLinkedList
void runJavaInterOpsUsingLinkedList() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator2)
CALL_TASK(StepOnePoolLoc1)
CALL_TASK(StepTwoPoolLoc1)
CALL_TASK(JavaPutGet1) // c1
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
// test case that checks for Invalid Usage and corr. IllegalStatException for
// PDXReader And PDXWriter APIs.
void _disable_see_bug_999_testReaderWriterInvalidUsage() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator2)
CALL_TASK(StepOnePoolLoc)
CALL_TASK(StepTwoPoolLoc)
CALL_TASK(testPdxWriterAPIsWithInvalidArgs)
CALL_TASK(testPdxReaderAPIsWithInvalidArgs)
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
//
void testPolymorphicUseCase() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator2)
CALL_TASK(StepOnePoolLoc)
CALL_TASK(StepTwoPoolLoc)
CALL_TASK(testPutWithMultilevelInheritance)
CALL_TASK(testGetWithMultilevelInheritance)
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
void runNestedPdxOps() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator1)
CALL_TASK(StepOnePoolLoc)
CALL_TASK(StepTwoPoolLoc)
CALL_TASK(PutAndVerifyNestedPdxInGet)
CALL_TASK(VerifyNestedGetOnly)
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
void runNestedPdxOpsWithVersioning() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator1)
CALL_TASK(StepOnePoolLoc)
CALL_TASK(StepTwoPoolLoc)
CALL_TASK(PutMixedVersionNestedPdx)
CALL_TASK(VerifyMixedVersionNestedGetOnly)
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
void runPdxInGFSOps() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator1)
CALL_TASK(StepOnePoolLoc)
CALL_TASK(StepTwoPoolLoc)
CALL_TASK(PutAndVerifyPdxInGFSInGet)
CALL_TASK(VerifyPdxInGFSGetOnly)
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
void runPdxIgnoreUnreadFieldTest() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator1)
CALL_TASK(StepOnePoolLoc_PDX)
CALL_TASK(StepTwoPoolLoc_PDX)
CALL_TASK(putV2PdxUI)
CALL_TASK(putV1PdxUI)
CALL_TASK(getV2PdxUI)
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
// runPdxMetadataCheckTest
void runPdxMetadataCheckTest() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator_PdxMetadataTest)
CALL_TASK(StepOnePoolLoc_PdxMetadataTest)
CALL_TASK(StepTwoPoolLoc_PdxMetadataTest)
CALL_TASK(generateJavaPdxType)
CALL_TASK(putAllPdxTypes)
CALL_TASK(verifyDotNetPdxTypes)
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
// END runPdxMetadataCheckTest
// runPdxBankTest
void runPdxBankTest() {
CALL_TASK(StartLocator)
CALL_TASK(CreateServerWithLocator_PdxMetadataTest)
CALL_TASK(StepOnePoolLoc_PdxMetadataTest)
CALL_TASK(StepTwoPoolLoc_PdxMetadataTest)
CALL_TASK(StepThreePoolLoc_PdxMetadataTest)
CALL_TASK(client1PutsV1Object) // c1
CALL_TASK(client2GetsV1ObjectAndPutsV2Object) // c2
CALL_TASK(client3GetsV2Object) // c3
CALL_TASK(CloseCache1)
CALL_TASK(CloseCache2)
CALL_TASK(CloseCache3) //
CALL_TASK(CloseServer)
CALL_TASK(CloseLocator)
}
void enableWeakHashMapC1() { CALL_TASK(SetWeakHashMapToTrueC1) }
void enableWeakHashMapC2() { CALL_TASK(SetWeakHashMapToTrueC2) }
void disableWeakHashMapC1() { CALL_TASK(setWeakHashMapToFlaseC1) }
void disableWeakHashMapC2() { CALL_TASK(SetWeakHashMapToFalseC2) }
/////
void enableWeakHashMapC1BM() { CALL_TASK(SetWeakHashMapToTrueC1BM) }
void enableWeakHashMapC2BM() { CALL_TASK(SetWeakHashMapToTrueC2BM) }
void disableWeakHashMapC1BM() { CALL_TASK(setWeakHashMapToFlaseC1BM) }
void disableWeakHashMapC2BM() { CALL_TASK(SetWeakHashMapToFalseC2BM) }
////
void enableWeakHashMapC1BM2() { CALL_TASK(SetWeakHashMapToTrueC1BM2) }
void enableWeakHashMapC2BM2() { CALL_TASK(SetWeakHashMapToTrueC2BM2) }
void disableWeakHashMapC1BM2() { CALL_TASK(setWeakHashMapToFlaseC1BM2) }
void disableWeakHashMapC2BM2() { CALL_TASK(SetWeakHashMapToFalseC2BM2) }
////
void enableWeakHashMapC1BM3() { CALL_TASK(SetWeakHashMapToTrueC1BM3) }
void enableWeakHashMapC2BM3() { CALL_TASK(SetWeakHashMapToTrueC2BM3) }
void disableWeakHashMapC1BM3() { CALL_TASK(setWeakHashMapToFlaseC1BM3) }
void disableWeakHashMapC2BM3() { CALL_TASK(SetWeakHashMapToFalseC2BM3) }
/////
void enableWeakHashMapC1BMR1() { CALL_TASK(SetWeakHashMapToTrueC1BMR1) }
void enableWeakHashMapC2BMR1() { CALL_TASK(SetWeakHashMapToTrueC2BMR1) }
void disableWeakHashMapC1BMR1() { CALL_TASK(setWeakHashMapToFlaseC1BMR1) }
void disableWeakHashMapC2BMR1() { CALL_TASK(SetWeakHashMapToFalseC2BMR1) }
///////
void enableWeakHashMapC1BMR2() { CALL_TASK(SetWeakHashMapToTrueC1BMR2) }
void enableWeakHashMapC2BMR2() { CALL_TASK(SetWeakHashMapToTrueC2BMR2) }
void disableWeakHashMapC1BMR2() { CALL_TASK(setWeakHashMapToFlaseC1BMR2) }
void disableWeakHashMapC2BMR2(){CALL_TASK(SetWeakHashMapToFalseC2BMR2)}
DUNIT_MAIN {
{ runPdxLongRunningClientTest(); }
// NON PDX UnitTest for Ticket#866 on NC OR SR#13306117704. Set client name
// via native client API
testBug866();
runPdxTestForCharTypes();
// PUT-GET Test with values of type CacheableObjectArray and PdxType object
runPdxPutGetTest();
// PdxDistOps-PdxTests::PdxType PUT/GET Test across clients
{ runPdxDistOps(); }
// BasicMergeOps
{
enableWeakHashMapC1BM();
enableWeakHashMapC2BM();
runBasicMergeOps();
}
// BasicMergeOps2
{
enableWeakHashMapC1BM2();
enableWeakHashMapC2BM2();
runBasicMergeOps2();
}
// BasicMergeOps3
{
enableWeakHashMapC1BM3();
enableWeakHashMapC2BM3();
runBasicMergeOps3();
}
// BasicMergeOpsR1
{
enableWeakHashMapC1BMR1();
enableWeakHashMapC2BMR1();
runBasicMergeOpsR1();
}
// BasicMergeOpsR2
{
enableWeakHashMapC1BMR2();
enableWeakHashMapC2BMR2();
runBasicMergeOpsR2();
}
// JavaInteroperableOps
{ runJavaInteroperableOps(); }
// PDXReaderWriterInvalidUsage
{
// disable see bug 999 for more details.
// testReaderWriterInvalidUsage();
}
// Test LinkedList
{
runJavaInterOpsUsingLinkedList();
}
// NestedPdxOps
{ runNestedPdxOps(); }
// MixedVersionNestedPdxOps
{ runNestedPdxOpsWithVersioning(); }
// Pdxobject In Geode Serializable Ops
//{
// runPdxInGFSOps();
//}
{
enableWeakHashMapC1();
enableWeakHashMapC2();
runPdxIgnoreUnreadFieldTest();
}
// PdxMetadataCheckTest
{ runPdxMetadataCheckTest(); }
// PdxBankTest
{ runPdxBankTest(); }
// Polymorphic-multilevel inheritance
{ testPolymorphicUseCase(); }
}
END_MAIN
| {
"content_hash": "069c49380238bde9c9aba2174039ec89",
"timestamp": "",
"source": "github",
"line_count": 4378,
"max_line_length": 85,
"avg_line_length": 34.28163544997716,
"alnum_prop": 0.6396641902921678,
"repo_name": "mhansonp/geode-native",
"id": "58c866d9fd946df92352fe50f05f9d073de0aedf",
"size": "150887",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "cppcache/integration-test/testThinClientPdxTests.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1899"
},
{
"name": "C#",
"bytes": "3515617"
},
{
"name": "C++",
"bytes": "10771399"
},
{
"name": "CMake",
"bytes": "107196"
},
{
"name": "GAP",
"bytes": "73860"
},
{
"name": "Java",
"bytes": "408387"
},
{
"name": "Perl",
"bytes": "2704"
},
{
"name": "PowerShell",
"bytes": "20450"
},
{
"name": "Shell",
"bytes": "35505"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="it">
<head>
<!-- Generated by javadoc (version 1.7.0_60) on Fri Feb 13 15:29:53 CET 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>E-Index</title>
<meta name="date" content="2015-02-13">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="E-Index";
}
//-->
</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>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-4.html">Prev Letter</a></li>
<li><a href="index-6.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-5.html" target="_top">Frames</a></li>
<li><a href="index-5.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="contentContainer"><a href="index-1.html">A</a> <a href="index-2.html">B</a> <a href="index-3.html">C</a> <a href="index-4.html">D</a> <a href="index-5.html">E</a> <a href="index-6.html">G</a> <a href="index-7.html">H</a> <a href="index-8.html">I</a> <a href="index-9.html">L</a> <a href="index-10.html">M</a> <a href="index-11.html">N</a> <a href="index-12.html">O</a> <a href="index-13.html">P</a> <a href="index-14.html">Q</a> <a href="index-15.html">R</a> <a href="index-16.html">S</a> <a href="index-17.html">T</a> <a href="index-18.html">U</a> <a href="index-19.html">V</a> <a name="_E_">
<!-- -->
</a>
<h2 class="title">E</h2>
<dl>
<dt><span class="strong"><a href="../gameshop/advance/model/DescrizioneProdotto.html#equals(java.lang.Object)">equals(Object)</a></span> - Method in class gameshop.advance.model.<a href="../gameshop/advance/model/DescrizioneProdotto.html" title="class in gameshop.advance.model">DescrizioneProdotto</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../gameshop/advance/model/transazione/TipologiaCliente.html#equals(gameshop.advance.model.transazione.TipologiaCliente)">equals(TipologiaCliente)</a></span> - Method in class gameshop.advance.model.transazione.<a href="../gameshop/advance/model/transazione/TipologiaCliente.html" title="class in gameshop.advance.model.transazione">TipologiaCliente</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../gameshop/advance/utility/IDProdotto.html#equals(java.lang.Object)">equals(Object)</a></span> - Method in class gameshop.advance.utility.<a href="../gameshop/advance/utility/IDProdotto.html" title="class in gameshop.advance.utility">IDProdotto</a></dt>
<dd>
<div class="block">Controlla se l'oggetto ricevuto come parametro è un
oggetto IDProdotto.In tal caso controlla se il parametro codice
dell'oggetto ricevuto è uguale al proprio codice.Solo in tal caso
restituirà true.</div>
</dd>
<dt><span class="strong"><a href="../gameshop/advance/utility/Money.html#equals(gameshop.advance.utility.Money)">equals(Money)</a></span> - Method in class gameshop.advance.utility.<a href="../gameshop/advance/utility/Money.html" title="class in gameshop.advance.utility">Money</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../gameshop/advance/interfaces/IPrenotazione.html#evadi()">evadi()</a></span> - Method in interface gameshop.advance.interfaces.<a href="../gameshop/advance/interfaces/IPrenotazione.html" title="interface in gameshop.advance.interfaces">IPrenotazione</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../gameshop/advance/model/transazione/Prenotazione.html#evadi()">evadi()</a></span> - Method in class gameshop.advance.model.transazione.<a href="../gameshop/advance/model/transazione/Prenotazione.html" title="class in gameshop.advance.model.transazione">Prenotazione</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../gameshop/advance/model/transazione/proxies/PrenotazioneSmartProxy.html#evadi()">evadi()</a></span> - Method in class gameshop.advance.model.transazione.proxies.<a href="../gameshop/advance/model/transazione/proxies/PrenotazioneSmartProxy.html" title="class in gameshop.advance.model.transazione.proxies">PrenotazioneSmartProxy</a></dt>
<dd> </dd>
</dl>
<a href="index-1.html">A</a> <a href="index-2.html">B</a> <a href="index-3.html">C</a> <a href="index-4.html">D</a> <a href="index-5.html">E</a> <a href="index-6.html">G</a> <a href="index-7.html">H</a> <a href="index-8.html">I</a> <a href="index-9.html">L</a> <a href="index-10.html">M</a> <a href="index-11.html">N</a> <a href="index-12.html">O</a> <a href="index-13.html">P</a> <a href="index-14.html">Q</a> <a href="index-15.html">R</a> <a href="index-16.html">S</a> <a href="index-17.html">T</a> <a href="index-18.html">U</a> <a href="index-19.html">V</a> </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>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-4.html">Prev Letter</a></li>
<li><a href="index-6.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-5.html" target="_top">Frames</a></li>
<li><a href="index-5.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "4327ca3f18498f4d218ea95f94fffc2a",
"timestamp": "",
"source": "github",
"line_count": 138,
"max_line_length": 700,
"avg_line_length": 53.70289855072464,
"alnum_prop": 0.6673863176359466,
"repo_name": "GameShopAdvance/GameShop-Advance",
"id": "8dc42aab636baf77f8515419588615fe7fa63332",
"size": "7414",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/javadoc/server/index-files/index-5.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "89112"
},
{
"name": "Java",
"bytes": "689435"
},
{
"name": "Shell",
"bytes": "846"
},
{
"name": "TeX",
"bytes": "16066"
}
],
"symlink_target": ""
} |
require_relative '../../../automated_init'
context "Message" do
context "Follow" do
context "Secondary Forms" do
context "Class Form" do
source = Controls::Message.example
context "Default" do
receiver = Messaging::Message::Follow.(source, source.class)
test "Message follows the preceding message" do
assert(receiver.follows?(source))
end
test "Constructs the class" do
assert(receiver.class == source.class)
end
test "Attributes are copied" do
assert(receiver == source)
end
end
end
end
end
end
| {
"content_hash": "ef70960303cd14562d8dcf280b4365c4",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 70,
"avg_line_length": 24.296296296296298,
"alnum_prop": 0.5792682926829268,
"repo_name": "eventide-project/messaging",
"id": "a7fcd2235f2ca1f7261b30007490c9cd392531c3",
"size": "656",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/automated/message/follow/secondary_forms/class.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "173455"
},
{
"name": "Shell",
"bytes": "1938"
}
],
"symlink_target": ""
} |
package com.yubico.jaas;
import java.security.Principal;
/**
* @author Fredrik Thulin ([email protected])
*
*/
public class HttpOathOtpPrincipal implements Principal {
/** The name of the principal. */
private String name;
/** The realm of this principal. Something like a domain name. */
private String realm = null;
/**
* Constructor.
*
* @param name principal's name.
*/
public HttpOathOtpPrincipal(String name) {
this.name = name;
}
/**
* Constructor.
*
* @param id principal's name.
* @param realm Realm of id.
*/
public HttpOathOtpPrincipal(String id, String realm) {
this.name = id;
this.realm = realm;
}
/** {@inheritDoc} */
public String getName() {
if (realm != null) {
return this.name + this.realm;
}
return name;
}
/** {@inheritDoc} */
public String toString() {
return "<HttpOathOtpPrincipal>" + getName();
}
}
| {
"content_hash": "33500f5ac3042a9fa636743b1cb493eb",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 66,
"avg_line_length": 20.346938775510203,
"alnum_prop": 0.5787362086258776,
"repo_name": "Yubico/yubico-java-client",
"id": "1fd6c4df08b37af4c67d84987b2440e339c402ce",
"size": "2390",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jaas/src/main/java/com/yubico/jaas/HttpOathOtpPrincipal.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "HTML",
"bytes": "706"
},
{
"name": "Java",
"bytes": "113318"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
Index Fungorum
#### Published in
null
#### Original name
Pseudocercospora brideligena H.S. Rao, Arch. Singh & Kamal
### Remarks
null | {
"content_hash": "2e30c66667a950128e7e24f0884e8d8f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 58,
"avg_line_length": 12.461538461538462,
"alnum_prop": 0.7098765432098766,
"repo_name": "mdoering/backbone",
"id": "5ef60adec60aba272fdf362be2da4928c870d13b",
"size": "244",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Pseudocercospora/Pseudocercospora brideliigena/ Syn. Pseudocercospora brideligena/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
namespace MattJanssen\ApiResponseBundle\Serializer\Adapter;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\SerializerInterface;
/**
* Adapter for Serializing Using JMS Serializer
*
* @author Matt Janssen <[email protected]>
*/
class JmsSerializerAdapter implements SerializerAdapterInterface
{
/**
* @var SerializerInterface
*/
private $jmsSerializer;
/**
* Constructor
*
* @param SerializerInterface $serializer
*/
public function __construct(SerializerInterface $serializer)
{
$this->jmsSerializer = $serializer;
}
/**
* {@inheritdoc}
*/
public function serialize($data, array $groups = null)
{
$context = SerializationContext::create();
// Serialize null properties.
$context->setSerializeNull(true);
if ($groups !== null) {
// Always serialize the default groups. This cannot be disabled.
$groups[] = 'Default';
$context->setGroups($groups);
}
$jsonString = $this->jmsSerializer->serialize($data, 'json', $context);
return $jsonString;
}
}
| {
"content_hash": "aa69a1a4d5dc89ef0818bebb3c93d420",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 79,
"avg_line_length": 22.745098039215687,
"alnum_prop": 0.628448275862069,
"repo_name": "mattjanssen/api-response-bundle",
"id": "83de159791e4f6b93e72a863a8c400db7f38193d",
"size": "1160",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Serializer/Adapter/JmsSerializerAdapter.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "70268"
}
],
"symlink_target": ""
} |
/**
* MascotSearchBean.java
* @author Vagisha Sharma
* Oct 12, 2009
* @version 1.0
*/
package org.yeastrc.ms.domain.search.mascot.impl;
import java.util.ArrayList;
import java.util.List;
import org.yeastrc.ms.domain.search.Param;
import org.yeastrc.ms.domain.search.impl.SearchBean;
import org.yeastrc.ms.domain.search.mascot.MascotSearch;
/**
*
*/
public class MascotSearchBean extends SearchBean implements MascotSearch {
private List<Param> paramList;
public MascotSearchBean() {
paramList = new ArrayList<Param>();
}
@Override
public List<Param> getMascotParams() {
return paramList;
}
public void setMascotParams(List<Param> paramList) {
this.paramList = paramList;
}
}
| {
"content_hash": "d7b52346ae07e9347c8bb13d4870f740",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 74,
"avg_line_length": 21.083333333333332,
"alnum_prop": 0.689064558629776,
"repo_name": "yeastrc/msdapl",
"id": "4146e1784214eb9ef72a39fa61ee59f2700f79d3",
"size": "759",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MS_LIBRARY/src/org/yeastrc/ms/domain/search/mascot/impl/MascotSearchBean.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "48342"
},
{
"name": "HTML",
"bytes": "44110"
},
{
"name": "Java",
"bytes": "8380949"
},
{
"name": "JavaScript",
"bytes": "526669"
},
{
"name": "Shell",
"bytes": "39063"
}
],
"symlink_target": ""
} |
<?php
namespace Zend\Http;
use Zend\Stdlib\ErrorHandler;
use Zend\Stdlib\ResponseInterface;
/**
* HTTP Response
*
* @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6
*/
class Response extends AbstractMessage implements ResponseInterface {
/**
* #@+
* @const int Status codes
*/
const STATUS_CODE_CUSTOM = 0;
const STATUS_CODE_100 = 100;
const STATUS_CODE_101 = 101;
const STATUS_CODE_102 = 102;
const STATUS_CODE_200 = 200;
const STATUS_CODE_201 = 201;
const STATUS_CODE_202 = 202;
const STATUS_CODE_203 = 203;
const STATUS_CODE_204 = 204;
const STATUS_CODE_205 = 205;
const STATUS_CODE_206 = 206;
const STATUS_CODE_207 = 207;
const STATUS_CODE_208 = 208;
const STATUS_CODE_300 = 300;
const STATUS_CODE_301 = 301;
const STATUS_CODE_302 = 302;
const STATUS_CODE_303 = 303;
const STATUS_CODE_304 = 304;
const STATUS_CODE_305 = 305;
const STATUS_CODE_306 = 306;
const STATUS_CODE_307 = 307;
const STATUS_CODE_400 = 400;
const STATUS_CODE_401 = 401;
const STATUS_CODE_402 = 402;
const STATUS_CODE_403 = 403;
const STATUS_CODE_404 = 404;
const STATUS_CODE_405 = 405;
const STATUS_CODE_406 = 406;
const STATUS_CODE_407 = 407;
const STATUS_CODE_408 = 408;
const STATUS_CODE_409 = 409;
const STATUS_CODE_410 = 410;
const STATUS_CODE_411 = 411;
const STATUS_CODE_412 = 412;
const STATUS_CODE_413 = 413;
const STATUS_CODE_414 = 414;
const STATUS_CODE_415 = 415;
const STATUS_CODE_416 = 416;
const STATUS_CODE_417 = 417;
const STATUS_CODE_418 = 418;
const STATUS_CODE_422 = 422;
const STATUS_CODE_423 = 423;
const STATUS_CODE_424 = 424;
const STATUS_CODE_425 = 425;
const STATUS_CODE_426 = 426;
const STATUS_CODE_428 = 428;
const STATUS_CODE_429 = 429;
const STATUS_CODE_431 = 431;
const STATUS_CODE_500 = 500;
const STATUS_CODE_501 = 501;
const STATUS_CODE_502 = 502;
const STATUS_CODE_503 = 503;
const STATUS_CODE_504 = 504;
const STATUS_CODE_505 = 505;
const STATUS_CODE_506 = 506;
const STATUS_CODE_507 = 507;
const STATUS_CODE_508 = 508;
const STATUS_CODE_511 = 511;
/**
* #@-
*/
/**
*
* @var array Recommended Reason Phrases
*/
protected $recommendedReasonPhrases = array (
// INFORMATIONAL CODES
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
// SUCCESS CODES
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-status',
208 => 'Already Reported',
// REDIRECTION CODES
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => 'Switch Proxy', // Deprecated
307 => 'Temporary Redirect',
// CLIENT ERROR
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Large',
415 => 'Unsupported Media Type',
416 => 'Requested range not satisfiable',
417 => 'Expectation Failed',
418 => 'I\'m a teapot',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
425 => 'Unordered Collection',
426 => 'Upgrade Required',
428 => 'Precondition Required',
429 => 'Too Many Requests',
431 => 'Request Header Fields Too Large',
// SERVER ERROR
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
508 => 'Loop Detected',
511 => 'Network Authentication Required'
);
/**
*
* @var int Status code
*/
protected $statusCode = 200;
/**
*
* @var string|null Null means it will be looked up from the $reasonPhrase list above
*/
protected $reasonPhrase = null;
/**
* Populate object from string
*
* @param string $string
* @return Response
* @throws Exception\InvalidArgumentException
*/
public static function fromString($string) {
$lines = explode ( "\r\n", $string );
if (! is_array ( $lines ) || count ( $lines ) == 1) {
$lines = explode ( "\n", $string );
}
$firstLine = array_shift ( $lines );
$response = new static ();
$regex = '/^HTTP\/(?P<version>1\.[01]) (?P<status>\d{3})(?:[ ]+(?P<reason>.*))?$/';
$matches = array ();
if (! preg_match ( $regex, $firstLine, $matches )) {
throw new Exception\InvalidArgumentException ( 'A valid response status line was not found in the provided string' );
}
$response->version = $matches ['version'];
$response->setStatusCode ( $matches ['status'] );
$response->setReasonPhrase ( (isset ( $matches ['reason'] ) ? $matches ['reason'] : '') );
if (count ( $lines ) == 0) {
return $response;
}
$isHeader = true;
$headers = $content = array ();
while ( $lines ) {
$nextLine = array_shift ( $lines );
if ($isHeader && $nextLine == '') {
$isHeader = false;
continue;
}
if ($isHeader) {
$headers [] = $nextLine;
} else {
$content [] = $nextLine;
}
}
if ($headers) {
$response->headers = implode ( "\r\n", $headers );
}
if ($content) {
$response->setContent ( implode ( "\r\n", $content ) );
}
return $response;
}
/**
*
* @return Header\SetCookie[]
*/
public function getCookie() {
return $this->getHeaders ()->get ( 'Set-Cookie' );
}
/**
* Set HTTP status code and (optionally) message
*
* @param int $code
* @throws Exception\InvalidArgumentException
* @return Response
*/
public function setStatusCode($code) {
$const = get_class ( $this ) . '::STATUS_CODE_' . $code;
if (! is_numeric ( $code ) || ! defined ( $const )) {
$code = is_scalar ( $code ) ? $code : gettype ( $code );
throw new Exception\InvalidArgumentException ( sprintf ( 'Invalid status code provided: "%s"', $code ) );
}
$this->statusCode = ( int ) $code;
return $this;
}
/**
* Retrieve HTTP status code
*
* @return int
*/
public function getStatusCode() {
return $this->statusCode;
}
/**
*
* @param string $reasonPhrase
* @return Response
*/
public function setReasonPhrase($reasonPhrase) {
$this->reasonPhrase = trim ( $reasonPhrase );
return $this;
}
/**
* Get HTTP status message
*
* @return string
*/
public function getReasonPhrase() {
if ($this->reasonPhrase == null) {
return $this->recommendedReasonPhrases [$this->statusCode];
}
return $this->reasonPhrase;
}
/**
* Get the body of the response
*
* @return string
*/
public function getBody() {
$body = ( string ) $this->getContent ();
$transferEncoding = $this->getHeaders ()->get ( 'Transfer-Encoding' );
if (! empty ( $transferEncoding )) {
if (strtolower ( $transferEncoding->getFieldValue () ) == 'chunked') {
$body = $this->decodeChunkedBody ( $body );
}
}
$contentEncoding = $this->getHeaders ()->get ( 'Content-Encoding' );
if (! empty ( $contentEncoding )) {
$contentEncoding = $contentEncoding->getFieldValue ();
if ($contentEncoding == 'gzip') {
$body = $this->decodeGzip ( $body );
} elseif ($contentEncoding == 'deflate') {
$body = $this->decodeDeflate ( $body );
}
}
return $body;
}
/**
* Does the status code indicate a client error?
*
* @return bool
*/
public function isClientError() {
$code = $this->getStatusCode ();
return ($code < 500 && $code >= 400);
}
/**
* Is the request forbidden due to ACLs?
*
* @return bool
*/
public function isForbidden() {
return (403 == $this->getStatusCode ());
}
/**
* Is the current status "informational"?
*
* @return bool
*/
public function isInformational() {
$code = $this->getStatusCode ();
return ($code >= 100 && $code < 200);
}
/**
* Does the status code indicate the resource is not found?
*
* @return bool
*/
public function isNotFound() {
return (404 === $this->getStatusCode ());
}
/**
* Do we have a normal, OK response?
*
* @return bool
*/
public function isOk() {
return (200 === $this->getStatusCode ());
}
/**
* Does the status code reflect a server error?
*
* @return bool
*/
public function isServerError() {
$code = $this->getStatusCode ();
return (500 <= $code && 600 > $code);
}
/**
* Do we have a redirect?
*
* @return bool
*/
public function isRedirect() {
$code = $this->getStatusCode ();
return (300 <= $code && 400 > $code);
}
/**
* Was the response successful?
*
* @return bool
*/
public function isSuccess() {
$code = $this->getStatusCode ();
return (200 <= $code && 300 > $code);
}
/**
* Render the status line header
*
* @return string
*/
public function renderStatusLine() {
$status = sprintf ( 'HTTP/%s %d %s', $this->getVersion (), $this->getStatusCode (), $this->getReasonPhrase () );
return trim ( $status );
}
/**
* Render entire response as HTTP response string
*
* @return string
*/
public function toString() {
$str = $this->renderStatusLine () . "\r\n";
$str .= $this->getHeaders ()->toString ();
$str .= "\r\n";
$str .= $this->getContent ();
return $str;
}
/**
* Decode a "chunked" transfer-encoded body and return the decoded text
*
* @param string $body
* @return string
* @throws Exception\RuntimeException
*/
protected function decodeChunkedBody($body) {
$decBody = '';
while ( trim ( $body ) ) {
if (! preg_match ( "/^([\da-fA-F]+)[^\r\n]*\r\n/sm", $body, $m )) {
throw new Exception\RuntimeException ( "Error parsing body - doesn't seem to be a chunked message" );
}
$length = hexdec ( trim ( $m [1] ) );
$cut = strlen ( $m [0] );
$decBody .= substr ( $body, $cut, $length );
$body = substr ( $body, $cut + $length + 2 );
}
return $decBody;
}
/**
* Decode a gzip encoded message (when Content-encoding = gzip)
*
* Currently requires PHP with zlib support
*
* @param string $body
* @return string
* @throws Exception\RuntimeException
*/
protected function decodeGzip($body) {
if (! function_exists ( 'gzinflate' )) {
throw new Exception\RuntimeException ( 'zlib extension is required in order to decode "gzip" encoding' );
}
ErrorHandler::start ();
$return = gzinflate ( substr ( $body, 10 ) );
$test = ErrorHandler::stop ();
if ($test) {
throw new Exception\RuntimeException ( 'Error occurred during gzip inflation', 0, $test );
}
return $return;
}
/**
* Decode a zlib deflated message (when Content-encoding = deflate)
*
* Currently requires PHP with zlib support
*
* @param string $body
* @return string
* @throws Exception\RuntimeException
*/
protected function decodeDeflate($body) {
if (! function_exists ( 'gzuncompress' )) {
throw new Exception\RuntimeException ( 'zlib extension is required in order to decode "deflate" encoding' );
}
/**
* Some servers (IIS ?) send a broken deflate response, without the
* RFC-required zlib header.
*
* We try to detect the zlib header, and if it does not exist we
* teat the body is plain DEFLATE content.
*
* This method was adapted from PEAR HTTP_Request2 by (c) Alexey Borzov
*
* @link http://framework.zend.com/issues/browse/ZF-6040
*/
$zlibHeader = unpack ( 'n', substr ( $body, 0, 2 ) );
if ($zlibHeader [1] % 31 == 0) {
return gzuncompress ( $body );
}
return gzinflate ( $body );
}
}
| {
"content_hash": "2a8befd6099cd37c7cb82f5119b3d196",
"timestamp": "",
"source": "github",
"line_count": 486,
"max_line_length": 120,
"avg_line_length": 25.419753086419753,
"alnum_prop": 0.5875829690788409,
"repo_name": "ngmautri/nhungttk",
"id": "cc534896874b68635ba1dfad68c029ceeb98ec87",
"size": "12662",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/ZF2/library/Zend/Http/Response.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "363"
},
{
"name": "CSS",
"bytes": "132055"
},
{
"name": "HTML",
"bytes": "9152608"
},
{
"name": "Hack",
"bytes": "15061"
},
{
"name": "JavaScript",
"bytes": "1259151"
},
{
"name": "Less",
"bytes": "78481"
},
{
"name": "PHP",
"bytes": "18771001"
},
{
"name": "SCSS",
"bytes": "79489"
}
],
"symlink_target": ""
} |
<?php
/**
* sfWidgetFormSelectCheckbox represents an array of checkboxes.
*
* @package symfony
* @subpackage widget
* @author Fabien Potencier <[email protected]>
* @version SVN: $Id: sfWidgetFormSelectCheckbox.class.php 13324 2008-11-24 22:53:58Z FabianLange $
*/
class sfWidgetFormSelectCheckbox extends sfWidgetForm
{
/**
* Constructor.
*
* Available options:
*
* * choices: An array of possible choices (required)
* * label_separator: The separator to use between the input checkbox and the label
* * class: The class to use for the main <ul> tag
* * separator: The separator to use between each input checkbox
* * formatter: A callable to call to format the checkbox choices
* The formatter callable receives the widget and the array of inputs as arguments
* * template: The template to use when grouping option in groups (%group% %options%)
*
* @param array $options An array of options
* @param array $attributes An array of default HTML attributes
*
* @see sfWidgetForm
*/
protected function configure($options = array(), $attributes = array())
{
$this->addRequiredOption('choices');
$this->addOption('class', 'checkbox_list');
$this->addOption('label_separator', ' ');
$this->addOption('separator', "\n");
$this->addOption('formatter', array($this, 'formatter'));
$this->addOption('template', '%group% %options%');
}
/**
* @param string $name The element name
* @param string $value The value selected in this widget
* @param array $attributes An array of HTML attributes to be merged with the default HTML attributes
* @param array $errors An array of errors for the field
*
* @return string An HTML tag string
*
* @see sfWidgetForm
*/
public function render($name, $value = null, $attributes = array(), $errors = array())
{
if ('[]' != substr($name, -2))
{
$name .= '[]';
}
if (is_null($value))
{
$value = array();
}
$choices = $this->getOption('choices');
if ($choices instanceof sfCallable)
{
$choices = $choices->call();
}
// with groups?
if (count($choices) && is_array(next($choices)))
{
$parts = array();
foreach ($choices as $key => $option)
{
$parts[] = strtr($this->getOption('template'), array('%group%' => $key, '%options%' => $this->formatChoices($name, $value, $option, $attributes)));
}
return implode("\n", $parts);
}
else
{
return $this->formatChoices($name, $value, $choices, $attributes);;
}
}
protected function formatChoices($name, $value, $choices, $attributes)
{
$inputs = array();
foreach ($choices as $key => $option)
{
$baseAttributes = array(
'name' => $name,
'type' => 'checkbox',
'value' => self::escapeOnce($key),
'id' => $id = $this->generateId($name, self::escapeOnce($key)),
);
if ((is_array($value) && in_array(strval($key), $value)) || strval($key) == strval($value))
{
$baseAttributes['checked'] = 'checked';
}
$inputs[] = array(
'input' => $this->renderTag('input', array_merge($baseAttributes, $attributes)),
'label' => $this->renderContentTag('label', $option, array('for' => $id)),
);
}
return call_user_func($this->getOption('formatter'), $this, $inputs);
}
public function formatter($widget, $inputs)
{
$rows = array();
foreach ($inputs as $input)
{
$rows[] = $this->renderContentTag('li', $input['input'].$this->getOption('label_separator').$input['label']);
}
return $this->renderContentTag('ul', implode($this->getOption('separator'), $rows), array('class' => $this->getOption('class')));
}
public function __clone()
{
if ($this->getOption('choices') instanceof sfCallable)
{
$callable = $this->getOption('choices')->getCallable();
if (is_array($callable))
{
$callable[0] = $this;
$this->setOption('choices', new sfCallable($callable));
}
}
}
}
| {
"content_hash": "b8085051bc79585469c01eed6fe5980a",
"timestamp": "",
"source": "github",
"line_count": 138,
"max_line_length": 155,
"avg_line_length": 30.557971014492754,
"alnum_prop": 0.5895186151292388,
"repo_name": "tolu/liu-bookbox",
"id": "95bde6ea4d0e9ecbfc72a7e910e41860af5e827c",
"size": "4462",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/symfony/widget/sfWidgetFormSelectCheckbox.class.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "56262"
},
{
"name": "JavaScript",
"bytes": "293074"
},
{
"name": "PHP",
"bytes": "4207819"
},
{
"name": "Shell",
"bytes": "3583"
}
],
"symlink_target": ""
} |
FROM centos:centos5
MAINTAINER Taiki Sugawara <[email protected]>
RUN yum update -y
RUN yum install -y curl tar
RUN yum install -y epel-release
RUN yum groupinstall -y "Development Tools"
RUN yum install -y rpmdevtools yum-utils
RUN yum install -y buildsys-macros
RUN yum install -y git
COPY macros /etc/rpm/macros
RUN rpmdev-setuptree
| {
"content_hash": "dc27ba2b52ac8ded8c4fbfa18ad57326",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 48,
"avg_line_length": 24.428571428571427,
"alnum_prop": 0.7865497076023392,
"repo_name": "buzztaiki/docker-rpmbuildenv",
"id": "52bf98fa0a8ef82110b363d77da26bd2687f9781",
"size": "342",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "centos5/Dockerfile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "114"
}
],
"symlink_target": ""
} |
import {Component, View, bootstrap} from 'angular2/angular2';
import {routerDirectives, routerInjectables, RouteConfig, Router} from 'angular2/router';
import {StatusBoard} from './status-board/status-board';
import {StatusBoardFloating} from './status-board/status-board-floating';
import {TwitterLink} from './twitter/twitter';
@Component({
selector:'contact-manager'
})
@View({
templateUrl:'app/contact-manager.html',
directives:[routerDirectives, TwitterLink]
})
@RouteConfig([
{path: '/status-board', as:'status-board', component:StatusBoard},
{path: '/status-board-floating', as:'status-board-floating', component:StatusBoardFloating}
])
class ContactManager{
title: string;
constructor(private router:Router){
this.title = "Angular2 Databinding Examples";
}
}
bootstrap(
ContactManager,
[
routerInjectables
]
); | {
"content_hash": "3ab4673aefe366562e336e604d28ba0f",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 92,
"avg_line_length": 27,
"alnum_prop": 0.7526881720430108,
"repo_name": "jwcarroll/angular2-databinding-examples",
"id": "2997d2493e86f1b3cd31b2f6149d3a380b65957f",
"size": "894",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/contact-manager.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2192"
},
{
"name": "JavaScript",
"bytes": "1113"
},
{
"name": "TypeScript",
"bytes": "7758"
}
],
"symlink_target": ""
} |
from SpiffyWorld import Dungeon
class DungeonCollection:
"""
A collection of Dungeons
"""
def __init__(self, **kwargs):
self.dungeons = []
def add(self, dungeon):
if not isinstance(dungeon, Dungeon):
raise ValueError("dungeon must be an instance of Dungeon")
if dungeon not in self.dungeons:
self.dungeons.append(dungeon)
def get_dungeon_by_channel(self, channel):
lower_channel = channel.lower()
for dungeon in self.dungeons:
if dungeon.channel.lower() == lower_channel:
return dungeon
| {
"content_hash": "31fb77ea2416f3d6d13d96688f325975",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 70,
"avg_line_length": 24.44,
"alnum_prop": 0.6072013093289689,
"repo_name": "butterscotchstallion/SpiffyRPG",
"id": "c229618e7e1633ef8f7acb13362dc5c87c082023",
"size": "657",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SpiffyRPG/SpiffyWorld/collections/dungeon_collection.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "294210"
}
],
"symlink_target": ""
} |
'use strict';
module.exports = function(app) {
// Routing logic
// ...
var tag = require('../../app/controllers/etiquetas.server.controller');
app.route('/etiqueta/proyecto/:proyectIdtag')
.post(tag.read)
.delete(tag.delete);
app.route('/etiqueta/tarea/:taskIdtag')
.post(tag.read)
.delete(tag.delete);
//app.route('/etiqueta/:tareaId').post(tag.read);
app.route('/etiquetas/save').post(tag.create);
app.param('proyectIdtag', tag.getByProyect);
app.param('taskIdtag', tag.getByTask);
//app.param('tareaId', tag.getById);
}; | {
"content_hash": "14e0c90172526f5757c55afa82b18f54",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 72,
"avg_line_length": 26.095238095238095,
"alnum_prop": 0.6788321167883211,
"repo_name": "rmaderamnz/eon_bitacoras",
"id": "6ecb63f840be878267d70f595505243a28207b44",
"size": "548",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/routes/etiquetas.server.routes.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2097"
},
{
"name": "HTML",
"bytes": "58819"
},
{
"name": "JavaScript",
"bytes": "140128"
},
{
"name": "Shell",
"bytes": "414"
}
],
"symlink_target": ""
} |
@implementation SYAlipayDummp
@end
| {
"content_hash": "201416f681e98c25e73b1527871b8867",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 29,
"avg_line_length": 12,
"alnum_prop": 0.8333333333333334,
"repo_name": "isandboy/SYPayKit",
"id": "b392fb0e70d2c55135fe60b705b6c92a836c5334",
"size": "141",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Example/Pods/SYAlipaySDK/SYAlipaySDK/SYAlipayDummp.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "33623"
},
{
"name": "Ruby",
"bytes": "2678"
}
],
"symlink_target": ""
} |
package com.team254.frc2015.subsystems;
import com.team254.frc2015.Constants;
import com.team254.lib.util.CheesySpeedController;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.Solenoid;
public class BottomCarriage extends ElevatorCarriage {
Solenoid m_pusher;
Solenoid m_flapper;
public BottomCarriage(String name, CheesySpeedController motor,
Solenoid brake, Encoder encoder, DigitalInput home,
Solenoid pusher, Solenoid flapper) {
super(name, motor, brake, encoder, home, false);
m_pusher = pusher;
m_flapper = flapper;
}
@Override
public void reloadConstants() {
m_limits.m_min_position = Constants.kBottomCarriageMinPositionInches;
m_limits.m_max_position = Constants.kBottomCarriageMaxPositionInches;
m_limits.m_home_position = Constants.kBottomCarriageHomePositionInches;
m_limits.m_rezero_position = Constants.kBottomCarriageReZeroPositionInches;
super.reloadConstants();
}
public void setPusherExtended(boolean extended) {
m_pusher.set(extended);
}
public boolean getPusherExtended() {
return m_pusher.get();
}
public void setFlapperOpen(boolean open) {
m_flapper.set(!open);
}
public boolean getFlapperOpen() {
return m_flapper.get();
}
}
| {
"content_hash": "50ee62b7adc489e4283d89e419a5a66a",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 83,
"avg_line_length": 30.404255319148938,
"alnum_prop": 0.6857942617214835,
"repo_name": "Team254/FRC-2015",
"id": "0e2a237f86d22c492548ed4c2364f46188acf2d4",
"size": "1429",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/team254/frc2015/subsystems/BottomCarriage.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "525"
},
{
"name": "HTML",
"bytes": "6523"
},
{
"name": "Java",
"bytes": "237152"
},
{
"name": "JavaScript",
"bytes": "259672"
},
{
"name": "Shell",
"bytes": "81"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "66f5511ebb3739b9f29580e033304539",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "38042e674e069d2d590f202c96a65b44253c44b9",
"size": "199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Convolvulaceae/Ipomoea/Ipomoea blanchetii/Ipomoea blanchetii pubescens/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<ion-header>
<ion-navbar>
<ion-title>
Crear Minga
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item>
<ion-label floating>Titulo de la Minga</ion-label>
<ion-input type="text"></ion-input>
</ion-item>
<ion-item>
<ion-label>¿Sera Publica?</ion-label>
<ion-toggle toggle-class="toggle-positive"></ion-toggle>
</ion-item>
<ion-item>
<label class="item item-select">
<span class="input-label">Categoria:</span>
<select>
<option>Mover Cosas</option>
<option>Reparacion</option>
<option>Construccion</option>
<option>Beneficio</option>
<option>Conocimiento</option>
</select>
</label>
</ion-item>
<ion-item>
<label class="item item-select">
<span class="input-label">Ciudad:</span>
<select>
<option>Quellon</option>
<option>Castro</option>
<option>Pto Montt</option>
</select>
</label>
</ion-item>
<ion-item>
<label class="item item-select">
<span class="input-label">Cantidad de Personas</span>
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</label>
</ion-item>
<ion-label>Recompensas</ion-label>
<ion-item>
<ion-label>Cerveza</ion-label>
<ion-checkbox></ion-checkbox>
</ion-item>
<ion-item>
<ion-label>Una Copa</ion-label>
<ion-checkbox></ion-checkbox>
</ion-item>
<ion-item>
<ion-label>Conversacion</ion-label>
<ion-checkbox></ion-checkbox>
</ion-item>
<ion-item>
<ion-label>Servicio</ion-label>
<ion-checkbox></ion-checkbox>
</ion-item>
</ion-list>
<button ion-button>Crear Minga!</button>
</ion-content>
| {
"content_hash": "83af8117177f7283ed848f2cdcdc770b",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 58,
"avg_line_length": 18.255555555555556,
"alnum_prop": 0.6329884357881923,
"repo_name": "MingApp-Organization/mobile",
"id": "1a6c25448ade7a9f163e702e3b86ee7872d30bf6",
"size": "1644",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/pages/about/about.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2964"
},
{
"name": "HTML",
"bytes": "5163"
},
{
"name": "JavaScript",
"bytes": "715"
},
{
"name": "TypeScript",
"bytes": "3298"
}
],
"symlink_target": ""
} |
package com.cloud.api.commands;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseCmd;
import com.cloud.api.BaseListCmd;
import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.PlugService;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.ListResponse;
import com.cloud.api.response.NiciraNvpDeviceResponse;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.NiciraNvpDeviceVO;
import com.cloud.network.element.NiciraNvpElementService;
import com.cloud.utils.exception.CloudRuntimeException;
@Implementation(responseObject=NiciraNvpDeviceResponse.class, description="Lists Nicira NVP devices")
public class ListNiciraNvpDevicesCmd extends BaseListCmd {
private static final Logger s_logger = Logger.getLogger(ListNiciraNvpDevicesCmd.class.getName());
private static final String s_name = "listniciranvpdevices";
@PlugService NiciraNvpElementService _niciraNvpElementService;
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@IdentityMapper(entityTableName="physical_network")
@Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID")
private Long physicalNetworkId;
@IdentityMapper(entityTableName="external_nicira_nvp_devices")
@Parameter(name=ApiConstants.NICIRA_NVP_DEVICE_ID, type=CommandType.LONG, description="nicira nvp device ID")
private Long niciraNvpDeviceId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Long getNiciraNvpDeviceId() {
return niciraNvpDeviceId;
}
public Long getPhysicalNetworkId() {
return physicalNetworkId;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException {
try {
List<NiciraNvpDeviceVO> niciraDevices = _niciraNvpElementService.listNiciraNvpDevices(this);
ListResponse<NiciraNvpDeviceResponse> response = new ListResponse<NiciraNvpDeviceResponse>();
List<NiciraNvpDeviceResponse> niciraDevicesResponse = new ArrayList<NiciraNvpDeviceResponse>();
if (niciraDevices != null && !niciraDevices.isEmpty()) {
for (NiciraNvpDeviceVO niciraDeviceVO : niciraDevices) {
NiciraNvpDeviceResponse niciraDeviceResponse = _niciraNvpElementService.createNiciraNvpDeviceResponse(niciraDeviceVO);
niciraDevicesResponse.add(niciraDeviceResponse);
}
}
response.setResponses(niciraDevicesResponse);
response.setResponseName(getCommandName());
this.setResponseObject(response);
} catch (InvalidParameterValueException invalidParamExcp) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage());
} catch (CloudRuntimeException runtimeExcp) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage());
}
}
@Override
public String getCommandName() {
return s_name;
}
}
| {
"content_hash": "798a3c410ae859f1faeb10fb2256558b",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 173,
"avg_line_length": 43.7,
"alnum_prop": 0.6699720315280956,
"repo_name": "argv0/cloudstack",
"id": "f9c157d9feb1d75f9ea15ba839222290681badf8",
"size": "4734",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "52484672"
},
{
"name": "JavaScript",
"bytes": "1913801"
},
{
"name": "Perl",
"bytes": "824212"
},
{
"name": "Python",
"bytes": "2076246"
},
{
"name": "Ruby",
"bytes": "2166"
},
{
"name": "Shell",
"bytes": "445096"
}
],
"symlink_target": ""
} |
<?php
namespace Iglesys\Bundle\GanadosBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class IglesysGanadosBundle extends Bundle
{
}
| {
"content_hash": "8287a73f38ac21270e4d91294d662327",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 47,
"avg_line_length": 15.88888888888889,
"alnum_prop": 0.8181818181818182,
"repo_name": "Futrille/iglesys",
"id": "c57d8d419001a17d3fac338e769c553a87302d25",
"size": "143",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Iglesys/Bundle/GanadosBundle/IglesysGanadosBundle.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "2403"
},
{
"name": "Batchfile",
"bytes": "52"
},
{
"name": "CSS",
"bytes": "11220"
},
{
"name": "HTML",
"bytes": "473590"
},
{
"name": "JavaScript",
"bytes": "3760"
},
{
"name": "PHP",
"bytes": "176120"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.Data.Json;
using Windows.Storage;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
// The data model defined by this file serves as a representative example of a strongly-typed
// model. The property names chosen coincide with data bindings in the standard item templates.
//
// Applications may use this model as a starting point and build on it, or discard it entirely and
// replace it with something appropriate to their needs. If using this model, you might improve app
// responsiveness by initiating the data loading task in the code behind for App.xaml when the app
// is first launched.
namespace WinRTUI.Data
{
/// <summary>
/// Generic item data model.
/// </summary>
public class SampleDataItem
{
public SampleDataItem(String uniqueId, String title, String subtitle, String imagePath, String description, String content)
{
this.UniqueId = uniqueId;
this.Title = title;
this.Subtitle = subtitle;
this.Description = description;
this.ImagePath = imagePath;
this.Content = content;
}
public string UniqueId { get; private set; }
public string Title { get; private set; }
public string Subtitle { get; private set; }
public string Description { get; private set; }
public string ImagePath { get; private set; }
public string Content { get; private set; }
public override string ToString()
{
return this.Title;
}
}
/// <summary>
/// Generic group data model.
/// </summary>
public class SampleDataGroup
{
public SampleDataGroup(String uniqueId, String title, String subtitle, String imagePath, String description)
{
this.UniqueId = uniqueId;
this.Title = title;
this.Subtitle = subtitle;
this.Description = description;
this.ImagePath = imagePath;
this.Items = new ObservableCollection<SampleDataItem>();
}
public string UniqueId { get; private set; }
public string Title { get; private set; }
public string Subtitle { get; set; }
public string Description { get; private set; }
public string ImagePath { get; private set; }
public ObservableCollection<SampleDataItem> Items { get; private set; }
public override string ToString()
{
return this.Title;
}
}
/// <summary>
/// Creates a collection of groups and items with content read from a static json file.
///
/// SampleDataSource initializes with data read from a static json file included in the
/// project. This provides sample data at both design-time and run-time.
/// </summary>
public sealed class SampleDataSource
{
private static SampleDataSource _sampleDataSource = new SampleDataSource();
private ObservableCollection<SampleDataGroup> _groups = new ObservableCollection<SampleDataGroup>();
public ObservableCollection<SampleDataGroup> Groups
{
get { return this._groups; }
}
public static async Task<IEnumerable<SampleDataGroup>> GetGroupsAsync()
{
await _sampleDataSource.GetSampleDataAsync();
return _sampleDataSource.Groups;
}
public static async Task<SampleDataGroup> GetGroupAsync(string uniqueId)
{
await _sampleDataSource.GetSampleDataAsync();
// Simple linear search is acceptable for small data sets
var matches = _sampleDataSource.Groups.Where((group) => group.UniqueId.Equals(uniqueId));
if (matches.Count() == 1) return matches.First();
return null;
}
public static async Task<SampleDataItem> GetItemAsync(string uniqueId)
{
await _sampleDataSource.GetSampleDataAsync();
// Simple linear search is acceptable for small data sets
var matches = _sampleDataSource.Groups.SelectMany(group => group.Items).Where((item) => item.UniqueId.Equals(uniqueId));
if (matches.Count() == 1) return matches.First();
return null;
}
private async Task GetSampleDataAsync()
{
if (this._groups.Count != 0)
return;
Uri dataUri = new Uri("ms-appx:///DataModel/SampleData.json");
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);
string jsonText = await FileIO.ReadTextAsync(file);
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonArray jsonArray = jsonObject["Groups"].GetArray();
foreach (JsonValue groupValue in jsonArray)
{
JsonObject groupObject = groupValue.GetObject();
SampleDataGroup group = new SampleDataGroup(groupObject["UniqueId"].GetString(),
groupObject["Title"].GetString(),
groupObject["Subtitle"].GetString(),
groupObject["ImagePath"].GetString(),
groupObject["Description"].GetString());
foreach (JsonValue itemValue in groupObject["Items"].GetArray())
{
JsonObject itemObject = itemValue.GetObject();
group.Items.Add(new SampleDataItem(itemObject["UniqueId"].GetString(),
itemObject["Title"].GetString(),
itemObject["Subtitle"].GetString(),
itemObject["ImagePath"].GetString(),
itemObject["Description"].GetString(),
itemObject["Content"].GetString()));
}
this.Groups.Add(group);
}
}
}
} | {
"content_hash": "05d1a77a06f283a4c55e692e27074024",
"timestamp": "",
"source": "github",
"line_count": 153,
"max_line_length": 132,
"avg_line_length": 41.209150326797385,
"alnum_prop": 0.5854084060269628,
"repo_name": "BrettJaner/csla",
"id": "5ecc603dc829c405fb6794a51873119dd642d98f",
"size": "6307",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Samples/NET/cs/ProjectTracker/WinRtUI/DataModel/SampleDataSource.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "13295"
},
{
"name": "Batchfile",
"bytes": "1434"
},
{
"name": "C#",
"bytes": "4395424"
},
{
"name": "HTML",
"bytes": "52832"
},
{
"name": "PowerShell",
"bytes": "25361"
},
{
"name": "Shell",
"bytes": "533"
},
{
"name": "Visual Basic",
"bytes": "42440"
}
],
"symlink_target": ""
} |
#pragma once
#include <aws/workmail/WorkMail_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/workmail/model/MemberType.h>
#include <aws/workmail/model/EntityState.h>
#include <aws/core/utils/DateTime.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace WorkMail
{
namespace Model
{
/**
* <p>The representation of a user or group.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/workmail-2017-10-01/Member">AWS API
* Reference</a></p>
*/
class AWS_WORKMAIL_API Member
{
public:
Member();
Member(Aws::Utils::Json::JsonView jsonValue);
Member& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The identifier of the member.</p>
*/
inline const Aws::String& GetId() const{ return m_id; }
/**
* <p>The identifier of the member.</p>
*/
inline bool IdHasBeenSet() const { return m_idHasBeenSet; }
/**
* <p>The identifier of the member.</p>
*/
inline void SetId(const Aws::String& value) { m_idHasBeenSet = true; m_id = value; }
/**
* <p>The identifier of the member.</p>
*/
inline void SetId(Aws::String&& value) { m_idHasBeenSet = true; m_id = std::move(value); }
/**
* <p>The identifier of the member.</p>
*/
inline void SetId(const char* value) { m_idHasBeenSet = true; m_id.assign(value); }
/**
* <p>The identifier of the member.</p>
*/
inline Member& WithId(const Aws::String& value) { SetId(value); return *this;}
/**
* <p>The identifier of the member.</p>
*/
inline Member& WithId(Aws::String&& value) { SetId(std::move(value)); return *this;}
/**
* <p>The identifier of the member.</p>
*/
inline Member& WithId(const char* value) { SetId(value); return *this;}
/**
* <p>The name of the member.</p>
*/
inline const Aws::String& GetName() const{ return m_name; }
/**
* <p>The name of the member.</p>
*/
inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }
/**
* <p>The name of the member.</p>
*/
inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }
/**
* <p>The name of the member.</p>
*/
inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }
/**
* <p>The name of the member.</p>
*/
inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }
/**
* <p>The name of the member.</p>
*/
inline Member& WithName(const Aws::String& value) { SetName(value); return *this;}
/**
* <p>The name of the member.</p>
*/
inline Member& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}
/**
* <p>The name of the member.</p>
*/
inline Member& WithName(const char* value) { SetName(value); return *this;}
/**
* <p>A member can be a user or group.</p>
*/
inline const MemberType& GetType() const{ return m_type; }
/**
* <p>A member can be a user or group.</p>
*/
inline bool TypeHasBeenSet() const { return m_typeHasBeenSet; }
/**
* <p>A member can be a user or group.</p>
*/
inline void SetType(const MemberType& value) { m_typeHasBeenSet = true; m_type = value; }
/**
* <p>A member can be a user or group.</p>
*/
inline void SetType(MemberType&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }
/**
* <p>A member can be a user or group.</p>
*/
inline Member& WithType(const MemberType& value) { SetType(value); return *this;}
/**
* <p>A member can be a user or group.</p>
*/
inline Member& WithType(MemberType&& value) { SetType(std::move(value)); return *this;}
/**
* <p>The state of the member, which can be ENABLED, DISABLED, or DELETED.</p>
*/
inline const EntityState& GetState() const{ return m_state; }
/**
* <p>The state of the member, which can be ENABLED, DISABLED, or DELETED.</p>
*/
inline bool StateHasBeenSet() const { return m_stateHasBeenSet; }
/**
* <p>The state of the member, which can be ENABLED, DISABLED, or DELETED.</p>
*/
inline void SetState(const EntityState& value) { m_stateHasBeenSet = true; m_state = value; }
/**
* <p>The state of the member, which can be ENABLED, DISABLED, or DELETED.</p>
*/
inline void SetState(EntityState&& value) { m_stateHasBeenSet = true; m_state = std::move(value); }
/**
* <p>The state of the member, which can be ENABLED, DISABLED, or DELETED.</p>
*/
inline Member& WithState(const EntityState& value) { SetState(value); return *this;}
/**
* <p>The state of the member, which can be ENABLED, DISABLED, or DELETED.</p>
*/
inline Member& WithState(EntityState&& value) { SetState(std::move(value)); return *this;}
/**
* <p>The date indicating when the member was enabled for WorkMail use.</p>
*/
inline const Aws::Utils::DateTime& GetEnabledDate() const{ return m_enabledDate; }
/**
* <p>The date indicating when the member was enabled for WorkMail use.</p>
*/
inline bool EnabledDateHasBeenSet() const { return m_enabledDateHasBeenSet; }
/**
* <p>The date indicating when the member was enabled for WorkMail use.</p>
*/
inline void SetEnabledDate(const Aws::Utils::DateTime& value) { m_enabledDateHasBeenSet = true; m_enabledDate = value; }
/**
* <p>The date indicating when the member was enabled for WorkMail use.</p>
*/
inline void SetEnabledDate(Aws::Utils::DateTime&& value) { m_enabledDateHasBeenSet = true; m_enabledDate = std::move(value); }
/**
* <p>The date indicating when the member was enabled for WorkMail use.</p>
*/
inline Member& WithEnabledDate(const Aws::Utils::DateTime& value) { SetEnabledDate(value); return *this;}
/**
* <p>The date indicating when the member was enabled for WorkMail use.</p>
*/
inline Member& WithEnabledDate(Aws::Utils::DateTime&& value) { SetEnabledDate(std::move(value)); return *this;}
/**
* <p>The date indicating when the member was disabled from WorkMail use.</p>
*/
inline const Aws::Utils::DateTime& GetDisabledDate() const{ return m_disabledDate; }
/**
* <p>The date indicating when the member was disabled from WorkMail use.</p>
*/
inline bool DisabledDateHasBeenSet() const { return m_disabledDateHasBeenSet; }
/**
* <p>The date indicating when the member was disabled from WorkMail use.</p>
*/
inline void SetDisabledDate(const Aws::Utils::DateTime& value) { m_disabledDateHasBeenSet = true; m_disabledDate = value; }
/**
* <p>The date indicating when the member was disabled from WorkMail use.</p>
*/
inline void SetDisabledDate(Aws::Utils::DateTime&& value) { m_disabledDateHasBeenSet = true; m_disabledDate = std::move(value); }
/**
* <p>The date indicating when the member was disabled from WorkMail use.</p>
*/
inline Member& WithDisabledDate(const Aws::Utils::DateTime& value) { SetDisabledDate(value); return *this;}
/**
* <p>The date indicating when the member was disabled from WorkMail use.</p>
*/
inline Member& WithDisabledDate(Aws::Utils::DateTime&& value) { SetDisabledDate(std::move(value)); return *this;}
private:
Aws::String m_id;
bool m_idHasBeenSet = false;
Aws::String m_name;
bool m_nameHasBeenSet = false;
MemberType m_type;
bool m_typeHasBeenSet = false;
EntityState m_state;
bool m_stateHasBeenSet = false;
Aws::Utils::DateTime m_enabledDate;
bool m_enabledDateHasBeenSet = false;
Aws::Utils::DateTime m_disabledDate;
bool m_disabledDateHasBeenSet = false;
};
} // namespace Model
} // namespace WorkMail
} // namespace Aws
| {
"content_hash": "100c2ee5e62fea4ba702fb01bdc58783",
"timestamp": "",
"source": "github",
"line_count": 268,
"max_line_length": 133,
"avg_line_length": 30.175373134328357,
"alnum_prop": 0.624953629281563,
"repo_name": "aws/aws-sdk-cpp",
"id": "a1cc35dd818b2c197e516dd09bca17e7070113c9",
"size": "8206",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "aws-cpp-sdk-workmail/include/aws/workmail/model/Member.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "309797"
},
{
"name": "C++",
"bytes": "476866144"
},
{
"name": "CMake",
"bytes": "1245180"
},
{
"name": "Dockerfile",
"bytes": "11688"
},
{
"name": "HTML",
"bytes": "8056"
},
{
"name": "Java",
"bytes": "413602"
},
{
"name": "Python",
"bytes": "79245"
},
{
"name": "Shell",
"bytes": "9246"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using log4net;
using MySql.Data.MySqlClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Data;
namespace OpenSim.Data.MySQL
{
public class MySQLXAssetData : IXAssetDataPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
/// <summary>
/// Number of days that must pass before we update the access time on an asset when it has been fetched.
/// </summary>
private const int DaysBetweenAccessTimeUpdates = 30;
private bool m_enableCompression = false;
private string m_connectionString;
/// <summary>
/// We can reuse this for all hashing since all methods are single-threaded through m_dbBLock
/// </summary>
private HashAlgorithm hasher = new SHA256CryptoServiceProvider();
#region IPlugin Members
public string Version { get { return "1.0.0.0"; } }
/// <summary>
/// <para>Initialises Asset interface</para>
/// <para>
/// <list type="bullet">
/// <item>Loads and initialises the MySQL storage plugin.</item>
/// <item>Warns and uses the obsolete mysql_connection.ini if connect string is empty.</item>
/// <item>Check for migration</item>
/// </list>
/// </para>
/// </summary>
/// <param name="connect">connect string</param>
public void Initialise(string connect)
{
m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
m_log.ErrorFormat("[MYSQL XASSETDATA]: THIS PLUGIN IS STRICTLY EXPERIMENTAL.");
m_log.ErrorFormat("[MYSQL XASSETDATA]: DO NOT USE FOR ANY DATA THAT YOU DO NOT MIND LOSING.");
m_log.ErrorFormat("[MYSQL XASSETDATA]: DATABASE TABLES CAN CHANGE AT ANY TIME, CAUSING EXISTING DATA TO BE LOST.");
m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
m_connectionString = connect;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
Migration m = new Migration(dbcon, Assembly, "XAssetStore");
m.Update();
}
}
public void Initialise()
{
throw new NotImplementedException();
}
public void Dispose() { }
/// <summary>
/// The name of this DB provider
/// </summary>
public string Name
{
get { return "MySQL XAsset storage engine"; }
}
#endregion
#region IAssetDataPlugin Members
/// <summary>
/// Fetch Asset <paramref name="assetID"/> from database
/// </summary>
/// <param name="assetID">Asset UUID to fetch</param>
/// <returns>Return the asset</returns>
/// <remarks>On failure : throw an exception and attempt to reconnect to database</remarks>
public AssetBase GetAsset(UUID assetID)
{
// m_log.DebugFormat("[MYSQL XASSET DATA]: Looking for asset {0}", assetID);
AssetBase asset = null;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = new MySqlCommand(
"SELECT Name, Description, AccessTime, AssetType, Local, Temporary, AssetFlags, CreatorID, Data FROM XAssetsMeta JOIN XAssetsData ON XAssetsMeta.Hash = XAssetsData.Hash WHERE ID=?ID",
dbcon))
{
cmd.Parameters.AddWithValue("?ID", assetID.ToString());
try
{
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (dbReader.Read())
{
asset = new AssetBase(assetID, (string)dbReader["Name"], (sbyte)dbReader["AssetType"], dbReader["CreatorID"].ToString());
asset.Data = (byte[])dbReader["Data"];
asset.Description = (string)dbReader["Description"];
string local = dbReader["Local"].ToString();
if (local.Equals("1") || local.Equals("true", StringComparison.InvariantCultureIgnoreCase))
asset.Local = true;
else
asset.Local = false;
asset.Temporary = Convert.ToBoolean(dbReader["Temporary"]);
asset.Flags = (AssetFlags)Convert.ToInt32(dbReader["AssetFlags"]);
if (m_enableCompression)
{
using (GZipStream decompressionStream = new GZipStream(new MemoryStream(asset.Data), CompressionMode.Decompress))
{
MemoryStream outputStream = new MemoryStream();
WebUtil.CopyStream(decompressionStream, outputStream, int.MaxValue);
// int compressedLength = asset.Data.Length;
asset.Data = outputStream.ToArray();
// m_log.DebugFormat(
// "[XASSET DB]: Decompressed {0} {1} to {2} bytes from {3}",
// asset.ID, asset.Name, asset.Data.Length, compressedLength);
}
}
UpdateAccessTime(asset.Metadata, (int)dbReader["AccessTime"]);
}
}
}
catch (Exception e)
{
m_log.Error(string.Format("[MYSQL XASSET DATA]: Failure fetching asset {0}", assetID), e);
}
}
}
return asset;
}
/// <summary>
/// Create an asset in database, or update it if existing.
/// </summary>
/// <param name="asset">Asset UUID to create</param>
/// <remarks>On failure : Throw an exception and attempt to reconnect to database</remarks>
public void StoreAsset(AssetBase asset)
{
// m_log.DebugFormat("[XASSETS DB]: Storing asset {0} {1}", asset.Name, asset.ID);
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlTransaction transaction = dbcon.BeginTransaction())
{
string assetName = asset.Name;
if (asset.Name.Length > AssetBase.MAX_ASSET_NAME)
{
assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME);
m_log.WarnFormat(
"[XASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Name, asset.ID, asset.Name.Length, assetName.Length);
}
string assetDescription = asset.Description;
if (asset.Description.Length > AssetBase.MAX_ASSET_DESC)
{
assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC);
m_log.WarnFormat(
"[XASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
}
if (m_enableCompression)
{
MemoryStream outputStream = new MemoryStream();
using (GZipStream compressionStream = new GZipStream(outputStream, CompressionMode.Compress, false))
{
// Console.WriteLine(WebUtil.CopyTo(new MemoryStream(asset.Data), compressionStream, int.MaxValue));
// We have to close the compression stream in order to make sure it writes everything out to the underlying memory output stream.
compressionStream.Close();
byte[] compressedData = outputStream.ToArray();
asset.Data = compressedData;
}
}
byte[] hash = hasher.ComputeHash(asset.Data);
// m_log.DebugFormat(
// "[XASSET DB]: Compressed data size for {0} {1}, hash {2} is {3}",
// asset.ID, asset.Name, hash, compressedData.Length);
try
{
using (MySqlCommand cmd =
new MySqlCommand(
"replace INTO XAssetsMeta(ID, Hash, Name, Description, AssetType, Local, Temporary, CreateTime, AccessTime, AssetFlags, CreatorID)" +
"VALUES(?ID, ?Hash, ?Name, ?Description, ?AssetType, ?Local, ?Temporary, ?CreateTime, ?AccessTime, ?AssetFlags, ?CreatorID)",
dbcon))
{
// create unix epoch time
int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow);
cmd.Parameters.AddWithValue("?ID", asset.ID);
cmd.Parameters.AddWithValue("?Hash", hash);
cmd.Parameters.AddWithValue("?Name", assetName);
cmd.Parameters.AddWithValue("?Description", assetDescription);
cmd.Parameters.AddWithValue("?AssetType", asset.Type);
cmd.Parameters.AddWithValue("?Local", asset.Local);
cmd.Parameters.AddWithValue("?Temporary", asset.Temporary);
cmd.Parameters.AddWithValue("?CreateTime", now);
cmd.Parameters.AddWithValue("?AccessTime", now);
cmd.Parameters.AddWithValue("?CreatorID", asset.Metadata.CreatorID);
cmd.Parameters.AddWithValue("?AssetFlags", (int)asset.Flags);
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[ASSET DB]: MySQL failure creating asset metadata {0} with name \"{1}\". Error: {2}",
asset.FullID, asset.Name, e.Message);
transaction.Rollback();
return;
}
if (!ExistsData(dbcon, transaction, hash))
{
try
{
using (MySqlCommand cmd =
new MySqlCommand(
"INSERT INTO XAssetsData(Hash, Data) VALUES(?Hash, ?Data)",
dbcon))
{
cmd.Parameters.AddWithValue("?Hash", hash);
cmd.Parameters.AddWithValue("?Data", asset.Data);
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[XASSET DB]: MySQL failure creating asset data {0} with name \"{1}\". Error: {2}",
asset.FullID, asset.Name, e.Message);
transaction.Rollback();
return;
}
}
transaction.Commit();
}
}
}
/// <summary>
/// Updates the access time of the asset if it was accessed above a given threshhold amount of time.
/// </summary>
/// <remarks>
/// This gives us some insight into assets which haven't ben accessed for a long period. This is only done
/// over the threshold time to avoid excessive database writes as assets are fetched.
/// </remarks>
/// <param name='asset'></param>
/// <param name='accessTime'></param>
private void UpdateAccessTime(AssetMetadata assetMetadata, int accessTime)
{
DateTime now = DateTime.UtcNow;
if ((now - Utils.UnixTimeToDateTime(accessTime)).TotalDays < DaysBetweenAccessTimeUpdates)
return;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
MySqlCommand cmd =
new MySqlCommand("update XAssetsMeta set AccessTime=?AccessTime where ID=?ID", dbcon);
try
{
using (cmd)
{
// create unix epoch time
cmd.Parameters.AddWithValue("?ID", assetMetadata.ID);
cmd.Parameters.AddWithValue("?AccessTime", (int)Utils.DateTimeToUnixTime(now));
cmd.ExecuteNonQuery();
}
}
catch (Exception)
{
m_log.ErrorFormat(
"[XASSET MYSQL DB]: Failure updating access_time for asset {0} with name {1}",
assetMetadata.ID, assetMetadata.Name);
}
}
}
/// <summary>
/// We assume we already have the m_dbLock.
/// </summary>
/// TODO: need to actually use the transaction.
/// <param name="dbcon"></param>
/// <param name="transaction"></param>
/// <param name="hash"></param>
/// <returns></returns>
private bool ExistsData(MySqlConnection dbcon, MySqlTransaction transaction, byte[] hash)
{
// m_log.DebugFormat("[ASSETS DB]: Checking for asset {0}", uuid);
bool exists = false;
using (MySqlCommand cmd = new MySqlCommand("SELECT Hash FROM XAssetsData WHERE Hash=?Hash", dbcon))
{
cmd.Parameters.AddWithValue("?Hash", hash);
try
{
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (dbReader.Read())
{
// m_log.DebugFormat("[ASSETS DB]: Found asset {0}", uuid);
exists = true;
}
}
}
catch (Exception e)
{
m_log.ErrorFormat(
"[XASSETS DB]: MySql failure in ExistsData fetching hash {0}. Exception {1}{2}",
hash, e.Message, e.StackTrace);
}
}
return exists;
}
/// <summary>
/// Check if the assets exist in the database.
/// </summary>
/// <param name="uuids">The asset UUID's</param>
/// <returns>For each asset: true if it exists, false otherwise</returns>
public bool[] AssetsExist(UUID[] uuids)
{
if (uuids.Length == 0)
return new bool[0];
HashSet<UUID> exists = new HashSet<UUID>();
string ids = "'" + string.Join("','", uuids) + "'";
string sql = string.Format("SELECT ID FROM assets WHERE ID IN ({0})", ids);
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = new MySqlCommand(sql, dbcon))
{
using (MySqlDataReader dbReader = cmd.ExecuteReader())
{
while (dbReader.Read())
{
UUID id = DBGuid.FromDB(dbReader["ID"]);
exists.Add(id);
}
}
}
}
bool[] results = new bool[uuids.Length];
for (int i = 0; i < uuids.Length; i++)
results[i] = exists.Contains(uuids[i]);
return results;
}
/// <summary>
/// Returns a list of AssetMetadata objects. The list is a subset of
/// the entire data set offset by <paramref name="start" /> containing
/// <paramref name="count" /> elements.
/// </summary>
/// <param name="start">The number of results to discard from the total data set.</param>
/// <param name="count">The number of rows the returned list should contain.</param>
/// <returns>A list of AssetMetadata objects.</returns>
public List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
{
List<AssetMetadata> retList = new List<AssetMetadata>(count);
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using(MySqlCommand cmd = new MySqlCommand("SELECT Name, Description, AccessTime, AssetType, Temporary, ID, AssetFlags, CreatorID FROM XAssetsMeta LIMIT ?start, ?count",dbcon))
{
cmd.Parameters.AddWithValue("?start",start);
cmd.Parameters.AddWithValue("?count", count);
try
{
using (MySqlDataReader dbReader = cmd.ExecuteReader())
{
while (dbReader.Read())
{
AssetMetadata metadata = new AssetMetadata();
metadata.Name = (string)dbReader["Name"];
metadata.Description = (string)dbReader["Description"];
metadata.Type = (sbyte)dbReader["AssetType"];
metadata.Temporary = Convert.ToBoolean(dbReader["Temporary"]); // Not sure if this is correct.
metadata.Flags = (AssetFlags)Convert.ToInt32(dbReader["AssetFlags"]);
metadata.FullID = DBGuid.FromDB(dbReader["ID"]);
metadata.CreatorID = dbReader["CreatorID"].ToString();
// We'll ignore this for now - it appears unused!
// metadata.SHA1 = dbReader["hash"]);
UpdateAccessTime(metadata, (int)dbReader["AccessTime"]);
retList.Add(metadata);
}
}
}
catch (Exception e)
{
m_log.Error("[XASSETS DB]: MySql failure fetching asset set" + Environment.NewLine + e.ToString());
}
}
}
return retList;
}
public bool Delete(string id)
{
// m_log.DebugFormat("[XASSETS DB]: Deleting asset {0}", id);
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = new MySqlCommand("delete from XAssetsMeta where ID=?ID", dbcon))
{
cmd.Parameters.AddWithValue("?ID", id);
cmd.ExecuteNonQuery();
}
// TODO: How do we deal with data from deleted assets? Probably not easily reapable unless we
// keep a reference count (?)
}
return true;
}
#endregion
}
}
| {
"content_hash": "a82d5670d56e7d3a64afdb466ab6f23e",
"timestamp": "",
"source": "github",
"line_count": 480,
"max_line_length": 203,
"avg_line_length": 44.02291666666667,
"alnum_prop": 0.4746107614405376,
"repo_name": "TomDataworks/opensim",
"id": "2c6acdef32d4c02a5003c969f7d610efdf53df9e",
"size": "22748",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OpenSim/Data/MySQL/MySQLXAssetData.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "3307"
},
{
"name": "C#",
"bytes": "21751059"
},
{
"name": "CSS",
"bytes": "1683"
},
{
"name": "HTML",
"bytes": "9919"
},
{
"name": "JavaScript",
"bytes": "556"
},
{
"name": "LSL",
"bytes": "36962"
},
{
"name": "Makefile",
"bytes": "1232"
},
{
"name": "NSIS",
"bytes": "6208"
},
{
"name": "PLpgSQL",
"bytes": "599"
},
{
"name": "Perl",
"bytes": "3578"
},
{
"name": "Python",
"bytes": "5053"
},
{
"name": "Ruby",
"bytes": "1111"
},
{
"name": "Shell",
"bytes": "2979"
}
],
"symlink_target": ""
} |
const String BaseKey = "\\Software\\Roel Schroeven\\VolBalCon";
const String PresetsKey = "\\Software\\Roel Schroeven\\VolBalCon\\Presets";
using rsutil::JoinPaths;
using rsutil::PrintF;
void TPresets::Load()
{
std::auto_ptr<TRegistry> Registry(new TRegistry);
Registry->RootKey = HKEY_CURRENT_USER;
if (!Registry->OpenKeyReadOnly(PresetsKey))
return;
std::auto_ptr<TStrings> PresetNames(new TStringList);
Registry->GetKeyNames(PresetNames.get());
for (int i = 0; i < PresetNames->Count; ++i)
{
String Name = PresetNames->Strings[i];
if (!Registry->OpenKeyReadOnly(JoinPaths(PresetsKey, Name)))
continue;
TPreset Preset;
Preset.Master = 0.01 * Registry->ReadInteger("Master");
int ChannelIndex = 0;
while (true)
{
String ValueName = PrintF(L"Channel%d", ChannelIndex);
if (!Registry->ValueExists(ValueName))
break;
float ChannelVolume = 0.0;
try { ChannelVolume = 0.01 * Registry->ReadInteger(ValueName); }
catch (Exception &E) { }
Preset.Channels.push_back(ChannelVolume);
ChannelIndex += 1;
}
Presets[Name] = Preset;
}
}
static void DeletePresetsFromRegistry(TRegistry *Registry, const String &PresetsKey)
{
if (!Registry->OpenKey(PresetsKey, false))
return;
std::auto_ptr<TStrings> PresetNames(new TStringList);
Registry->GetKeyNames(PresetNames.get());
for (int i = 0; i < PresetNames->Count; ++i)
Registry->DeleteKey(JoinPaths(PresetsKey, PresetNames->Strings[i]));
}
void TPresets::Save()
{
std::auto_ptr<TRegistry> Registry(new TRegistry);
Registry->RootKey = HKEY_CURRENT_USER;
// First remove all presets to start from a clean slate
DeletePresetsFromRegistry(Registry.get(), PresetsKey);
// Write presets
for (std::map<String, TPreset>::const_iterator it = Presets.begin(); it != Presets.end(); ++it)
{
const String &PresetName = it->first;
const TPreset &Preset = it->second;
if (!Registry->OpenKey(JoinPaths(PresetsKey, PresetName), true))
continue;
Registry->WriteInteger(L"Master", 100 * Preset.Master);
for (unsigned i = 0; i < Preset.Channels.size(); ++i)
Registry->WriteInteger(PrintF(L"Channel%d", i), 100 * Preset.Channels[i]);
}
}
| {
"content_hash": "6a872b8586af2bcd9f600ff01d4fbc04",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 97,
"avg_line_length": 33.029411764705884,
"alnum_prop": 0.6749777382012466,
"repo_name": "roelschroeven/VolBalCon",
"id": "0870f3d980b8f1914f6707d9991f052201677dd7",
"size": "2534",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Presets.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "228"
},
{
"name": "C++",
"bytes": "32470"
},
{
"name": "Pascal",
"bytes": "4521"
}
],
"symlink_target": ""
} |
({
testDefaultAttributes:{
failOnWarning: true,
auraWarningsExpectedDuringInit : ["\"alt\" attribute should not be empty for informational image"],
test:function(cmp){
var imgElement = cmp.getElement();
$A.test.assertTrue($A.test.isInstanceOfImageElement(imgElement), "Expected to see a image element.");
$A.test.assertTrue($A.util.stringEndsWith(imgElement.src, '/auraFW/resources/aura/s.gif'), "Expected src to be '/auraFW/resources/aura/s.gif' by default");
$A.test.assertUndefinedOrNull(cmp.find('link'), 'By default there should be no link on the image.');
}
},
testGetImageElementWithoutAnchor:{
attributes : {src: '/auraFW/resources/aura/auralogo.png', imageType:'decorative'},
test : function(cmp) {
this.checkImageMatches(cmp, '/auraFW/resources/aura/auralogo.png');
}
},
testGetImageElementWithAnchor:{
attributes : {src: '/auraFW/resources/aura/auralogo.png', href: 'http://www.salesforce.com', imageType:'decorative'},
test : function(cmp) {
this.checkImageMatches(cmp, '/auraFW/resources/aura/auralogo.png');
}
},
testImageOnly:{
attributes : {src: '/auraFW/resources/aura/auralogo.png', imageType:'decorative'},
test: function(cmp){
var imgElement = cmp.getElement();
$A.test.assertTrue($A.test.isInstanceOfImageElement(imgElement), "Expected to see a image element.");
$A.test.assertTrue($A.util.stringEndsWith(imgElement.src, '/auraFW/resources/aura/auralogo.png'), "Failed to display specified image source.");
$A.test.assertUndefinedOrNull(cmp.find('link'), 'By default there should be no link on the image.');
}
},
testImageWithLink:{
attributes : {src: '/auraFW/resources/aura/auralogo.png', href: 'http://www.salesforce.com', imageType:'decorative'},
test: function(cmp){
var linkElement = cmp.find('link').getElement();
$A.test.assertTrue($A.test.isInstanceOfAnchorElement(linkElement), "Expected to see a anchor element.");
$A.test.assertTrue($A.test.contains(linkElement.href,'http://www.salesforce.com'), linkElement.href + " Expected a link with specified address.");
$A.test.assertEquals('_self',linkElement.target, "Expected target to be _self by default.");
$A.test.assertEquals(1, linkElement.childElementCount || linkElement.children.length); //IE8 and below don't have childElementCount
var imgElement = linkElement.children[0];
$A.test.assertTrue($A.test.isInstanceOfImageElement(imgElement), "Expected to see a image element embedded in the anchor tag.");
$A.test.assertTrue($A.util.stringEndsWith(imgElement.src, '/auraFW/resources/aura/auralogo.png'), "Failed to display specified image source.");
}
},
testUseAllAttributes:{
attributes : {src: '/auraFW/resources/aura/images/bug.png', href: 'http://www.salesforce.com', linkClass:'logo', alt:'Company', target:'_top'},
test: function(cmp){
var linkElement = cmp.find('link').getElement();
$A.test.assertTrue($A.test.isInstanceOfAnchorElement(linkElement), "Expected to see a anchor element.");
$A.test.assertTrue($A.test.contains(linkElement.href,'http://www.salesforce.com'), linkElement.href + " Expected a link with specified address.");
$A.test.assertEquals('_top',linkElement.target, "Expected target to be _top.");
$A.test.assertNotEquals(linkElement.className.indexOf('logo'), -1, "Expected link element to have specified class selector.");
var imgElement = linkElement.children[0];
$A.test.assertTrue($A.util.stringEndsWith(imgElement.src, '/auraFW/resources/aura/images/bug.png'), "Failed to display specified image source.");
$A.test.assertEquals('Company', imgElement.alt, "Expected to see alt text on image element.");
$A.test.assertEquals(-1, imgElement.className.indexOf('logo'));
}
},
testInformationImageTypeWithAltText:{
attributes : {imageType:'informational', alt:'Company'},
test: function(cmp){
var imgElement = cmp.getElement();
$A.test.assertTrue($A.test.isInstanceOfImageElement(imgElement), "Expected to see a image element.");
$A.test.assertEquals('Company', imgElement.alt, "Expected to see alt text on image element.");
}
},
testInformationImageTypeWithoutAltText:{
failOnWarning: true,
auraWarningsExpectedDuringInit : ["\"alt\" attribute should not be empty for informational image"],
attributes : {imageType:'informational'},
test: function(cmp){
// This is testing component "init" which is already tested above (auraWarningsExpectedDuringInit).
}
},
testDecorativeImageTypeWithAltText:{
failOnWarning: true,
auraWarningsExpectedDuringInit : ["\"alt\" attribute should be empty for decorative image"],
attributes : {imageType:'decorative', alt:'Company'},
test: function(cmp){
// This is testing component "init" which is already tested above (auraWarningsExpectedDuringInit).
}
},
testDecorativeImageTypeWithoutAltText:{
attributes : {imageType:'decorative'},
test: function(cmp,action){
var imgElement = cmp.getElement();
$A.test.assertTrue($A.test.isInstanceOfImageElement(imgElement), "Expected to see a image element.");
}
},
testGetImageElementWithoutAnchor:{
attributes : {src: '/auraFW/resources/aura/auralogo.png', imageType:'decorative'},
test : function(cmp) {
var imgEl = cmp.getDef().getHelper().getImageElement(cmp);
$A.test.assertTrue($A.test.isInstanceOfImageElement(imgEl));
$A.test.assertEquals(imgEl, document.getElementsByTagName("img")[0]);
}
},
testGetImageElementWithAnchor:{
attributes : {src: '/auraFW/resources/aura/auralogo.png', href: 'http://www.salesforce.com', imageType:'decorative'},
test : function(cmp) {
var imgEl = cmp.getDef().getHelper().getImageElement(cmp);
$A.test.assertTrue($A.test.isInstanceOfImageElement(imgEl));
$A.test.assertEquals(imgEl, document.getElementsByTagName("img")[0]);
}
},
//W-1014086
_testAccessibility:{
test:function(cmp){
var imgElement = cmp.getElement();
$A.test.assertTrue($A.test.isInstanceOfImageElement(imgElement))
$A.test.assertEquals("",imgElement.alt, "Expected a empty alt text for all image tags.");
cmp.set("v.alt",'Help Accessibility');
cmp.set("v.src",'http://www.google.com/intl/en_com/images/srpr/logo3w.png');
$A.renderingService.rerender(cmp);
imgElement = cmp.getElement();
$A.test.assertEquals("Help Accessibility",imgElement.alt, "Expected alt text for the image element.");
}
}
})
| {
"content_hash": "b62395c4fdda4fe285c577aa7dddb5d0",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 167,
"avg_line_length": 52.39259259259259,
"alnum_prop": 0.654602007634667,
"repo_name": "igor-sfdc/aura",
"id": "45069e7ff1566addcbfc22f9fe4c28962b82cfae",
"size": "7684",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aura-components/src/main/components/ui/image/imageTest.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "623718"
},
{
"name": "GAP",
"bytes": "10093"
},
{
"name": "Java",
"bytes": "7141467"
},
{
"name": "JavaScript",
"bytes": "11685106"
},
{
"name": "PHP",
"bytes": "3345441"
},
{
"name": "Python",
"bytes": "9743"
},
{
"name": "Shell",
"bytes": "22516"
},
{
"name": "XSLT",
"bytes": "1140"
}
],
"symlink_target": ""
} |
package org.caffinitas.ohc;
import java.util.concurrent.ScheduledExecutorService;
import org.caffinitas.ohc.chunked.OHCacheChunkedImpl;
import org.caffinitas.ohc.linked.OHCacheLinkedImpl;
/**
* Configures and builds OHC instance.
* <table summary="Configuration parameters">
* <tr>
* <th>Field</th>
* <th>Meaning</th>
* <th>Default</th>
* </tr>
* <tr>
* <td>{@code keySerializer}</td>
* <td>Serializer implementation used for keys</td>
* <td>Must be configured</td>
* </tr>
* <tr>
* <td>{@code valueSerializer}</td>
* <td>Serializer implementation used for values</td>
* <td>Must be configured</td>
* </tr>
* <tr>
* <td>{@code executorService}</td>
* <td>Executor service required for get operations using a cache loader. E.g. {@link org.caffinitas.ohc.OHCache#getWithLoaderAsync(Object, CacheLoader)}</td>
* <td>(Not configured by default meaning get operations with cache loader not supported by default)</td>
* </tr>
* <tr>
* <td>{@code segmentCount}</td>
* <td>Number of segments</td>
* <td>2 * number of CPUs ({@code java.lang.Runtime.availableProcessors()})</td>
* </tr>
* <tr>
* <td>{@code hashTableSize}</td>
* <td>Initial size of each segment's hash table</td>
* <td>{@code 8192}</td>
* </tr>
* <tr>
* <td>{@code loadFactor}</td>
* <td>Hash table load factor. I.e. determines when rehashing occurs.</td>
* <td>{@code .75f}</td>
* </tr>
* <tr>
* <td>{@code capacity}</td>
* <td>Capacity of the cache in bytes</td>
* <td>16 MB * number of CPUs ({@code java.lang.Runtime.availableProcessors()}), minimum 64 MB</td>
* </tr>
* <tr>
* <td>{@code chunkSize}</td>
* <td>If set and positive, the <i>chunked</i> implementation will be used and each segment
* will be divided into this amount of chunks.</td>
* <td>{@code 0} - i.e. <i>linked</i> implementation will be used</td>
* </tr>
* <tr>
* <td>{@code fixedEntrySize}</td>
* <td>If set and positive, the <i>chunked</i> implementation with fixed sized entries
* will be used. The parameter {@code chunkSize} must be set for fixed-sized entries.</td>
* <td>{@code 0} - i.e. <i>linked</i> implementation will be used,
* if {@code chunkSize} is also {@code 0}</td>
* </tr>
* <tr>
* <td>{@code maxEntrySize}</td>
* <td>Maximum size of a hash entry (including header, serialized key + serialized value)</td>
* <td>(not set, defaults to capacity divided by number of segments)</td>
* </tr>
* <tr>
* <td>{@code throwOOME}</td>
* <td>Throw {@code OutOfMemoryError} if off-heap allocation fails</td>
* <td>{@code false}</td>
* </tr>
* <tr>
* <td>{@code hashAlgorighm}</td>
* <td>Hash algorithm to use internally. Valid options are: {@code XX} for xx-hash, {@code MURMUR3} or {@code CRC32}
* Note: this setting does may only help to improve throughput in rare situations - i.e. if the key is
* very long and you've proven that it really improves performace</td>
* <td>{@code MURMUR3}</td>
* </tr>
* <tr>
* <td>{@code unlocked}</td>
* <td>If set to {@code true}, implementations will not perform any locking. The calling code has to take
* care of synchronized access. In order to create an instance for a thread-per-core implementation,
* set {@code segmentCount=1}, too.</td>
* <td>{@code false}</td>
* </tr>
* <tr>
* <td>{@code defaultTTLmillis}</td>
* <td>If set to a value {@code > 0}, implementations supporting TTLs will tag all entries with
* the given TTL in <b>milliseconds</b>.</td>
* <td>{@code 0}</td>
* </tr>
* <tr>
* <td>{@code timeoutsSlots}</td>
* <td>The number of timeouts slots for each segment - compare with hashed wheel timer.</td>
* <td>{@code 64}</td>
* </tr>
* <tr>
* <td>{@code timeoutsPrecision}</td>
* <td>The amount of time in milliseconds for each timeouts-slot.</td>
* <td>{@code 128}</td>
* </tr>
* <tr>
* <td>{@code ticker}</td>
* <td>Indirection for current time - used for unit tests.</td>
* <td>Default ticker using {@code System.nanoTime()} and {@code System.currentTimeMillis()}</td>
* </tr>
* <tr>
* <td>{@code eviction}</td>
* <td>Choose the eviction algorithm to use. Available are:
* <ul>
* <li>{@link Eviction#LRU LRU}: Plain LRU - least used entry is subject to eviction</li>
* <li>{@link Eviction#W_TINY_LFU W-WinyLFU}: Enable use of Window Tiny-LFU. The size of the
* frequency sketch ("admission filter") is set to the value of {@code hashTableSize}.
* See <a href="http://highscalability.com/blog/2016/1/25/design-of-a-modern-cache.html">this article</a>
* for a description.</li>
* <li>{@link Eviction#NONE None}: No entries will be evicted - this effectively provides a
* capacity-bounded off-heap map.</li>
* </ul>
* </td>
* <td>{@code LRU}</td>
* </tr>
* <tr>
* <td>{@code frequencySketchSize}</td>
* <td>Size of the frequency sketch used by {@link Eviction#W_TINY_LFU W-WinyLFU}</td>
* <td>Defaults to {@code hashTableSize}.</td>
* </tr>
* <tr>
* <td>{@code edenSize}</td>
* <td>Size of the eden generation used by {@link Eviction#W_TINY_LFU W-WinyLFU} relative to a segment's size</td>
* <td>{@code 0.2}</td>
* </tr>
* </table>
* <p>
* You may also use system properties prefixed with {@code org.caffinitas.org.} to other defaults.
* E.g. the system property {@code org.caffinitas.org.segmentCount} configures the default of the number of segments.
* </p>
*
* @param <K> cache key type
* @param <V> cache value type
*/
public class OHCacheBuilder<K, V>
{
private int segmentCount;
private int hashTableSize = 8192;
private long capacity;
private int chunkSize;
private CacheSerializer<K> keySerializer;
private CacheSerializer<V> valueSerializer;
private float loadFactor = .75f;
private int fixedKeySize;
private int fixedValueSize;
private long maxEntrySize;
private ScheduledExecutorService executorService;
private boolean throwOOME;
private HashAlgorithm hashAlgorighm = HashAlgorithm.MURMUR3;
private boolean unlocked;
private long defaultTTLmillis;
private boolean timeouts;
private int timeoutsSlots;
private int timeoutsPrecision;
private Ticker ticker = Ticker.DEFAULT;
private Eviction eviction = Eviction.LRU;
private int frequencySketchSize;
private double edenSize = 0.2d;
private OHCacheBuilder()
{
int cpus = Runtime.getRuntime().availableProcessors();
segmentCount = roundUpToPowerOf2(cpus * 2, 1 << 30);
capacity = Math.min(cpus * 16, 64) * 1024 * 1024;
segmentCount = fromSystemProperties("segmentCount", segmentCount);
hashTableSize = fromSystemProperties("hashTableSize", hashTableSize);
capacity = fromSystemProperties("capacity", capacity);
chunkSize = fromSystemProperties("chunkSize", chunkSize);
loadFactor = fromSystemProperties("loadFactor", loadFactor);
maxEntrySize = fromSystemProperties("maxEntrySize", maxEntrySize);
throwOOME = fromSystemProperties("throwOOME", throwOOME);
hashAlgorighm = HashAlgorithm.valueOf(fromSystemProperties("hashAlgorighm", hashAlgorighm.name()));
unlocked = fromSystemProperties("unlocked", unlocked);
defaultTTLmillis = fromSystemProperties("defaultTTLmillis", defaultTTLmillis);
timeouts = fromSystemProperties("timeouts", timeouts);
timeoutsSlots = fromSystemProperties("timeoutsSlots", timeoutsSlots);
timeoutsPrecision = fromSystemProperties("timeoutsPrecision", timeoutsPrecision);
eviction = fromSystemProperties("eviction", eviction, Eviction.class);
frequencySketchSize = fromSystemProperties("frequencySketchSize", frequencySketchSize);
edenSize = fromSystemProperties("edenSize", edenSize);
}
public static final String SYSTEM_PROPERTY_PREFIX = "org.caffinitas.ohc.";
private static float fromSystemProperties(String name, float defaultValue)
{
try
{
return Float.parseFloat(System.getProperty(SYSTEM_PROPERTY_PREFIX + name, Float.toString(defaultValue)));
}
catch (Exception e)
{
throw new RuntimeException("Failed to parse system property " + SYSTEM_PROPERTY_PREFIX + name, e);
}
}
private static long fromSystemProperties(String name, long defaultValue)
{
try
{
return Long.parseLong(System.getProperty(SYSTEM_PROPERTY_PREFIX + name, Long.toString(defaultValue)));
}
catch (Exception e)
{
throw new RuntimeException("Failed to parse system property " + SYSTEM_PROPERTY_PREFIX + name, e);
}
}
private static int fromSystemProperties(String name, int defaultValue)
{
try
{
return Integer.parseInt(System.getProperty(SYSTEM_PROPERTY_PREFIX + name, Integer.toString(defaultValue)));
}
catch (Exception e)
{
throw new RuntimeException("Failed to parse system property " + SYSTEM_PROPERTY_PREFIX + name, e);
}
}
private static double fromSystemProperties(String name, double defaultValue)
{
try
{
return Double.parseDouble(System.getProperty(SYSTEM_PROPERTY_PREFIX + name, Double.toString(defaultValue)));
}
catch (Exception e)
{
throw new RuntimeException("Failed to parse system property " + SYSTEM_PROPERTY_PREFIX + name, e);
}
}
private static boolean fromSystemProperties(String name, boolean defaultValue)
{
try
{
return Boolean.parseBoolean(System.getProperty(SYSTEM_PROPERTY_PREFIX + name, Boolean.toString(defaultValue)));
}
catch (Exception e)
{
throw new RuntimeException("Failed to parse system property " + SYSTEM_PROPERTY_PREFIX + name, e);
}
}
private static String fromSystemProperties(String name, String defaultValue)
{
return System.getProperty(SYSTEM_PROPERTY_PREFIX + name, defaultValue);
}
private static <E extends Enum> E fromSystemProperties(String name, E defaultValue, Class<E> type)
{
String value = fromSystemProperties(name, defaultValue.name());
return (E) Enum.valueOf(type, value.toUpperCase());
}
static int roundUpToPowerOf2(int number, int max)
{
return number >= max
? max
: (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
}
public static <K, V> OHCacheBuilder<K, V> newBuilder()
{
return new OHCacheBuilder<>();
}
public OHCache<K, V> build()
{
if (fixedKeySize > 0 || fixedValueSize > 0|| chunkSize > 0)
return new OHCacheChunkedImpl<>(this);
return new OHCacheLinkedImpl<>(this);
}
public int getHashTableSize()
{
return hashTableSize;
}
public OHCacheBuilder<K, V> hashTableSize(int hashTableSize)
{
if (hashTableSize < -1)
throw new IllegalArgumentException("hashTableSize:" + hashTableSize);
this.hashTableSize = hashTableSize;
return this;
}
public int getChunkSize()
{
return chunkSize;
}
public OHCacheBuilder<K, V> chunkSize(int chunkSize)
{
if (chunkSize < -1)
throw new IllegalArgumentException("chunkSize:" + chunkSize);
this.chunkSize = chunkSize;
return this;
}
public long getCapacity()
{
return capacity;
}
public OHCacheBuilder<K, V> capacity(long capacity)
{
if (capacity <= 0)
throw new IllegalArgumentException("capacity:" + capacity);
this.capacity = capacity;
return this;
}
public CacheSerializer<K> getKeySerializer()
{
return keySerializer;
}
public OHCacheBuilder<K, V> keySerializer(CacheSerializer<K> keySerializer)
{
this.keySerializer = keySerializer;
return this;
}
public CacheSerializer<V> getValueSerializer()
{
return valueSerializer;
}
public OHCacheBuilder<K, V> valueSerializer(CacheSerializer<V> valueSerializer)
{
this.valueSerializer = valueSerializer;
return this;
}
public int getSegmentCount()
{
return segmentCount;
}
public OHCacheBuilder<K, V> segmentCount(int segmentCount)
{
if (segmentCount < -1)
throw new IllegalArgumentException("segmentCount:" + segmentCount);
this.segmentCount = segmentCount;
return this;
}
public float getLoadFactor()
{
return loadFactor;
}
public OHCacheBuilder<K, V> loadFactor(float loadFactor)
{
if (loadFactor <= 0f)
throw new IllegalArgumentException("loadFactor:" + loadFactor);
this.loadFactor = loadFactor;
return this;
}
public long getMaxEntrySize()
{
return maxEntrySize;
}
public OHCacheBuilder<K, V> maxEntrySize(long maxEntrySize)
{
if (maxEntrySize < 0)
throw new IllegalArgumentException("maxEntrySize:" + maxEntrySize);
this.maxEntrySize = maxEntrySize;
return this;
}
public int getFixedKeySize()
{
return fixedKeySize;
}
public int getFixedValueSize()
{
return fixedValueSize;
}
public OHCacheBuilder<K, V> fixedEntrySize(int fixedKeySize, int fixedValueSize)
{
if ((fixedKeySize > 0 || fixedValueSize > 0) &&
(fixedKeySize <= 0 || fixedValueSize <= 0))
throw new IllegalArgumentException("fixedKeySize:" + fixedKeySize+",fixedValueSize:" + fixedValueSize);
this.fixedKeySize = fixedKeySize;
this.fixedValueSize = fixedValueSize;
return this;
}
public ScheduledExecutorService getExecutorService()
{
return executorService;
}
public OHCacheBuilder<K, V> executorService(ScheduledExecutorService executorService)
{
this.executorService = executorService;
return this;
}
public HashAlgorithm getHashAlgorighm()
{
return hashAlgorighm;
}
public OHCacheBuilder<K, V> hashMode(HashAlgorithm hashMode)
{
if (hashMode == null)
throw new NullPointerException("hashMode");
this.hashAlgorighm = hashMode;
return this;
}
public boolean isThrowOOME()
{
return throwOOME;
}
public OHCacheBuilder<K, V> throwOOME(boolean throwOOME)
{
this.throwOOME = throwOOME;
return this;
}
public boolean isUnlocked()
{
return unlocked;
}
public OHCacheBuilder<K, V> unlocked(boolean unlocked)
{
this.unlocked = unlocked;
return this;
}
public long getDefaultTTLmillis()
{
return defaultTTLmillis;
}
public OHCacheBuilder<K, V> defaultTTLmillis(long defaultTTLmillis)
{
this.defaultTTLmillis = defaultTTLmillis;
return this;
}
public boolean isTimeouts()
{
return timeouts;
}
public OHCacheBuilder<K, V> timeouts(boolean timeouts)
{
this.timeouts = timeouts;
return this;
}
public int getTimeoutsSlots()
{
return timeoutsSlots;
}
public OHCacheBuilder<K, V> timeoutsSlots(int timeoutsSlots)
{
if (timeoutsSlots > 0)
this.timeouts = true;
this.timeoutsSlots = timeoutsSlots;
return this;
}
public int getTimeoutsPrecision()
{
return timeoutsPrecision;
}
public OHCacheBuilder<K, V> timeoutsPrecision(int timeoutsPrecision)
{
if (timeoutsPrecision > 0)
this.timeouts = true;
this.timeoutsPrecision = timeoutsPrecision;
return this;
}
public Ticker getTicker()
{
return ticker;
}
public OHCacheBuilder<K, V> ticker(Ticker ticker)
{
this.ticker = ticker;
return this;
}
public Eviction getEviction()
{
return eviction;
}
public OHCacheBuilder<K, V> eviction(Eviction eviction)
{
this.eviction = eviction;
return this;
}
public int getFrequencySketchSize()
{
return frequencySketchSize;
}
public OHCacheBuilder<K, V> frequencySketchSize(int frequencySketchSize)
{
this.frequencySketchSize = frequencySketchSize;
return this;
}
public double getEdenSize()
{
return edenSize;
}
public OHCacheBuilder<K, V> edenSize(double edenSize)
{
this.edenSize = edenSize;
return this;
}
}
| {
"content_hash": "8102ddc943b8d1e768033f0889994c06",
"timestamp": "",
"source": "github",
"line_count": 543,
"max_line_length": 166,
"avg_line_length": 32.01289134438306,
"alnum_prop": 0.6127250762238969,
"repo_name": "snazy/ohc",
"id": "a99dc967eb5de7ce8aa307f13d8a045df5c22146",
"size": "18037",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "ohc-core/src/main/java/org/caffinitas/ohc/OHCacheBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "702288"
},
{
"name": "Shell",
"bytes": "20695"
}
],
"symlink_target": ""
} |
#region Copyright Simple Injector Contributors
#endregion
namespace SimpleInjector
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using SimpleInjector.Decorators;
using SimpleInjector.Internals;
internal static class Requires
{
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
[DebuggerStepThrough]
internal static void IsNotNull(object instance, string paramName)
{
if (instance == null)
{
ThrowArgumentNullException(paramName);
}
}
[DebuggerStepThrough]
internal static void IsNotNullOrEmpty(string instance, string paramName)
{
IsNotNull(instance, paramName);
if (instance.Length == 0)
{
throw new ArgumentException("Value can not be empty.", paramName);
}
}
[DebuggerStepThrough]
internal static void IsTrue(bool predicate, string paramName, string message = null)
{
if (!predicate)
{
throw new ArgumentException(message ?? string.Empty, paramName);
}
}
[DebuggerStepThrough]
internal static void IsReferenceType(Type type, string paramName)
{
if (!type.IsClass && !type.IsInterface)
{
throw new ArgumentException(StringResources.SuppliedTypeIsNotAReferenceType(type), paramName);
}
}
[DebuggerStepThrough]
internal static void IsNotOpenGenericType(Type type, string paramName)
{
// We check for ContainsGenericParameters to see whether there is a Generic Parameter
// to find out if this type can be created.
if (type.ContainsGenericParameters)
{
throw new ArgumentException(StringResources.SuppliedTypeIsAnOpenGenericType(type), paramName);
}
}
[DebuggerStepThrough]
internal static void ServiceIsAssignableFromImplementation(Type service, Type implementation,
string paramName)
{
if (!service.IsAssignableFrom(implementation))
{
ThrowSuppliedTypeDoesNotInheritFromOrImplement(service, implementation, paramName);
}
}
[DebuggerStepThrough]
internal static void IsNotAnAmbiguousType(Type type, string paramName)
{
if (Helpers.IsAmbiguousType(type))
{
throw new ArgumentException(StringResources.TypeIsAmbiguous(type), paramName);
}
}
[DebuggerStepThrough]
internal static void IsGenericType(Type type, string paramName, Func<Type, string> guidance = null)
{
if (!type.IsGenericType)
{
string message = StringResources.SuppliedTypeIsNotAGenericType(type) +
(guidance == null ? string.Empty : (" " + guidance(type)));
throw new ArgumentException(message, paramName);
}
}
[DebuggerStepThrough]
internal static void IsOpenGenericType(Type type, string paramName, Func<Type, string> guidance = null)
{
// We don't check for ContainsGenericParameters, because we can't handle types that don't have
// a direct parameter (such as Lazy<Func<TResult>>). This is a limitation in the current
// implementation of the GenericArgumentFinder. That's not an easy thing to fix :-(
if (!type.ContainsGenericParameters)
{
string message = StringResources.SuppliedTypeIsNotAnOpenGenericType(type) +
(guidance == null ? string.Empty : (" " + guidance(type)));
throw new ArgumentException(message, paramName);
}
}
internal static void DoesNotContainNullValues<T>(IEnumerable<T> collection, string paramName)
where T : class
{
if (collection != null && collection.Contains(null))
{
throw new ArgumentException("The collection contains null elements.", paramName);
}
}
internal static void DoesNotContainOpenGenericTypesWhenServiceTypeIsNotGeneric(Type serviceType,
IEnumerable<Type> serviceTypes, string paramName)
{
Type openGenericType = serviceTypes.FirstOrDefault(t => t.ContainsGenericParameters);
if (!serviceType.IsGenericType && openGenericType != null)
{
throw new ArgumentException(
StringResources.SuppliedTypeIsAnOpenGenericTypeWhileTheServiceTypeIsNot(openGenericType),
paramName);
}
}
internal static void ServiceTypeIsNotClosedWhenImplementationIsOpen(Type service, Type implementation)
{
bool implementationIsOpen = implementation.IsGenericType && implementation.ContainsGenericParameters;
bool serviceTypeIsClosed = service.IsGenericType && !service.ContainsGenericParameters;
if (implementationIsOpen && serviceTypeIsClosed)
{
throw new NotSupportedException(StringResources.SuppliedTypeCanNotBeOpenWhenDecoratorIsClosed());
}
}
internal static void ServiceOrItsGenericTypeDefinitionIsAssignableFromImplementation(Type service,
Type implementation, string paramName)
{
if (service != implementation &&
!Helpers.ServiceIsAssignableFromImplementation(service, implementation))
{
throw new ArgumentException(
StringResources.SuppliedTypeDoesNotInheritFromOrImplement(service, implementation),
paramName);
}
}
internal static void ServiceIsAssignableFromImplementations(Type serviceType,
IEnumerable<Type> typesToRegister, string paramName, bool typeCanBeServiceType = false)
{
var invalidType = (
from type in typesToRegister
where !Helpers.ServiceIsAssignableFromImplementation(serviceType, type)
where !typeCanBeServiceType || type != serviceType
select type)
.FirstOrDefault();
if (invalidType != null)
{
throw new ArgumentException(
StringResources.SuppliedTypeDoesNotInheritFromOrImplement(serviceType, invalidType),
paramName);
}
}
internal static void ServiceIsAssignableFromImplementations(Type serviceType,
IEnumerable<Registration> registrations, string paramName, bool typeCanBeServiceType = false)
{
var typesToRegister = registrations.Select(registration => registration.ImplementationType);
ServiceIsAssignableFromImplementations(serviceType, typesToRegister, paramName, typeCanBeServiceType);
}
internal static void ImplementationHasSelectableConstructor(Container container, Type serviceType,
Type implementationType, string paramName)
{
string message;
if (!container.Options.IsConstructableType(serviceType, implementationType, out message))
{
throw new ArgumentException(message, paramName);
}
}
internal static void ImplementationsAllHaveSelectableConstructor(Container container,
Type openGenericServiceType, IEnumerable<Type> openGenericImplementations, string paramName)
{
foreach (Type type in openGenericImplementations)
{
string message = null;
if (!container.Options.IsConstructableType(openGenericServiceType, type, out message))
{
throw new ArgumentException(message, paramName);
}
}
}
internal static void TypeFactoryReturnedTypeThatDoesNotContainUnresolvableTypeArguments(
Type serviceType, Type implementationType)
{
try
{
OpenGenericTypeDoesNotContainUnresolvableTypeArguments(
serviceType.IsGenericType ? serviceType.GetGenericTypeDefinition() : serviceType,
implementationType,
null);
}
catch (ArgumentException ex)
{
throw new ActivationException(ex.Message);
}
}
internal static void OpenGenericTypesDoNotContainUnresolvableTypeArguments(Type serviceType,
IEnumerable<Registration> registrations, string parameterName)
{
OpenGenericTypesDoNotContainUnresolvableTypeArguments(serviceType,
registrations.Select(registration => registration.ImplementationType), parameterName);
}
internal static void OpenGenericTypesDoNotContainUnresolvableTypeArguments(Type serviceType,
IEnumerable<Type> implementationTypes, string parameterName)
{
foreach (Type implementationType in implementationTypes)
{
OpenGenericTypeDoesNotContainUnresolvableTypeArguments(serviceType, implementationType,
parameterName);
}
}
internal static void OpenGenericTypeDoesNotContainUnresolvableTypeArguments(Type serviceType,
Type implementationType, string parameterName)
{
if (serviceType.ContainsGenericParameters && implementationType.ContainsGenericParameters)
{
var builder = new GenericTypeBuilder(serviceType, implementationType);
if (!builder.OpenGenericImplementationCanBeAppliedToServiceType())
{
string error =
StringResources.OpenGenericTypeContainsUnresolvableTypeArguments(implementationType);
throw new ArgumentException(error, parameterName);
}
}
}
internal static void DecoratorIsNotAnOpenGenericTypeDefinitionWhenTheServiceTypeIsNot(Type serviceType,
Type decoratorType, string parameterName)
{
if (!serviceType.ContainsGenericParameters && decoratorType.ContainsGenericParameters)
{
throw new ArgumentException(
StringResources.DecoratorCanNotBeAGenericTypeDefinitionWhenServiceTypeIsNot(
serviceType, decoratorType), parameterName);
}
}
internal static void HasFactoryCreatedDecorator(Container container, Type serviceType, Type decoratorType)
{
try
{
IsDecorator(container, serviceType, decoratorType, null);
}
catch (ArgumentException ex)
{
throw new ActivationException(ex.Message);
}
}
internal static void FactoryReturnsATypeThatIsAssignableFromServiceType(Type serviceType,
Type implementationType)
{
if (!serviceType.IsAssignableFrom(implementationType))
{
throw new ActivationException(StringResources.TypeFactoryReturnedIncompatibleType(
serviceType, implementationType));
}
}
internal static void IsDecorator(Container container, Type serviceType, Type decoratorType,
string paramName)
{
ConstructorInfo decoratorConstructor =
container.Options.SelectConstructor(serviceType, decoratorType);
Requires.DecoratesServiceType(serviceType, decoratorConstructor, paramName);
}
internal static void AreRegistrationsForThisContainer(Container container,
IEnumerable<Registration> registrations, string paramName)
{
foreach (Registration registration in registrations)
{
IsRegistrationForThisContainer(container, registration, paramName);
}
}
internal static void IsRegistrationForThisContainer(Container container, Registration registration,
string paramName)
{
if (!object.ReferenceEquals(container, registration.Container))
{
string message = StringResources.TheSuppliedRegistrationBelongsToADifferentContainer();
throw new ArgumentException(message, paramName);
}
}
internal static void CollectionDoesNotContainOpenGenericTypes(IEnumerable<Type> typesToRegister,
string paramName)
{
var openGenericTypes =
from type in typesToRegister
where type.ContainsGenericParameters
select type;
if (openGenericTypes.Any())
{
string message = StringResources.ThisOverloadDoesNotAllowOpenGenerics(openGenericTypes);
throw new ArgumentException(message, paramName);
}
}
[DebuggerStepThrough]
internal static void IsValidEnum<TEnum>(TEnum value, string paramName) where TEnum : struct
{
if (!Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Contains(value))
{
throw new ArgumentException(
StringResources.ValueInvalidForEnumType(paramName, value, typeof(TEnum)));
}
}
internal static void IsNotPartiallyClosed(Type openGenericServiceType, string paramName)
{
if (openGenericServiceType.IsPartiallyClosed())
{
throw new ArgumentException(
StringResources.ServiceTypeCannotBeAPartiallyClosedType(openGenericServiceType),
paramName);
}
}
internal static void IsNotPartiallyClosed(Type openGenericServiceType, string paramName,
string implementationTypeParamName)
{
if (openGenericServiceType.IsPartiallyClosed())
{
throw new ArgumentException(
StringResources.ServiceTypeCannotBeAPartiallyClosedType(openGenericServiceType, paramName,
implementationTypeParamName),
paramName);
}
}
private static void DecoratesServiceType(Type serviceType, ConstructorInfo decoratorConstructor,
string paramName)
{
bool decoratesServiceType = DecoratorHelpers.DecoratesServiceType(serviceType, decoratorConstructor);
if (!decoratesServiceType)
{
ThrowMustDecorateServiceType(serviceType, decoratorConstructor, paramName);
}
}
private static void ThrowMustDecorateServiceType(Type serviceType,
ConstructorInfo decoratorConstructor, string paramName)
{
int numberOfServiceTypeDependencies =
DecoratorHelpers.GetNumberOfServiceTypeDependencies(serviceType, decoratorConstructor);
if (numberOfServiceTypeDependencies == 0)
{
// We must get the real type to be decorated to prevent the exception message from being
// confusing to the user.
// At this point we know that the decorator type implements an service type in some way
// (either open or closed), so we this call will return at least one record.
serviceType = DecoratorHelpers.GetDecoratingBaseTypeCandidates(serviceType,
decoratorConstructor.DeclaringType)
.First();
ThrowMustContainTheServiceTypeAsArgument(serviceType, decoratorConstructor, paramName);
}
else
{
ThrowMustContainASingleInstanceOfTheServiceTypeAsArgument(serviceType, decoratorConstructor, paramName);
}
}
private static void ThrowMustContainTheServiceTypeAsArgument(Type serviceType,
ConstructorInfo decoratorConstructor, string paramName)
{
string message = StringResources.TheConstructorOfTypeMustContainTheServiceTypeAsArgument(
decoratorConstructor.DeclaringType, serviceType);
throw new ArgumentException(message, paramName);
}
private static void ThrowMustContainASingleInstanceOfTheServiceTypeAsArgument(Type serviceType,
ConstructorInfo decoratorConstructor, string paramName)
{
string message =
StringResources.TheConstructorOfTypeMustContainASingleInstanceOfTheServiceTypeAsArgument(
decoratorConstructor.DeclaringType, serviceType);
throw new ArgumentException(message, paramName);
}
private static void ThrowArgumentNullException(string paramName)
{
throw new ArgumentNullException(paramName);
}
private static void ThrowSuppliedTypeDoesNotInheritFromOrImplement(Type service, Type implementation,
string paramName)
{
throw new ArgumentException(
StringResources.SuppliedTypeDoesNotInheritFromOrImplement(service, implementation),
paramName);
}
}
} | {
"content_hash": "728a63350426bd3fea24ee4276648022",
"timestamp": "",
"source": "github",
"line_count": 439,
"max_line_length": 120,
"avg_line_length": 40.993166287015946,
"alnum_prop": 0.6136363636363636,
"repo_name": "bcraun/SimpleInjector",
"id": "547159a4684b1eaf26e1317c463c328c54924e9d",
"size": "19235",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SimpleInjector.NET/Requires.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "26218"
},
{
"name": "C#",
"bytes": "3027359"
},
{
"name": "Pascal",
"bytes": "8738"
},
{
"name": "Visual Basic",
"bytes": "452"
}
],
"symlink_target": ""
} |
import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
import {main, readCommandLineAndConfiguration, watchMode} from '../src/main';
import {setup} from './test_support';
describe('ngc transformer command-line', () => {
let basePath: string;
let outDir: string;
let write: (fileName: string, content: string) => void;
let errorSpy: jasmine.Spy&((s: string) => void);
function shouldExist(fileName: string) {
if (!fs.existsSync(path.resolve(outDir, fileName))) {
throw new Error(`Expected ${fileName} to be emitted (outDir: ${outDir})`);
}
}
function shouldNotExist(fileName: string) {
if (fs.existsSync(path.resolve(outDir, fileName))) {
throw new Error(`Did not expect ${fileName} to be emitted (outDir: ${outDir})`);
}
}
function writeConfig(tsconfig: string = '{"extends": "./tsconfig-base.json"}') {
write('tsconfig.json', tsconfig);
}
beforeEach(() => {
errorSpy = jasmine.createSpy('consoleError').and.callFake(console.error);
const support = setup();
basePath = support.basePath;
outDir = path.join(basePath, 'built');
process.chdir(basePath);
write = (fileName: string, content: string) => { support.write(fileName, content); };
write('tsconfig-base.json', `{
"compilerOptions": {
"experimentalDecorators": true,
"skipLibCheck": true,
"noImplicitAny": true,
"types": [],
"outDir": "built",
"rootDir": ".",
"baseUrl": ".",
"declaration": true,
"target": "es5",
"newLine": "lf",
"module": "es2015",
"moduleResolution": "node",
"lib": ["es6", "dom"],
"typeRoots": ["node_modules/@types"]
}
}`);
});
it('should compile without errors', () => {
writeConfig();
write('test.ts', 'export const A = 1;');
const exitCode = main(['-p', basePath], errorSpy);
expect(errorSpy).not.toHaveBeenCalled();
expect(exitCode).toBe(0);
});
it('should respect the "newLine" compiler option when printing diagnostics', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"compilerOptions": {
"newLine": "CRLF",
}
}`);
write('test.ts', 'export NOT_VALID = true;');
// Stub the error spy because we don't want to call through and print the
// expected error diagnostic.
errorSpy.and.stub();
const exitCode = main(['-p', basePath], errorSpy);
expect(errorSpy).toHaveBeenCalledWith(
`test.ts(1,1): error TS1128: Declaration or statement expected.\r\n`);
expect(exitCode).toBe(1);
});
describe('errors', () => {
beforeEach(() => { errorSpy.and.stub(); });
it('should not print the stack trace if user input file does not exist', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"files": ["test.ts"]
}`);
const exitCode = main(['-p', basePath], errorSpy);
expect(errorSpy).toHaveBeenCalledWith(
`error TS6053: File '` + path.posix.join(basePath, 'test.ts') + `' not found.` +
'\n');
expect(exitCode).toEqual(1);
});
it('should not print the stack trace if user input file is malformed', () => {
writeConfig();
write('test.ts', 'foo;');
const exitCode = main(['-p', basePath], errorSpy);
expect(errorSpy).toHaveBeenCalledWith(
`test.ts(1,1): error TS2304: Cannot find name 'foo'.` +
'\n');
expect(exitCode).toEqual(1);
});
it('should not print the stack trace if cannot find the imported module', () => {
writeConfig();
write('test.ts', `import {MyClass} from './not-exist-deps';`);
const exitCode = main(['-p', basePath], errorSpy);
expect(errorSpy).toHaveBeenCalledWith(
`test.ts(1,23): error TS2307: Cannot find module './not-exist-deps'.` +
'\n');
expect(exitCode).toEqual(1);
});
it('should not print the stack trace if cannot import', () => {
writeConfig();
write('empty-deps.ts', 'export const A = 1;');
write('test.ts', `import {MyClass} from './empty-deps';`);
const exitCode = main(['-p', basePath], errorSpy);
expect(errorSpy).toHaveBeenCalledWith(
`test.ts(1,9): error TS2305: Module '"./empty-deps"' has no exported member 'MyClass'.\n`);
expect(exitCode).toEqual(1);
});
it('should not print the stack trace if type mismatches', () => {
writeConfig();
write('empty-deps.ts', 'export const A = "abc";');
write('test.ts', `
import {A} from './empty-deps';
A();
`);
const exitCode = main(['-p', basePath], errorSpy);
expect(errorSpy).toHaveBeenCalledWith(
'test.ts(3,9): error TS2349: Cannot invoke an expression whose type lacks a call signature. ' +
'Type \'String\' has no compatible call signatures.\n');
expect(exitCode).toEqual(1);
});
it('should print the stack trace on compiler internal errors', () => {
write('test.ts', 'export const A = 1;');
const exitCode = main(['-p', 'not-exist'], errorSpy);
expect(errorSpy).toHaveBeenCalledTimes(1);
expect(errorSpy.calls.mostRecent().args[0]).toContain('no such file or directory');
expect(errorSpy.calls.mostRecent().args[0]).toMatch(/at Object\.(fs\.)?lstatSync/);
expect(exitCode).toEqual(2);
});
it('should report errors for ngfactory files that are not referenced by root files', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"files": ["mymodule.ts"]
}`);
write('mymodule.ts', `
import {NgModule, Component} from '@angular/core';
@Component({template: '{{unknownProp}}'})
export class MyComp {}
@NgModule({declarations: [MyComp]})
export class MyModule {}
`);
const exitCode = main(['-p', basePath], errorSpy);
expect(errorSpy).toHaveBeenCalledTimes(1);
expect(errorSpy.calls.mostRecent().args[0]).toContain('mymodule.ts.MyComp.html');
expect(errorSpy.calls.mostRecent().args[0])
.toContain(`Property 'unknownProp' does not exist on type 'MyComp'`);
expect(exitCode).toEqual(1);
});
it('should report errors as coming from the html file, not the factory', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"files": ["mymodule.ts"]
}`);
write('my.component.ts', `
import {Component} from '@angular/core';
@Component({templateUrl: './my.component.html'})
export class MyComp {}
`);
write('my.component.html', `<h1>
{{unknownProp}}
</h1>`);
write('mymodule.ts', `
import {NgModule} from '@angular/core';
import {MyComp} from './my.component';
@NgModule({declarations: [MyComp]})
export class MyModule {}
`);
const exitCode = main(['-p', basePath], errorSpy);
expect(errorSpy).toHaveBeenCalledTimes(1);
expect(errorSpy.calls.mostRecent().args[0]).toContain('my.component.html(1,5):');
expect(errorSpy.calls.mostRecent().args[0])
.toContain(`Property 'unknownProp' does not exist on type 'MyComp'`);
expect(exitCode).toEqual(1);
});
});
describe('compile ngfactory files', () => {
it('should compile ngfactory files that are not referenced by root files', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"files": ["mymodule.ts"]
}`);
write('mymodule.ts', `
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
@NgModule({
imports: [CommonModule]
})
export class MyModule {}
`);
const exitCode = main(['-p', basePath], errorSpy);
expect(exitCode).toEqual(0);
expect(fs.existsSync(path.resolve(outDir, 'mymodule.ngfactory.js'))).toBe(true);
expect(fs.existsSync(
path.resolve(outDir, 'node_modules', '@angular', 'core', 'core.ngfactory.js')))
.toBe(true);
});
describe('comments', () => {
function compileAndRead(contents: string) {
writeConfig(`{
"extends": "./tsconfig-base.json",
"files": ["mymodule.ts"],
"angularCompilerOptions": {"allowEmptyCodegenFiles": true}
}`);
write('mymodule.ts', contents);
const exitCode = main(['-p', basePath], errorSpy);
expect(exitCode).toEqual(0);
const modPath = path.resolve(outDir, 'mymodule.ngfactory.js');
expect(fs.existsSync(modPath)).toBe(true);
return fs.readFileSync(modPath, {encoding: 'UTF-8'});
}
it('should be added', () => {
const contents = compileAndRead(`
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
@NgModule({
imports: [CommonModule]
})
export class MyModule {}
`);
expect(contents).toContain('@fileoverview');
expect(contents).toContain('generated by the Angular template compiler');
expect(contents).toContain('@suppress {suspiciousCode');
});
it('should be merged with existing fileoverview comments', () => {
const contents = compileAndRead(`/** Hello world. */
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
@NgModule({
imports: [CommonModule]
})
export class MyModule {}
`);
expect(contents).toContain('Hello world.');
});
it('should only pick file comments', () => {
const contents = compileAndRead(`
/** Comment on class. */
class MyClass {
}
`);
expect(contents).toContain('@fileoverview');
expect(contents).not.toContain('Comment on class.');
});
it('should not be merged with @license comments', () => {
const contents = compileAndRead(`/** @license Some license. */
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
@NgModule({
imports: [CommonModule]
})
export class MyModule {}
`);
expect(contents).toContain('@fileoverview');
expect(contents).not.toContain('@license');
});
it('should be included in empty files', () => {
const contents = compileAndRead(`/** My comment. */
import {Inject, Injectable, Optional} from '@angular/core';
@Injectable()
export class NotAnAngularComponent {}
`);
expect(contents).toContain('My comment');
});
});
it('should compile with an explicit tsconfig reference', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"files": ["mymodule.ts"]
}`);
write('mymodule.ts', `
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
@NgModule({
imports: [CommonModule]
})
export class MyModule {}
`);
const exitCode = main(['-p', path.join(basePath, 'tsconfig.json')], errorSpy);
expect(exitCode).toEqual(0);
expect(fs.existsSync(path.resolve(outDir, 'mymodule.ngfactory.js'))).toBe(true);
expect(fs.existsSync(
path.resolve(outDir, 'node_modules', '@angular', 'core', 'core.ngfactory.js')))
.toBe(true);
});
describe(`emit generated files depending on the source file`, () => {
const modules = ['comp', 'directive', 'module'];
beforeEach(() => {
write('src/comp.ts', `
import {Component, ViewEncapsulation} from '@angular/core';
@Component({
selector: 'comp-a',
template: 'A',
styleUrls: ['plain.css'],
encapsulation: ViewEncapsulation.None
})
export class CompA {
}
@Component({
selector: 'comp-b',
template: 'B',
styleUrls: ['emulated.css']
})
export class CompB {
}`);
write('src/plain.css', 'div {}');
write('src/emulated.css', 'div {}');
write('src/directive.ts', `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[someDir]',
host: {'[title]': 'someProp'},
})
export class SomeDirective {
@Input() someProp: string;
}`);
write('src/module.ts', `
import {NgModule} from '@angular/core';
import {CompA, CompB} from './comp';
import {SomeDirective} from './directive';
@NgModule({
declarations: [
CompA, CompB,
SomeDirective,
],
exports: [
CompA, CompB,
SomeDirective,
],
})
export class SomeModule {
}`);
});
function expectJsDtsMetadataJsonToExist() {
modules.forEach(moduleName => {
shouldExist(moduleName + '.js');
shouldExist(moduleName + '.d.ts');
shouldExist(moduleName + '.metadata.json');
});
}
function expectAllGeneratedFilesToExist(enableSummariesForJit = true) {
modules.forEach(moduleName => {
if (/module|comp/.test(moduleName)) {
shouldExist(moduleName + '.ngfactory.js');
shouldExist(moduleName + '.ngfactory.d.ts');
} else {
shouldNotExist(moduleName + '.ngfactory.js');
shouldNotExist(moduleName + '.ngfactory.d.ts');
}
if (enableSummariesForJit) {
shouldExist(moduleName + '.ngsummary.js');
shouldExist(moduleName + '.ngsummary.d.ts');
} else {
shouldNotExist(moduleName + '.ngsummary.js');
shouldNotExist(moduleName + '.ngsummary.d.ts');
}
shouldExist(moduleName + '.ngsummary.json');
shouldNotExist(moduleName + '.ngfactory.metadata.json');
shouldNotExist(moduleName + '.ngsummary.metadata.json');
});
shouldExist('plain.css.ngstyle.js');
shouldExist('plain.css.ngstyle.d.ts');
shouldExist('emulated.css.shim.ngstyle.js');
shouldExist('emulated.css.shim.ngstyle.d.ts');
}
it('should emit generated files from sources with summariesForJit', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"angularCompilerOptions": {
"enableSummariesForJit": true
},
"include": ["src/**/*.ts"]
}`);
const exitCode = main(['-p', path.join(basePath, 'tsconfig.json')], errorSpy);
expect(exitCode).toEqual(0);
outDir = path.resolve(basePath, 'built', 'src');
expectJsDtsMetadataJsonToExist();
expectAllGeneratedFilesToExist(true);
});
it('should not emit generated files from sources without summariesForJit', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"angularCompilerOptions": {
"enableSummariesForJit": false
},
"include": ["src/**/*.ts"]
}`);
const exitCode = main(['-p', path.join(basePath, 'tsconfig.json')], errorSpy);
expect(exitCode).toEqual(0);
outDir = path.resolve(basePath, 'built', 'src');
expectJsDtsMetadataJsonToExist();
expectAllGeneratedFilesToExist(false);
});
it('should emit generated files from libraries', () => {
// first only generate .d.ts / .js / .metadata.json files
writeConfig(`{
"extends": "./tsconfig-base.json",
"angularCompilerOptions": {
"skipTemplateCodegen": true
},
"compilerOptions": {
"outDir": "lib"
},
"include": ["src/**/*.ts"]
}`);
let exitCode = main(['-p', path.join(basePath, 'tsconfig.json')], errorSpy);
expect(exitCode).toEqual(0);
outDir = path.resolve(basePath, 'lib', 'src');
modules.forEach(moduleName => {
shouldExist(moduleName + '.js');
shouldExist(moduleName + '.d.ts');
shouldExist(moduleName + '.metadata.json');
shouldNotExist(moduleName + '.ngfactory.js');
shouldNotExist(moduleName + '.ngfactory.d.ts');
shouldNotExist(moduleName + '.ngsummary.js');
shouldNotExist(moduleName + '.ngsummary.d.ts');
shouldNotExist(moduleName + '.ngsummary.json');
shouldNotExist(moduleName + '.ngfactory.metadata.json');
shouldNotExist(moduleName + '.ngsummary.metadata.json');
});
shouldNotExist('src/plain.css.ngstyle.js');
shouldNotExist('src/plain.css.ngstyle.d.ts');
shouldNotExist('src/emulated.css.shim.ngstyle.js');
shouldNotExist('src/emulated.css.shim.ngstyle.d.ts');
// Then compile again, using the previous .metadata.json as input.
writeConfig(`{
"extends": "./tsconfig-base.json",
"angularCompilerOptions": {
"skipTemplateCodegen": false,
"enableSummariesForJit": true
},
"compilerOptions": {
"outDir": "built"
},
"include": ["lib/**/*.d.ts"]
}`);
write('lib/src/plain.css', 'div {}');
write('lib/src/emulated.css', 'div {}');
exitCode = main(['-p', path.join(basePath, 'tsconfig.json')], errorSpy);
expect(exitCode).toEqual(0);
outDir = path.resolve(basePath, 'built', 'lib', 'src');
expectAllGeneratedFilesToExist();
});
});
describe('closure', () => {
it('should not run tsickle by default', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"files": ["mymodule.ts"],
}`);
write('mymodule.ts', `
import {NgModule, Component} from '@angular/core';
@Component({template: ''})
export class MyComp {}
@NgModule({declarations: [MyComp]})
export class MyModule {}
`);
const exitCode = main(['-p', basePath], errorSpy);
expect(exitCode).toEqual(0);
const mymodulejs = path.resolve(outDir, 'mymodule.js');
const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8');
expect(mymoduleSource).not.toContain('@fileoverview added by tsickle');
expect(mymoduleSource).toContain('MyComp = __decorate');
expect(mymoduleSource).not.toContain('MyComp.decorators = [');
});
it('should add closure annotations', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"angularCompilerOptions": {
"annotateForClosureCompiler": true
},
"files": ["mymodule.ts"]
}`);
write('mymodule.ts', `
import {NgModule, Component} from '@angular/core';
@Component({template: ''})
export class MyComp {
fn(p: any) {}
}
@NgModule({declarations: [MyComp]})
export class MyModule {}
`);
const exitCode = main(['-p', basePath], errorSpy);
expect(exitCode).toEqual(0);
const mymodulejs = path.resolve(outDir, 'mymodule.js');
const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8');
expect(mymoduleSource).toContain('@fileoverview added by tsickle');
expect(mymoduleSource).toContain('@param {?} p');
});
it('should add metadata as decorators', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"compilerOptions": {
"emitDecoratorMetadata": true
},
"angularCompilerOptions": {
"annotationsAs": "decorators"
},
"files": ["mymodule.ts"]
}`);
write('aclass.ts', `export class AClass {}`);
write('mymodule.ts', `
import {NgModule} from '@angular/core';
import {AClass} from './aclass';
@NgModule({declarations: []})
export class MyModule {
constructor(importedClass: AClass) {}
}
`);
const exitCode = main(['-p', basePath], errorSpy);
expect(exitCode).toEqual(0);
const mymodulejs = path.resolve(outDir, 'mymodule.js');
const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8');
expect(mymoduleSource).toContain('MyModule = __decorate([');
expect(mymoduleSource).toContain(`import { AClass } from './aclass';`);
expect(mymoduleSource).toContain(`__metadata("design:paramtypes", [AClass])`);
});
it('should add metadata as static fields', () => {
// Note: Don't specify emitDecoratorMetadata here on purpose,
// as regression test for https://github.com/angular/angular/issues/19916.
writeConfig(`{
"extends": "./tsconfig-base.json",
"compilerOptions": {
"emitDecoratorMetadata": false
},
"angularCompilerOptions": {
"annotationsAs": "static fields"
},
"files": ["mymodule.ts"]
}`);
write('aclass.ts', `export class AClass {}`);
write('mymodule.ts', `
import {NgModule} from '@angular/core';
import {AClass} from './aclass';
@NgModule({declarations: []})
export class MyModule {
constructor(importedClass: AClass) {}
}
`);
const exitCode = main(['-p', basePath], errorSpy);
expect(exitCode).toEqual(0);
const mymodulejs = path.resolve(outDir, 'mymodule.js');
const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8');
expect(mymoduleSource).not.toContain('__decorate');
expect(mymoduleSource).toContain('args: [{ declarations: [] },] }');
expect(mymoduleSource).not.toContain(`__metadata`);
expect(mymoduleSource).toContain(`import { AClass } from './aclass';`);
expect(mymoduleSource).toContain(`{ type: AClass }`);
});
});
it('should not rewrite imports when annotating with closure', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"compilerOptions": {
"paths": {
"submodule": ["./src/submodule/public_api.ts"]
}
},
"angularCompilerOptions": {
"annotateForClosureCompiler": true
},
"files": ["mymodule.ts"]
}`);
write('src/test.txt', ' ');
write('src/submodule/public_api.ts', `
export const A = 1;
`);
write('mymodule.ts', `
import {NgModule, Component} from '@angular/core';
import {A} from 'submodule';
@Component({template: ''})
export class MyComp {
fn(p: any) { return A; }
}
@NgModule({declarations: [MyComp]})
export class MyModule {}
`);
const exitCode = main(['-p', basePath], errorSpy);
expect(exitCode).toEqual(0);
const mymodulejs = path.resolve(outDir, 'mymodule.js');
const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8');
expect(mymoduleSource).toContain(`import { A } from 'submodule'`);
});
describe('expression lowering', () => {
beforeEach(() => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"files": ["mymodule.ts"]
}`);
});
function compile(): number {
errorSpy.calls.reset();
const result = main(['-p', path.join(basePath, 'tsconfig.json')], errorSpy);
expect(errorSpy).not.toHaveBeenCalled();
return result;
}
it('should be able to lower a lambda expression in a provider', () => {
write('mymodule.ts', `
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
class Foo {}
@NgModule({
imports: [CommonModule],
providers: [{provide: 'someToken', useFactory: () => new Foo()}]
})
export class MyModule {}
`);
expect(compile()).toEqual(0);
const mymodulejs = path.resolve(outDir, 'mymodule.js');
const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8');
expect(mymoduleSource).toContain('var ɵ0 = function () { return new Foo(); }');
expect(mymoduleSource).toContain('export { ɵ0');
const mymodulefactory = path.resolve(outDir, 'mymodule.ngfactory.js');
const mymodulefactorySource = fs.readFileSync(mymodulefactory, 'utf8');
expect(mymodulefactorySource).toContain('"someToken", i1.ɵ0');
});
it('should be able to lower a function expression in a provider', () => {
write('mymodule.ts', `
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
class Foo {}
@NgModule({
imports: [CommonModule],
providers: [{provide: 'someToken', useFactory: function() {return new Foo();}}]
})
export class MyModule {}
`);
expect(compile()).toEqual(0);
const mymodulejs = path.resolve(outDir, 'mymodule.js');
const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8');
expect(mymoduleSource).toContain('var ɵ0 = function () { return new Foo(); }');
expect(mymoduleSource).toContain('export { ɵ0');
const mymodulefactory = path.resolve(outDir, 'mymodule.ngfactory.js');
const mymodulefactorySource = fs.readFileSync(mymodulefactory, 'utf8');
expect(mymodulefactorySource).toContain('"someToken", i1.ɵ0');
});
it('should able to lower multiple expressions', () => {
write('mymodule.ts', `
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
class Foo {}
@NgModule({
imports: [CommonModule],
providers: [
{provide: 'someToken', useFactory: () => new Foo()},
{provide: 'someToken', useFactory: () => new Foo()},
{provide: 'someToken', useFactory: () => new Foo()},
{provide: 'someToken', useFactory: () => new Foo()}
]
})
export class MyModule {}
`);
expect(compile()).toEqual(0);
const mymodulejs = path.resolve(outDir, 'mymodule.js');
const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8');
expect(mymoduleSource).toContain('ɵ0 = function () { return new Foo(); }');
expect(mymoduleSource).toContain('ɵ1 = function () { return new Foo(); }');
expect(mymoduleSource).toContain('ɵ2 = function () { return new Foo(); }');
expect(mymoduleSource).toContain('ɵ3 = function () { return new Foo(); }');
expect(mymoduleSource).toContain('export { ɵ0, ɵ1, ɵ2, ɵ3');
});
it('should be able to lower an indirect expression', () => {
write('mymodule.ts', `
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
class Foo {}
const factory = () => new Foo();
@NgModule({
imports: [CommonModule],
providers: [{provide: 'someToken', useFactory: factory}]
})
export class MyModule {}
`);
expect(compile()).toEqual(0, 'Compile failed');
const mymodulejs = path.resolve(outDir, 'mymodule.js');
const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8');
expect(mymoduleSource).toContain('var factory = function () { return new Foo(); }');
expect(mymoduleSource).toContain('var ɵ0 = factory;');
expect(mymoduleSource).toContain('export { ɵ0 };');
});
it('should not lower a lambda that is already exported', () => {
write('mymodule.ts', `
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
export class Foo {}
export const factory = () => new Foo();
@NgModule({
imports: [CommonModule],
providers: [{provide: 'someToken', useFactory: factory}]
})
export class MyModule {}
`);
expect(compile()).toEqual(0);
const mymodulejs = path.resolve(outDir, 'mymodule.js');
const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8');
expect(mymoduleSource).not.toContain('ɵ0');
});
it('should lower an NgModule id', () => {
write('mymodule.ts', `
import {NgModule} from '@angular/core';
@NgModule({
id: (() => 'test')(),
})
export class MyModule {}
`);
expect(compile()).toEqual(0);
const mymodulejs = path.resolve(outDir, 'mymodule.js');
const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8');
expect(mymoduleSource).toContain('id: ɵ0');
expect(mymoduleSource).toMatch(/ɵ0 = .*'test'/);
});
it('should lower loadChildren', () => {
write('mymodule.ts', `
import {Component, NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
export function foo(): string {
console.log('side-effect');
return 'test';
}
@Component({
selector: 'route',
template: 'route',
})
export class Route {}
@NgModule({
declarations: [Route],
imports: [
RouterModule.forRoot([
{path: '', pathMatch: 'full', component: Route, loadChildren: foo()}
]),
]
})
export class MyModule {}
`);
expect(compile()).toEqual(0);
const mymodulejs = path.resolve(outDir, 'mymodule.js');
const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8');
expect(mymoduleSource).toContain('loadChildren: ɵ0');
expect(mymoduleSource).toMatch(/ɵ0 = .*foo\(\)/);
});
it('should be able to lower supported expressions', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"files": ["module.ts"]
}`);
write('module.ts', `
import {NgModule, InjectionToken} from '@angular/core';
import {AppComponent} from './app';
export interface Info {
route: string;
data: string;
}
export const T1 = new InjectionToken<string>('t1');
export const T2 = new InjectionToken<string>('t2');
export const T3 = new InjectionToken<number>('t3');
export const T4 = new InjectionToken<Info[]>('t4');
enum SomeEnum {
OK,
Cancel
}
function calculateString() {
return 'someValue';
}
const routeLikeData = [{
route: '/home',
data: calculateString()
}];
@NgModule({
declarations: [AppComponent],
providers: [
{ provide: T1, useValue: calculateString() },
{ provide: T2, useFactory: () => 'someValue' },
{ provide: T3, useValue: SomeEnum.OK },
{ provide: T4, useValue: routeLikeData }
]
})
export class MyModule {}
`);
write('app.ts', `
import {Component, Inject} from '@angular/core';
import * as m from './module';
@Component({
selector: 'my-app',
template: ''
})
export class AppComponent {
constructor(
@Inject(m.T1) private t1: string,
@Inject(m.T2) private t2: string,
@Inject(m.T3) private t3: number,
@Inject(m.T4) private t4: m.Info[],
) {}
}
`);
expect(main(['-p', basePath], errorSpy)).toBe(0);
shouldExist('module.js');
});
it('should allow to use lowering with export *', () => {
write('mymodule.ts', `
import {NgModule} from '@angular/core';
export * from './util';
// Note: the lambda will be lowered into an exported expression
@NgModule({providers: [{provide: 'aToken', useValue: () => 2}]})
export class MyModule {}
`);
write('util.ts', `
// Note: The lambda will be lowered into an exported expression
const x = () => 2;
export const y = x;
`);
expect(compile()).toEqual(0);
const mymoduleSource = fs.readFileSync(path.resolve(outDir, 'mymodule.js'), 'utf8');
expect(mymoduleSource).toContain('ɵ0');
const utilSource = fs.readFileSync(path.resolve(outDir, 'util.js'), 'utf8');
expect(utilSource).toContain('ɵ0');
const mymoduleNgFactoryJs =
fs.readFileSync(path.resolve(outDir, 'mymodule.ngfactory.js'), 'utf8');
// check that the generated code refers to ɵ0 from mymodule, and not from util!
expect(mymoduleNgFactoryJs).toContain(`import * as i1 from "./mymodule"`);
expect(mymoduleNgFactoryJs).toContain(`"aToken", i1.ɵ0`);
});
});
function writeFlatModule(outFile: string) {
writeConfig(`
{
"extends": "./tsconfig-base.json",
"angularCompilerOptions": {
"flatModuleId": "flat_module",
"flatModuleOutFile": "${outFile}",
"skipTemplateCodegen": true,
"enableResourceInlining": true
},
"files": ["public-api.ts"]
}
`);
write('public-api.ts', `
export * from './src/flat.component';
export * from './src/flat.module';`);
write('src/flat.component.html', '<div>flat module component</div>');
write('src/flat.component.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'flat-comp',
templateUrl: 'flat.component.html',
})
export class FlatComponent {
}`);
write('src/flat.module.ts', `
import {NgModule} from '@angular/core';
import {FlatComponent} from './flat.component';
@NgModule({
declarations: [
FlatComponent,
],
exports: [
FlatComponent,
],
})
export class FlatModule {
}`);
}
it('should be able to generate a flat module library', () => {
writeFlatModule('index.js');
const exitCode = main(['-p', path.join(basePath, 'tsconfig.json')], errorSpy);
expect(exitCode).toEqual(0);
shouldExist('index.js');
shouldExist('index.metadata.json');
});
it('should downlevel templates in flat module metadata', () => {
writeFlatModule('index.js');
const exitCode = main(['-p', path.join(basePath, 'tsconfig.json')], errorSpy);
expect(exitCode).toEqual(0);
shouldExist('index.js');
shouldExist('index.metadata.json');
const metadataPath = path.resolve(outDir, 'index.metadata.json');
const metadataSource = fs.readFileSync(metadataPath, 'utf8');
expect(metadataSource).not.toContain('templateUrl');
expect(metadataSource).toContain('<div>flat module component</div>');
});
describe('with tree example', () => {
beforeEach(() => {
writeConfig();
write('index_aot.ts', `
import {enableProdMode} from '@angular/core';
import {platformBrowser} from '@angular/platform-browser';
import {AppModuleNgFactory} from './tree.ngfactory';
enableProdMode();
platformBrowser().bootstrapModuleFactory(AppModuleNgFactory);`);
write('tree.ts', `
import {Component, NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
@Component({
selector: 'tree',
inputs: ['data'],
template:
\`<span [style.backgroundColor]="bgColor"> {{data.value}} </span><tree *ngIf='data.right != null' [data]='data.right'></tree><tree *ngIf='data.left != null' [data]='data.left'></tree>\`
})
export class TreeComponent {
data: any;
bgColor = 0;
}
@NgModule({imports: [CommonModule], bootstrap: [TreeComponent], declarations: [TreeComponent]})
export class AppModule {}
`);
});
it('should compile without error', () => {
expect(main(['-p', path.join(basePath, 'tsconfig.json')], errorSpy)).toBe(0);
});
});
describe('with external symbol re-exports enabled', () => {
it('should be able to compile multiple libraries with summaries', () => {
// Note: we need to emit the generated code for the libraries
// into the node_modules, as that is the only way that we
// currently support when using summaries.
// TODO(tbosch): add support for `paths` to our CompilerHost.fileNameToModuleName
// and then use `paths` here instead of writing to node_modules.
// Angular
write('tsconfig-ng.json', `{
"extends": "./tsconfig-base.json",
"angularCompilerOptions": {
"generateCodeForLibraries": true,
"enableSummariesForJit": true
},
"compilerOptions": {
"outDir": "."
},
"include": ["node_modules/@angular/core/**/*"],
"exclude": [
"node_modules/@angular/core/test/**",
"node_modules/@angular/core/testing/**"
]
}`);
// Lib 1
write('lib1/tsconfig-lib1.json', `{
"extends": "../tsconfig-base.json",
"angularCompilerOptions": {
"generateCodeForLibraries": false,
"enableSummariesForJit": true,
"createExternalSymbolFactoryReexports": true
},
"compilerOptions": {
"rootDir": ".",
"outDir": "../node_modules/lib1_built"
}
}`);
write('lib1/module.ts', `
import {NgModule} from '@angular/core';
export function someFactory(): any { return null; }
@NgModule({
providers: [{provide: 'foo', useFactory: someFactory}]
})
export class Module {}
`);
write('lib1/class1.ts', `export class Class1 {}`);
// Lib 2
write('lib2/tsconfig-lib2.json', `{
"extends": "../tsconfig-base.json",
"angularCompilerOptions": {
"generateCodeForLibraries": false,
"enableSummariesForJit": true,
"createExternalSymbolFactoryReexports": true
},
"compilerOptions": {
"rootDir": ".",
"outDir": "../node_modules/lib2_built"
}
}`);
write('lib2/module.ts', `
export {Module} from 'lib1_built/module';
`);
write('lib2/class2.ts', `
import {Class1} from 'lib1_built/class1';
export class Class2 {
constructor(class1: Class1) {}
}
`);
// Application
write('app/tsconfig-app.json', `{
"extends": "../tsconfig-base.json",
"angularCompilerOptions": {
"generateCodeForLibraries": false,
"enableSummariesForJit": true,
"createExternalSymbolFactoryReexports": true
},
"compilerOptions": {
"rootDir": ".",
"outDir": "../built/app"
}
}`);
write('app/main.ts', `
import {NgModule, Inject} from '@angular/core';
import {Module} from 'lib2_built/module';
@NgModule({
imports: [Module]
})
export class AppModule {
constructor(@Inject('foo') public foo: any) {}
}
`);
expect(main(['-p', path.join(basePath, 'lib1', 'tsconfig-lib1.json')], errorSpy)).toBe(0);
expect(main(['-p', path.join(basePath, 'lib2', 'tsconfig-lib2.json')], errorSpy)).toBe(0);
expect(main(['-p', path.join(basePath, 'app', 'tsconfig-app.json')], errorSpy)).toBe(0);
// library 1
// make `shouldExist` / `shouldNotExist` relative to `node_modules`
outDir = path.resolve(basePath, 'node_modules');
shouldExist('lib1_built/module.js');
shouldExist('lib1_built/module.ngsummary.json');
shouldExist('lib1_built/module.ngsummary.js');
shouldExist('lib1_built/module.ngsummary.d.ts');
shouldExist('lib1_built/module.ngfactory.js');
shouldExist('lib1_built/module.ngfactory.d.ts');
// library 2
// make `shouldExist` / `shouldNotExist` relative to `node_modules`
outDir = path.resolve(basePath, 'node_modules');
shouldExist('lib2_built/module.js');
shouldExist('lib2_built/module.ngsummary.json');
shouldExist('lib2_built/module.ngsummary.js');
shouldExist('lib2_built/module.ngsummary.d.ts');
shouldExist('lib2_built/module.ngfactory.js');
shouldExist('lib2_built/module.ngfactory.d.ts');
shouldExist('lib2_built/class2.ngsummary.json');
shouldNotExist('lib2_built/class2.ngsummary.js');
shouldNotExist('lib2_built/class2.ngsummary.d.ts');
shouldExist('lib2_built/class2.ngfactory.js');
shouldExist('lib2_built/class2.ngfactory.d.ts');
// app
// make `shouldExist` / `shouldNotExist` relative to `built`
outDir = path.resolve(basePath, 'built');
shouldExist('app/main.js');
});
it('should create external symbol re-exports', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"angularCompilerOptions": {
"generateCodeForLibraries": false,
"createExternalSymbolFactoryReexports": true
}
}`);
write('test.ts', `
import {Injectable, NgZone} from '@angular/core';
@Injectable({providedIn: 'root'})
export class MyService {
constructor(public ngZone: NgZone) {}
}
`);
expect(main(['-p', basePath], errorSpy)).toBe(0);
shouldExist('test.js');
shouldExist('test.metadata.json');
shouldExist('test.ngsummary.json');
shouldExist('test.ngfactory.js');
shouldExist('test.ngfactory.d.ts');
const summaryJson = require(path.join(outDir, 'test.ngsummary.json'));
const factoryOutput = fs.readFileSync(path.join(outDir, 'test.ngfactory.js'), 'utf8');
expect(summaryJson['symbols'][0].name).toBe('MyService');
expect(summaryJson['symbols'][1])
.toEqual(jasmine.objectContaining({name: 'NgZone', importAs: 'NgZone_1'}));
expect(factoryOutput).toContain(`export { NgZone as NgZone_1 } from "@angular/core";`);
});
});
it('should be able to compile multiple libraries with summaries', () => {
// Lib 1
write('lib1/tsconfig-lib1.json', `{
"extends": "../tsconfig-base.json",
"angularCompilerOptions": {
"generateCodeForLibraries": false,
"enableSummariesForJit": true
},
"compilerOptions": {
"rootDir": ".",
"outDir": "../node_modules/lib1_built"
}
}`);
write('lib1/module.ts', `
import {NgModule} from '@angular/core';
export function someFactory(): any { return null; }
@NgModule({
providers: [{provide: 'foo', useFactory: someFactory}]
})
export class Module {}
`);
write('lib1/class1.ts', `export class Class1 {}`);
// Lib 2
write('lib2/tsconfig-lib2.json', `{
"extends": "../tsconfig-base.json",
"angularCompilerOptions": {
"generateCodeForLibraries": false,
"enableSummariesForJit": true
},
"compilerOptions": {
"rootDir": ".",
"outDir": "../node_modules/lib2_built"
}
}`);
write('lib2/module.ts', `export {Module} from 'lib1_built/module';`);
write('lib2/class2.ts', `
import {Class1} from 'lib1_built/class1';
export class Class2 {
constructor(class1: Class1) {}
}
`);
// Application
write('app/tsconfig-app.json', `{
"extends": "../tsconfig-base.json",
"angularCompilerOptions": {
"generateCodeForLibraries": false,
"enableSummariesForJit": true
},
"compilerOptions": {
"rootDir": ".",
"outDir": "../built/app"
}
}`);
write('app/main.ts', `
import {NgModule, Inject} from '@angular/core';
import {Module} from 'lib2_built/module';
@NgModule({
imports: [Module]
})
export class AppModule {
constructor(@Inject('foo') public foo: any) {}
}
`);
expect(main(['-p', path.join(basePath, 'lib1', 'tsconfig-lib1.json')], errorSpy)).toBe(0);
expect(main(['-p', path.join(basePath, 'lib2', 'tsconfig-lib2.json')], errorSpy)).toBe(0);
expect(main(['-p', path.join(basePath, 'app', 'tsconfig-app.json')], errorSpy)).toBe(0);
// library 1
// make `shouldExist` / `shouldNotExist` relative to `node_modules`
outDir = path.resolve(basePath, 'node_modules');
shouldExist('lib1_built/module.js');
shouldExist('lib1_built/module.ngsummary.json');
shouldExist('lib1_built/module.ngsummary.js');
shouldExist('lib1_built/module.ngsummary.d.ts');
shouldExist('lib1_built/module.ngfactory.js');
shouldExist('lib1_built/module.ngfactory.d.ts');
// library 2
// make `shouldExist` / `shouldNotExist` relative to `node_modules`
outDir = path.resolve(basePath, 'node_modules');
shouldExist('lib2_built/module.js');
// "module.ts" re-exports an external symbol and will therefore
// have a summary JSON file and its corresponding JIT summary.
shouldExist('lib2_built/module.ngsummary.json');
shouldExist('lib2_built/module.ngsummary.js');
shouldExist('lib2_built/module.ngsummary.d.ts');
// "module.ts" only re-exports an external symbol and the AOT compiler does not
// need to generate anything. Therefore there should be no factory files.
shouldNotExist('lib2_built/module.ngfactory.js');
shouldNotExist('lib2_built/module.ngfactory.d.ts');
shouldExist('lib2_built/class2.ngsummary.json');
shouldNotExist('lib2_built/class2.ngsummary.js');
shouldNotExist('lib2_built/class2.ngsummary.d.ts');
// We don't expect factories here because the "class2.ts" file
// just exports a class that does not produce any AOT code.
shouldNotExist('lib2_built/class2.ngfactory.js');
shouldNotExist('lib2_built/class2.ngfactory.d.ts');
// app
// make `shouldExist` / `shouldNotExist` relative to `built`
outDir = path.resolve(basePath, 'built');
shouldExist('app/main.js');
});
describe('enableResourceInlining', () => {
it('should inline templateUrl and styleUrl in JS and metadata', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"files": ["mymodule.ts"],
"angularCompilerOptions": {
"enableResourceInlining": true
}
}`);
write('my.component.ts', `
import {Component} from '@angular/core';
@Component({
templateUrl: './my.component.html',
styleUrls: ['./my.component.css'],
})
export class MyComp {}
`);
write('my.component.html', `<h1>Some template content</h1>`);
write('my.component.css', `h1 {color: blue}`);
write('mymodule.ts', `
import {NgModule} from '@angular/core';
import {MyComp} from './my.component';
@NgModule({declarations: [MyComp]})
export class MyModule {}
`);
const exitCode = main(['-p', basePath]);
expect(exitCode).toEqual(0);
outDir = path.resolve(basePath, 'built');
const outputJs = fs.readFileSync(path.join(outDir, 'my.component.js'), {encoding: 'utf-8'});
expect(outputJs).not.toContain('templateUrl');
expect(outputJs).not.toContain('styleUrls');
expect(outputJs).toContain('Some template content');
expect(outputJs).toContain('color: blue');
const outputMetadata =
fs.readFileSync(path.join(outDir, 'my.component.metadata.json'), {encoding: 'utf-8'});
expect(outputMetadata).not.toContain('templateUrl');
expect(outputMetadata).not.toContain('styleUrls');
expect(outputMetadata).toContain('Some template content');
expect(outputMetadata).toContain('color: blue');
});
});
});
describe('expression lowering', () => {
const shouldExist = (fileName: string) => {
if (!fs.existsSync(path.resolve(basePath, fileName))) {
throw new Error(`Expected ${fileName} to be emitted (basePath: ${basePath})`);
}
};
it('should be able to lower supported expressions', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"files": ["module.ts"]
}`);
write('module.ts', `
import {NgModule, InjectionToken} from '@angular/core';
import {AppComponent} from './app';
export interface Info {
route: string;
data: string;
}
export const T1 = new InjectionToken<string>('t1');
export const T2 = new InjectionToken<string>('t2');
export const T3 = new InjectionToken<number>('t3');
export const T4 = new InjectionToken<Info[]>('t4');
enum SomeEnum {
OK,
Cancel
}
function calculateString() {
return 'someValue';
}
const routeLikeData = [{
route: '/home',
data: calculateString()
}];
@NgModule({
declarations: [AppComponent],
providers: [
{ provide: T1, useValue: calculateString() },
{ provide: T2, useFactory: () => 'someValue' },
{ provide: T3, useValue: SomeEnum.OK },
{ provide: T4, useValue: routeLikeData }
]
})
export class MyModule {}
`);
write('app.ts', `
import {Component, Inject} from '@angular/core';
import * as m from './module';
@Component({
selector: 'my-app',
template: ''
})
export class AppComponent {
constructor(
@Inject(m.T1) private t1: string,
@Inject(m.T2) private t2: string,
@Inject(m.T3) private t3: number,
@Inject(m.T4) private t4: m.Info[],
) {}
}
`);
expect(main(['-p', basePath], s => {})).toBe(0);
shouldExist('built/module.js');
});
});
describe('watch mode', () => {
let timer: (() => void)|undefined = undefined;
let results: ((message: string) => void)|undefined = undefined;
let originalTimeout: number;
function trigger() {
const delay = 1000;
setTimeout(() => {
const t = timer;
timer = undefined;
if (!t) {
fail('Unexpected state. Timer was not set.');
} else {
t();
}
}, delay);
}
function whenResults(): Promise<string> {
return new Promise(resolve => {
results = message => {
resolve(message);
results = undefined;
};
});
}
function errorSpy(message: string): void {
if (results) results(message);
}
beforeEach(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
const timerToken = 100;
spyOn(ts.sys, 'setTimeout').and.callFake((callback: () => void) => {
timer = callback;
return timerToken;
});
spyOn(ts.sys, 'clearTimeout').and.callFake((token: number) => {
if (token == timerToken) {
timer = undefined;
}
});
write('greet.html', `<p class="greeting"> Hello {{name}}!</p>`);
write('greet.css', `p.greeting { color: #eee }`);
write('greet.ts', `
import {Component, Input} from '@angular/core';
@Component({
selector: 'greet',
templateUrl: 'greet.html',
styleUrls: ['greet.css']
})
export class Greet {
@Input()
name: string;
}
`);
write('app.ts', `
import {Component} from '@angular/core'
@Component({
selector: 'my-app',
template: \`
<div>
<greet [name]='name'></greet>
</div>
\`,
})
export class App {
name:string;
constructor() {
this.name = \`Angular!\`
}
}`);
write('module.ts', `
import {NgModule} from '@angular/core';
import {Greet} from './greet';
import {App} from './app';
@NgModule({
declarations: [Greet, App]
})
export class MyModule {}
`);
});
afterEach(() => { jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; });
function writeAppConfig(location: string) {
writeConfig(`{
"extends": "./tsconfig-base.json",
"compilerOptions": {
"outDir": "${location}"
}
}`);
}
function expectRecompile(cb: () => void) {
return (done: DoneFn) => {
writeAppConfig('dist');
const config = readCommandLineAndConfiguration(['-p', basePath]);
const compile = watchMode(config.project, config.options, errorSpy);
return new Promise(resolve => {
compile.ready(() => {
cb();
// Allow the watch callbacks to occur and trigger the timer.
trigger();
// Expect the file to trigger a result.
whenResults().then(message => {
expect(message).toMatch(/File change detected/);
compile.close();
done();
resolve();
});
});
});
};
}
it('should recompile when config file changes', expectRecompile(() => writeAppConfig('dist2')));
it('should recompile when a ts file changes', expectRecompile(() => {
write('greet.ts', `
import {Component, Input} from '@angular/core';
@Component({
selector: 'greet',
templateUrl: 'greet.html',
styleUrls: ['greet.css'],
})
export class Greet {
@Input()
name: string;
age: number;
}
`);
}));
it('should recompile when the html file changes',
expectRecompile(() => { write('greet.html', '<p> Hello {{name}} again!</p>'); }));
it('should recompile when the css file changes',
expectRecompile(() => { write('greet.css', `p.greeting { color: blue }`); }));
});
describe('regressions', () => {
//#20479
it('should not generate an invalid metadata file', () => {
write('src/tsconfig.json', `{
"extends": "../tsconfig-base.json",
"files": ["lib.ts"],
"angularCompilerOptions": {
"skipTemplateCodegen": true
}
}`);
write('src/lib.ts', `
export namespace A{
export class C1 {
}
export interface I1{
}
}`);
expect(main(['-p', path.join(basePath, 'src/tsconfig.json')])).toBe(0);
shouldNotExist('src/lib.metadata.json');
});
//#19544
it('should recognize @NgModule() directive with a redundant @Injectable()', () => {
write('src/tsconfig.json', `{
"extends": "../tsconfig-base.json",
"compilerOptions": {
"outDir": "../dist",
"rootDir": ".",
"rootDirs": [
".",
"../dist"
]
},
"files": ["test-module.ts"]
}`);
write('src/test.component.ts', `
import {Component} from '@angular/core';
@Component({
template: '<p>hello</p>',
})
export class TestComponent {}
`);
write('src/test-module.ts', `
import {Injectable, NgModule} from '@angular/core';
import {TestComponent} from './test.component';
@NgModule({declarations: [TestComponent]})
@Injectable()
export class TestModule {}
`);
const messages: string[] = [];
const exitCode =
main(['-p', path.join(basePath, 'src/tsconfig.json')], message => messages.push(message));
expect(exitCode).toBe(0, 'Compile failed unexpectedly.\n ' + messages.join('\n '));
});
// #19765
it('should not report an error when the resolved .css file is in outside rootDir', () => {
write('src/tsconfig.json', `{
"extends": "../tsconfig-base.json",
"compilerOptions": {
"outDir": "../dist",
"rootDir": ".",
"rootDirs": [
".",
"../dist"
]
},
"files": ["test-module.ts"]
}`);
write('src/lib/test.component.ts', `
import {Component} from '@angular/core';
@Component({
template: '<p>hello</p>',
styleUrls: ['./test.component.css']
})
export class TestComponent {}
`);
write('dist/dummy.txt', ''); // Force dist to be created
write('dist/lib/test.component.css', `
p { color: blue }
`);
write('src/test-module.ts', `
import {NgModule} from '@angular/core';
import {TestComponent} from './lib/test.component';
@NgModule({declarations: [TestComponent]})
export class TestModule {}
`);
const messages: string[] = [];
const exitCode =
main(['-p', path.join(basePath, 'src/tsconfig.json')], message => messages.push(message));
expect(exitCode).toBe(0, 'Compile failed unexpectedly.\n ' + messages.join('\n '));
});
it('should emit all structural errors', () => {
write('src/tsconfig.json', `{
"extends": "../tsconfig-base.json",
"files": ["test-module.ts"]
}`);
write('src/lib/indirect2.ts', `
declare var f: any;
export const t2 = f\`<p>hello</p>\`;
`);
write('src/lib/indirect1.ts', `
import {t2} from './indirect2';
export const t1 = t2 + ' ';
`);
write('src/lib/test.component.ts', `
import {Component} from '@angular/core';
import {t1} from './indirect1';
@Component({
template: t1
})
export class TestComponent {}
`);
write('src/test-module.ts', `
import {NgModule} from '@angular/core';
import {TestComponent} from './lib/test.component';
@NgModule({declarations: [TestComponent]})
export class TestModule {}
`);
const messages: string[] = [];
const exitCode =
main(['-p', path.join(basePath, 'src/tsconfig.json')], message => messages.push(message));
expect(exitCode).toBe(1, 'Compile was expected to fail');
expect(messages[0]).toContain('Tagged template expressions are not supported in metadata');
});
// Regression: #20076
it('should report template error messages', () => {
write('src/tsconfig.json', `{
"extends": "../tsconfig-base.json",
"files": ["test-module.ts"]
}`);
write('src/lib/test.component.ts', `
import {Component} from '@angular/core';
@Component({
template: '{{thing.?stuff}}'
})
export class TestComponent {
thing: string;
}
`);
write('src/test-module.ts', `
import {NgModule} from '@angular/core';
import {TestComponent} from './lib/test.component';
@NgModule({declarations: [TestComponent]})
export class TestModule {}
`);
const messages: string[] = [];
const exitCode =
main(['-p', path.join(basePath, 'src/tsconfig.json')], message => messages.push(message));
expect(exitCode).toBe(1, 'Compile was expected to fail');
expect(messages[0]).toContain('Parser Error: Unexpected token');
});
// Regression test for #19979
it('should not stack overflow on a recursive module export', () => {
write('src/tsconfig.json', `{
"extends": "../tsconfig-base.json",
"files": ["test-module.ts"]
}`);
write('src/test-module.ts', `
import {Component, NgModule} from '@angular/core';
@Component({
template: 'Hello'
})
export class MyFaultyComponent {}
@NgModule({
exports: [MyFaultyModule],
declarations: [MyFaultyComponent],
providers: [],
})
export class MyFaultyModule { }
`);
const messages: string[] = [];
expect(
main(['-p', path.join(basePath, 'src/tsconfig.json')], message => messages.push(message)))
.toBe(1, 'Compile was expected to fail');
expect(messages[0]).toContain(`module 'MyFaultyModule' is exported recursively`);
});
// Regression test for #19979
it('should not stack overflow on a recursive module import', () => {
write('src/tsconfig.json', `{
"extends": "../tsconfig-base.json",
"files": ["test-module.ts"]
}`);
write('src/test-module.ts', `
import {Component, NgModule, forwardRef} from '@angular/core';
@Component({
template: 'Hello'
})
export class MyFaultyComponent {}
@NgModule({
imports: [forwardRef(() => MyFaultyModule)]
})
export class MyFaultyImport {}
@NgModule({
imports: [MyFaultyImport],
declarations: [MyFaultyComponent]
})
export class MyFaultyModule { }
`);
const messages: string[] = [];
expect(
main(['-p', path.join(basePath, 'src/tsconfig.json')], message => messages.push(message)))
.toBe(1, 'Compile was expected to fail');
expect(messages[0]).toContain(`is imported recursively by the module 'MyFaultyImport`);
});
// Regression test for #21273
it('should not report errors for unknown property annotations', () => {
write('src/tsconfig.json', `{
"extends": "../tsconfig-base.json",
"files": ["test-module.ts"]
}`);
write('src/test-decorator.ts', `
export function Convert(p: any): any {
// Make sur this doesn't look like a macro function
var r = p;
return r;
}
`);
write('src/test-module.ts', `
import {Component, Input, NgModule} from '@angular/core';
import {Convert} from './test-decorator';
@Component({template: '{{name}}'})
export class TestComponent {
@Input() @Convert(convert) name: string;
}
function convert(n: any) { return n; }
@NgModule({declarations: [TestComponent]})
export class TestModule {}
`);
const messages: string[] = [];
expect(
main(['-p', path.join(basePath, 'src/tsconfig.json')], message => messages.push(message)))
.toBe(0, `Compile failed:\n ${messages.join('\n ')}`);
});
it('should allow using 2 classes with the same name in declarations with noEmitOnError=true',
() => {
write('src/tsconfig.json', `{
"extends": "../tsconfig-base.json",
"compilerOptions": {
"noEmitOnError": true
},
"files": ["test-module.ts"]
}`);
function writeComp(fileName: string) {
write(fileName, `
import {Component} from '@angular/core';
@Component({selector: 'comp', template: ''})
export class TestComponent {}
`);
}
writeComp('src/comp1.ts');
writeComp('src/comp2.ts');
write('src/test-module.ts', `
import {NgModule} from '@angular/core';
import {TestComponent as Comp1} from './comp1';
import {TestComponent as Comp2} from './comp2';
@NgModule({
declarations: [Comp1, Comp2],
})
export class MyModule {}
`);
expect(main(['-p', path.join(basePath, 'src/tsconfig.json')])).toBe(0);
});
it('should not type check a .js files from node_modules with allowJs', () => {
write('src/tsconfig.json', `{
"extends": "../tsconfig-base.json",
"compilerOptions": {
"noEmitOnError": true,
"allowJs": true,
"declaration": false
},
"files": ["test-module.ts"]
}`);
write('src/test-module.ts', `
import {Component, NgModule} from '@angular/core';
import 'my-library';
@Component({
template: 'hello'
})
export class HelloCmp {}
@NgModule({
declarations: [HelloCmp],
})
export class MyModule {}
`);
write('src/node_modules/t.txt', ``);
write('src/node_modules/my-library/index.js', `
export someVar = 1;
export someOtherVar = undefined + 1;
`);
expect(main(['-p', path.join(basePath, 'src/tsconfig.json')])).toBe(0);
});
});
describe('formatted messages', () => {
it('should emit a formatted error message for a structural error', () => {
write('src/tsconfig.json', `{
"extends": "../tsconfig-base.json",
"files": ["test-module.ts"]
}`);
write('src/lib/indirect2.ts', `
declare var f: any;
export const t2 = f\`<p>hello</p>\`;
`);
write('src/lib/indirect1.ts', `
import {t2} from './indirect2';
export const t1 = t2 + ' ';
`);
write('src/lib/test.component.ts', `
import {Component} from '@angular/core';
import {t1} from './indirect1';
@Component({
template: t1,
styleUrls: ['./test.component.css']
})
export class TestComponent {}
`);
write('src/test-module.ts', `
import {NgModule} from '@angular/core';
import {TestComponent} from './lib/test.component';
@NgModule({declarations: [TestComponent]})
export class TestModule {}
`);
const messages: string[] = [];
const exitCode =
main(['-p', path.join(basePath, 'src/tsconfig.json')], message => messages.push(message));
expect(exitCode).toBe(1, 'Compile was expected to fail');
expect(messages[0])
.toEqual(`lib/test.component.ts(6,21): Error during template compile of 'TestComponent'
Tagged template expressions are not supported in metadata in 't1'
't1' references 't2' at lib/indirect1.ts(3,27)
't2' contains the error at lib/indirect2.ts(4,27).
`);
});
});
describe('tree shakeable services', () => {
function compileService(source: string): string {
write('service.ts', source);
const exitCode = main(['-p', path.join(basePath, 'tsconfig.json')], errorSpy);
expect(exitCode).toEqual(0);
const servicePath = path.resolve(outDir, 'service.js');
return fs.readFileSync(servicePath, 'utf8');
}
beforeEach(() => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"files": ["service.ts"]
}`);
write('module.ts', `
import {NgModule} from '@angular/core';
@NgModule({})
export class Module {}
`);
});
describe(`doesn't break existing injectables`, () => {
it('on simple services', () => {
const source = compileService(`
import {Injectable, NgModule} from '@angular/core';
@Injectable()
export class Service {
constructor(public param: string) {}
}
@NgModule({
providers: [{provide: Service, useValue: new Service('test')}],
})
export class ServiceModule {}
`);
expect(source).not.toMatch(/ngInjectableDef/);
});
it('on a service with a base class service', () => {
const source = compileService(`
import {Injectable, NgModule} from '@angular/core';
@Injectable()
export class Dep {}
export class Base {
constructor(private dep: Dep) {}
}
@Injectable()
export class Service extends Base {}
@NgModule({
providers: [Service],
})
export class ServiceModule {}
`);
expect(source).not.toMatch(/ngInjectableDef/);
});
});
it('compiles a basic InjectableDef', () => {
const source = compileService(`
import {Injectable} from '@angular/core';
import {Module} from './module';
@Injectable({
providedIn: Module,
})
export class Service {}
`);
expect(source).toMatch(/ngInjectableDef = .+\.defineInjectable\(/);
expect(source).toMatch(/ngInjectableDef.*token: Service/);
expect(source).toMatch(/ngInjectableDef.*providedIn: .+\.Module/);
});
it('ngInjectableDef in es5 mode is annotated @nocollapse when closure options are enabled',
() => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"angularCompilerOptions": {
"annotateForClosureCompiler": true
},
"files": ["service.ts"]
}`);
const source = compileService(`
import {Injectable} from '@angular/core';
import {Module} from './module';
@Injectable({
providedIn: Module,
})
export class Service {}
`);
expect(source).toMatch(/\/\*\* @nocollapse \*\/ Service\.ngInjectableDef =/);
});
it('compiles a useValue InjectableDef', () => {
const source = compileService(`
import {Injectable} from '@angular/core';
import {Module} from './module';
export const CONST_SERVICE: Service = null;
@Injectable({
providedIn: Module,
useValue: CONST_SERVICE
})
export class Service {}
`);
expect(source).toMatch(/ngInjectableDef.*return CONST_SERVICE/);
});
it('compiles a useExisting InjectableDef', () => {
const source = compileService(`
import {Injectable} from '@angular/core';
import {Module} from './module';
@Injectable()
export class Existing {}
@Injectable({
providedIn: Module,
useExisting: Existing,
})
export class Service {}
`);
expect(source).toMatch(/ngInjectableDef.*return ..\.inject\(Existing\)/);
});
it('compiles a useFactory InjectableDef with optional dep', () => {
const source = compileService(`
import {Injectable, Optional} from '@angular/core';
import {Module} from './module';
@Injectable()
export class Existing {}
@Injectable({
providedIn: Module,
useFactory: (existing: Existing|null) => new Service(existing),
deps: [[new Optional(), Existing]],
})
export class Service {
constructor(e: Existing|null) {}
}
`);
expect(source).toMatch(/ngInjectableDef.*return ..\(..\.inject\(Existing, 8\)/);
});
it('compiles a useFactory InjectableDef with skip-self dep', () => {
const source = compileService(`
import {Injectable, SkipSelf} from '@angular/core';
import {Module} from './module';
@Injectable()
export class Existing {}
@Injectable({
providedIn: Module,
useFactory: (existing: Existing) => new Service(existing),
deps: [[new SkipSelf(), Existing]],
})
export class Service {
constructor(e: Existing) {}
}
`);
expect(source).toMatch(/ngInjectableDef.*return ..\(..\.inject\(Existing, 4\)/);
});
it('compiles a service that depends on a token', () => {
const source = compileService(`
import {Inject, Injectable, InjectionToken} from '@angular/core';
import {Module} from './module';
export const TOKEN = new InjectionToken('desc', {providedIn: Module, factory: () => true});
@Injectable({
providedIn: Module,
})
export class Service {
constructor(@Inject(TOKEN) value: boolean) {}
}
`);
expect(source).toMatch(/ngInjectableDef = .+\.defineInjectable\(/);
expect(source).toMatch(/ngInjectableDef.*token: Service/);
expect(source).toMatch(/ngInjectableDef.*providedIn: .+\.Module/);
});
it('generates exports.* references when outputting commonjs', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"compilerOptions": {
"module": "commonjs"
},
"files": ["service.ts"]
}`);
const source = compileService(`
import {Inject, Injectable, InjectionToken} from '@angular/core';
import {Module} from './module';
export const TOKEN = new InjectionToken<string>('test token', {
providedIn: 'root',
factory: () => 'this is a test',
});
@Injectable({providedIn: 'root'})
export class Service {
constructor(@Inject(TOKEN) token: any) {}
}
`);
expect(source).toMatch(/new Service\(i0\.inject\(exports\.TOKEN\)\);/);
});
});
it('libraries should not break strictMetadataEmit', () => {
// first only generate .d.ts / .js / .metadata.json files
writeConfig(`{
"extends": "./tsconfig-base.json",
"angularCompilerOptions": {
"skipTemplateCodegen": true,
"strictMetadataEmit": true,
"fullTemplateTypeCheck": true
},
"compilerOptions": {
"outDir": "lib"
},
"files": ["main.ts", "test.d.ts"]
}`);
write('main.ts', `
import {Test} from './test';
export const bar = Test.bar;
`);
write('test.d.ts', `
declare export class Test {
static bar: string;
}
`);
let exitCode = main(['-p', path.join(basePath, 'tsconfig.json')], errorSpy);
expect(exitCode).toEqual(0);
});
});
| {
"content_hash": "f5deaac42ed7101039c7591a8547a420",
"timestamp": "",
"source": "github",
"line_count": 2242,
"max_line_length": 201,
"avg_line_length": 33.35905441570027,
"alnum_prop": 0.5482076720461018,
"repo_name": "hansl/angular",
"id": "69a1b7c3a56052e764564a337087367cf0ea9899",
"size": "75018",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/compiler-cli/test/ngc_spec.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "247"
},
{
"name": "CSS",
"bytes": "337345"
},
{
"name": "Dockerfile",
"bytes": "14627"
},
{
"name": "HTML",
"bytes": "327986"
},
{
"name": "JSONiq",
"bytes": "410"
},
{
"name": "JavaScript",
"bytes": "794437"
},
{
"name": "PHP",
"bytes": "7222"
},
{
"name": "PowerShell",
"bytes": "4229"
},
{
"name": "Python",
"bytes": "329250"
},
{
"name": "Shell",
"bytes": "67724"
},
{
"name": "TypeScript",
"bytes": "17127977"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.