repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
dlawde/homebrew-cask | Casks/screencast.rb | <reponame>dlawde/homebrew-cask
cask "screencast" do
version "0.0.6"
sha256 "0fb23d34ee3c94eb47233b42d2ac93de84d14dcdafe1e7205ce0a4341ee812f0"
url "https://github.com/soh335/Screencast/releases/download/#{version}/Screencast.dmg"
name "Screencast"
desc "Simple screen video capture application"
homepage "https://github.com/soh335/Screencast"
app "Screencast.app"
zap trash: "~/Library/Preferences/jp.makeitreal.Screencast.plist"
end
|
JumHorn/leetcode | C/CombinationSumII.c | #include <stdbool.h>
#include <stdlib.h>
#include <string.h>
//integer cmp function
int cmp(const void *lhs, const void *rhs)
{
if (*(int *)lhs == *(int *)rhs)
return 0;
return *(int *)lhs < *(int *)rhs ? -1 : 1;
}
//malloc result
int **mallocRes(int (*data)[30], int dataSize, int *dataColSize, int *returnSize, int **returnColumnSizes)
{
*returnSize = dataSize;
*returnColumnSizes = (int *)malloc(sizeof(int) * (*returnSize));
memcpy(*returnColumnSizes, dataColSize, sizeof(int) * (*returnSize));
int **res = (int **)malloc(sizeof(int *) * (*returnSize));
for (int i = 0; i < *returnSize; ++i)
{
res[i] = (int *)malloc(sizeof(int) * ((*returnColumnSizes)[i]));
memcpy(res[i], data[i], sizeof(int) * ((*returnColumnSizes)[i]));
}
return res;
}
/********end of malloc result********/
void addOneResult(int (*staticRes)[30], int *resSize, int *resColSize, int *data, int dataSize)
{
memcpy(staticRes[*resSize], data, sizeof(int) * dataSize);
resColSize[*resSize] = dataSize;
++*resSize;
}
bool dfs(int *candidates, int candidatesSize, int index, int target, int *data, int dataSize, int (*staticRes)[30], int *resSize, int *resColSize)
{
if (target < 0)
return true;
if (target == 0)
{
addOneResult(staticRes, resSize, resColSize, data, dataSize);
return true;
}
for (int i = index; i < candidatesSize; ++i)
{
if (i != index && candidates[i] == candidates[i - 1]) //remove dumplicate
continue;
data[dataSize] = candidates[i];
if (dfs(candidates, candidatesSize, i + 1, target - candidates[i], data, dataSize + 1, staticRes, resSize, resColSize))
break;
}
return false;
}
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int **combinationSum2(int *candidates, int candidatesSize, int target, int *returnSize, int **returnColumnSizes)
{
static int staticRes[10000][30], staticResColSize[10000];
int data[30];
*returnSize = 0;
qsort(candidates, candidatesSize, sizeof(int), cmp);
dfs(candidates, candidatesSize, 0, target, data, 0, staticRes, returnSize, staticResColSize);
return mallocRes(staticRes, *returnSize, staticResColSize, returnSize, returnColumnSizes);
} |
nistefan/cmssw | FWCore/Integration/test/ProducerWithPSetDesc.cc | #include "FWCore/Integration/test/ProducerWithPSetDesc.h"
#include "DataFormats/TestObjects/interface/ThingCollection.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/getFixedSizeArray.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/ParameterSet/interface/ParameterDescriptionBase.h"
#include "FWCore/ParameterSet/interface/ParameterDescription.h"
#include "FWCore/ParameterSet/interface/ParameterDescriptionNode.h"
#include "FWCore/ParameterSet/interface/ParameterWildcard.h"
#include "FWCore/ParameterSet/interface/EmptyGroupDescription.h"
#include "DataFormats/Provenance/interface/EventRange.h"
#include "DataFormats/Provenance/interface/LuminosityBlockID.h"
#include "DataFormats/Provenance/interface/EventID.h"
#include "FWCore/Utilities/interface/InputTag.h"
#include "FWCore/ParameterSet/interface/FileInPath.h"
#include <vector>
#include <limits>
#include <string>
#include <iostream>
namespace edmtest {
ProducerWithPSetDesc::ProducerWithPSetDesc(edm::ParameterSet const& ps) {
testingAutoGeneratedCfi = ps.getUntrackedParameter<bool>("testingAutoGeneratedCfi", true);
assert(ps.getParameter<int>("p_int") == 2147483647);
assert(ps.getUntrackedParameter<int>("p_int_untracked") == -2147483647);
if (testingAutoGeneratedCfi) assert(ps.getParameter<int>("p_int_opt") == 0);
if (testingAutoGeneratedCfi) {
assert(ps.getUntrackedParameter<int>("p_int_optuntracked") == 7);
assert(!ps.exists("p_int_opt_nd"));
assert(!ps.exists("p_int_optuntracked_nd"));
} else {
assert(!ps.exists("p_int_optuntracked"));
assert(ps.getParameter<int>("p_int_opt_nd") == 11);
assert(ps.getUntrackedParameter<int>("p_int_optuntracked_nd") == 12);
}
std::vector<int> vint;
vint = ps.getParameter<std::vector<int> >("vint1");
assert(vint.empty());
vint = ps.getParameter<std::vector<int> >("vint2");
assert(vint[0] == 2147483647);
vint = ps.getParameter<std::vector<int> >("vint3");
assert(vint[0] == 2147483647);
assert(vint[1] == -2147483647);
std::array<int, 2> testArray = edm::getFixedSizeArray<int, 2>(ps, std::string("vint3"));
assert(testArray[0] == 2147483647);
assert(testArray[1] == -2147483647);
std::array<int, 2> testArray1 = edm::getFixedSizeArray<int, 2>(ps, "vint3");
assert(testArray1[0] == 2147483647);
assert(testArray1[1] == -2147483647);
vint = ps.getParameter<std::vector<int> >("vint4");
assert(vint[0] == 2147483647);
assert(vint[1] == -2147483647);
assert(vint[2] == 0);
assert(ps.getParameter<unsigned>("uint1") == 4294967295U);
assert(ps.getUntrackedParameter<unsigned>("uint2") == 0);
std::vector<unsigned> vuint;
vuint = ps.getParameter<std::vector<unsigned> >("vuint1");
assert(vuint.empty());
vuint = ps.getParameter<std::vector<unsigned> >("vuint2");
assert(vuint[0] == 4294967295U);
vuint = ps.getParameter<std::vector<unsigned> >("vuint3");
assert(vuint[0] == 4294967295U);
assert(vuint[1] == 0);
vuint = ps.getParameter<std::vector<unsigned> >("vuint4");
assert(vuint[0] == 4294967295U);
assert(vuint[1] == 0);
assert(vuint[2] == 11);
assert(ps.getParameter<long long>("int64v1") == 9000000000000000000LL);
assert(ps.getParameter<long long>("int64v2") == -9000000000000000000LL);
assert(ps.getParameter<long long>("int64v3") == 0);
std::vector<long long> vint64;
vint64 = ps.getParameter<std::vector<long long> >("vint64v1");
assert(vint64.empty());
vint64 = ps.getParameter<std::vector<long long> >("vint64v2");
assert(vint64[0] == 9000000000000000000LL);
vint64 = ps.getParameter<std::vector<long long> >("vint64v3");
assert(vint64[0] == 9000000000000000000LL);
assert(vint64[1] == -9000000000000000000LL);
vint64 = ps.getParameter<std::vector<long long> >("vint64v4");
assert(vint64[0] == 9000000000000000000LL);
assert(vint64[1] == -9000000000000000000LL);
assert(vint64[2] == 0);
assert(ps.getParameter<unsigned long long>("uint64v1") == 18000000000000000000ULL);
assert(ps.getUntrackedParameter<unsigned long long>("uint64v2") == 0);
std::vector<unsigned long long> vuint64;
vuint64 = ps.getParameter<std::vector<unsigned long long> >("vuint64v1");
assert(vuint64.empty());
vuint64 = ps.getParameter<std::vector<unsigned long long> >("vuint64v2");
assert(vuint64[0] == 18000000000000000000ULL);
vuint64 = ps.getParameter<std::vector<unsigned long long> >("vuint64v3");
assert(vuint64[0] == 18000000000000000000ULL);
assert(vuint64[1] == 0);
vuint64 = ps.getParameter<std::vector<unsigned long long> >("vuint64v4");
assert(vuint64[0] == 18000000000000000000ULL);
assert(vuint64[1] == 0);
assert(vuint64[2] == 11);
// This one does not work because the precision in the ParameterSet stringified
// format is 16 instead of 17.
// assert(ps.getParameter<double>("doublev1") == std::numeric_limits<double>::min());
assert(ps.getUntrackedParameter<double>("doublev2") == 0.0);
assert(fabs(ps.getUntrackedParameter<double>("doublev3") - 0.3)< 0.0000001);
std::vector<double> vdouble;
vdouble = ps.getParameter<std::vector<double> >("vdoublev1");
assert(vdouble.empty());
// cmsRun will fail with a value this big
// vdouble.push_back(std::numeric_limits<double>::max());
// This works though
vdouble = ps.getParameter<std::vector<double> >("vdoublev2");
assert(vdouble[0] == 1e+300);
vdouble = ps.getParameter<std::vector<double> >("vdoublev3");
assert(vdouble[0] == 1e+300);
assert(vdouble[1] == 0.0);
vdouble = ps.getParameter<std::vector<double> >("vdoublev4");
assert(vdouble[0] == 1e+300);
assert(vdouble[1] == 0.0);
assert(vdouble[2] == 11.0);
vdouble = ps.getParameter<std::vector<double> >("vdoublev5");
assert(vdouble[0] == 1e+300);
assert(vdouble[1] == 0.0);
assert(vdouble[2] == 11.0);
assert(fabs(vdouble[3] - 0.3)< 0.0000001);
assert(ps.getParameter<bool>("boolv1") == true);
assert(ps.getParameter<bool>("boolv2") == false);
std::string test("Hello");
assert(ps.getParameter<std::string>("stringv1") == test);
test.clear();
assert(ps.getParameter<std::string>("stringv2") == test);
std::vector<std::string> vstring;
vstring = ps.getParameter<std::vector<std::string> >("vstringv1");
assert(vstring.empty());
vstring = ps.getParameter<std::vector<std::string> >("vstringv2");
assert(vstring[0] == std::string("Hello"));
vstring = ps.getParameter<std::vector<std::string> >("vstringv3");
assert(vstring[0] == std::string("Hello"));
assert(vstring[1] == std::string("World"));
vstring = ps.getParameter<std::vector<std::string> >("vstringv4");
assert(vstring[0] == std::string("Hello"));
assert(vstring[1] == std::string("World"));
assert(vstring[2] == std::string(""));
edm::EventID eventID1(11, 0, 12);
assert(ps.getParameter<edm::EventID>("eventIDv1") == eventID1);
edm::EventID eventID2(101, 0, 102);
assert(ps.getParameter<edm::EventID>("eventIDv2") == eventID2);
std::vector<edm::EventID> vEventID;
vEventID = ps.getParameter<std::vector<edm::EventID> >("vEventIDv1");
assert(vEventID.empty());
vEventID = ps.getParameter<std::vector<edm::EventID> >("vEventIDv2");
assert(vEventID[0] == edm::EventID(1000, 0, 1100));
vEventID = ps.getParameter<std::vector<edm::EventID> >("vEventIDv3");
assert(vEventID[0] == edm::EventID(1000, 0, 1100));
assert(vEventID[1] == edm::EventID(10000, 0, 11000));
vEventID = ps.getParameter<std::vector<edm::EventID> >("vEventIDv4");
assert(vEventID[0] == edm::EventID(1000, 0, 1100));
assert(vEventID[1] == edm::EventID(10000, 0, 11000));
assert(vEventID[2] == edm::EventID(100000, 0, 110000));
edm::LuminosityBlockID luminosityID1(11, 12);
assert(ps.getParameter<edm::LuminosityBlockID>("luminosityIDv1") == luminosityID1);
edm::LuminosityBlockID luminosityID2(101, 102);
assert(ps.getParameter<edm::LuminosityBlockID>("luminosityIDv2") == luminosityID2);
std::vector<edm::LuminosityBlockID> vLuminosityBlockID;
vLuminosityBlockID = ps.getParameter<std::vector<edm::LuminosityBlockID> >("vLuminosityBlockIDv1");
assert(vLuminosityBlockID.empty());
vLuminosityBlockID = ps.getParameter<std::vector<edm::LuminosityBlockID> >("vLuminosityBlockIDv2");
assert(vLuminosityBlockID[0] == edm::LuminosityBlockID(1000, 1100));
vLuminosityBlockID = ps.getParameter<std::vector<edm::LuminosityBlockID> >("vLuminosityBlockIDv3");
assert(vLuminosityBlockID[0] == edm::LuminosityBlockID(1000, 1100));
assert(vLuminosityBlockID[1] == edm::LuminosityBlockID(10000, 11000));
vLuminosityBlockID = ps.getParameter<std::vector<edm::LuminosityBlockID> >("vLuminosityBlockIDv4");
assert(vLuminosityBlockID[0] == edm::LuminosityBlockID(1000, 1100));
assert(vLuminosityBlockID[1] == edm::LuminosityBlockID(10000, 11000));
assert(vLuminosityBlockID[2] == edm::LuminosityBlockID(100000, 110000));
edm::LuminosityBlockRange lumiRange1(1,1, 9,9);
assert(ps.getParameter<edm::LuminosityBlockRange>("lumiRangev1").startLumiID() ==
lumiRange1.startLumiID());
assert(ps.getParameter<edm::LuminosityBlockRange>("lumiRangev1").endLumiID() ==
lumiRange1.endLumiID());
edm::LuminosityBlockRange lumiRange2(3,4, 1000,1000);
assert(ps.getParameter<edm::LuminosityBlockRange>("lumiRangev2").startLumiID() ==
lumiRange2.startLumiID());
assert(ps.getParameter<edm::LuminosityBlockRange>("lumiRangev2").endLumiID() ==
lumiRange2.endLumiID());
std::vector<edm::LuminosityBlockRange> vLumiRange;
vLumiRange = ps.getParameter<std::vector<edm::LuminosityBlockRange> >("vLumiRangev1");
assert(vLumiRange.empty());
vLumiRange = ps.getParameter<std::vector<edm::LuminosityBlockRange> >("vLumiRangev2");
assert(vLumiRange[0].startLumiID() == lumiRange1.startLumiID());
vLumiRange = ps.getParameter<std::vector<edm::LuminosityBlockRange> >("vLumiRangev3");
assert(vLumiRange[0].startLumiID() == lumiRange1.startLumiID());
assert(vLumiRange[1].startLumiID() == lumiRange2.startLumiID());
assert(vLumiRange[1].endLumiID() == lumiRange2.endLumiID());
edm::EventRange eventRange1(1,0,1, 8,0,8);
assert(ps.getParameter<edm::EventRange>("eventRangev1").startEventID() ==
eventRange1.startEventID());
assert(ps.getParameter<edm::EventRange>("eventRangev1").endEventID() ==
eventRange1.endEventID());
edm::EventRange eventRange2(3,0,4, 1001,0,1002);
assert(ps.getParameter<edm::EventRange>("eventRangev2").startEventID() ==
eventRange2.startEventID());
assert(ps.getParameter<edm::EventRange>("eventRangev2").endEventID() ==
eventRange2.endEventID());
std::vector<edm::EventRange> vEventRange;
vEventRange = ps.getParameter<std::vector<edm::EventRange> >("vEventRangev1");
assert(vEventRange.empty());
vEventRange = ps.getParameter<std::vector<edm::EventRange> >("vEventRangev2");
assert(vEventRange[0].startEventID() == eventRange1.startEventID());
vEventRange = ps.getParameter<std::vector<edm::EventRange> >("vEventRangev3");
assert(vEventRange[0].startEventID() == eventRange1.startEventID());
assert(vEventRange[1].startEventID() == eventRange2.startEventID());
edm::InputTag inputTag1("One", "Two", "Three");
assert(ps.getParameter<edm::InputTag>("inputTagv1") == inputTag1);
edm::InputTag inputTag2("One", "Two");
assert(ps.getParameter<edm::InputTag>("inputTagv2") == inputTag2);
edm::InputTag inputTag3("One");
assert(ps.getParameter<edm::InputTag>("inputTagv3") == inputTag3);
edm::InputTag inputTag4("One", "", "Three");
assert(ps.getParameter<edm::InputTag>("inputTagv4") == inputTag4);
std::vector<edm::InputTag> vInputTag;
vInputTag = ps.getParameter<std::vector<edm::InputTag> >("vInputTagv1");
assert(vInputTag.empty());
vInputTag = ps.getParameter<std::vector<edm::InputTag> >("vInputTagv2");
assert(vInputTag[0] == inputTag1);
vInputTag = ps.getParameter<std::vector<edm::InputTag> >("vInputTagv3");
assert(vInputTag[0] == inputTag1);
assert(vInputTag[1] == inputTag2);
vInputTag = ps.getParameter<std::vector<edm::InputTag> >("vInputTagv4");
assert(vInputTag[0] == inputTag1);
assert(vInputTag[1] == inputTag2);
assert(vInputTag[2] == inputTag3);
vInputTag = ps.getParameter<std::vector<edm::InputTag> >("vInputTagv5");
assert(vInputTag[0] == inputTag1);
assert(vInputTag[1] == inputTag2);
assert(vInputTag[2] == inputTag3);
assert(vInputTag[3] == inputTag4);
// For purposes of the test, this just needs to point to any file
// that exists. I guess pointing to itself cannot ever fail ...
edm::FileInPath fileInPath("FWCore/Integration/test/ProducerWithPSetDesc.cc");
assert(fileInPath == ps.getParameter<edm::FileInPath>("fileInPath"));
edm::ParameterSet const& pset = ps.getParameterSet("bar");
assert(pset.getParameter<unsigned>("Drinks") == 5U);
assert(pset.getUntrackedParameter<unsigned>("uDrinks") == 5U);
if (testingAutoGeneratedCfi) assert(pset.getParameter<unsigned>("oDrinks") == 5U);
if (testingAutoGeneratedCfi) assert(pset.getUntrackedParameter<unsigned>("ouDrinks") == 5U);
//std::vector<edm::ParameterSet> const& vpsetUntracked =
// ps.getUntrackedParameterSetVector("test104");
std::vector<edm::ParameterSet> const& vpset =
ps.getParameterSetVector("bars");
assert(vpset.size() == 2U);
edm::ParameterSet pset0 = vpset[0];
assert(pset0.getParameter<unsigned>("Drinks") == 5U);
assert(pset0.getUntrackedParameter<unsigned>("uDrinks") == 5U);
assert(pset0.getParameter<unsigned>("oDrinks") == 11U);
assert(pset0.exists("ouDrinks") == false);
assert(pset0.exists("ndoDrinks") == false);
assert(pset0.exists("ndouDrinks") == false);
// assert(pset0.getUntrackedParameter<unsigned>("ndouDrinks") == 5);
edm::ParameterSet pset1 = vpset[1];
assert(pset1.getParameter<unsigned>("Drinks") == 5U);
assert(pset1.getUntrackedParameter<unsigned>("uDrinks") == 5U);
assert(pset1.getParameter<unsigned>("oDrinks") == 11U);
assert(pset1.getUntrackedParameter<unsigned>("ouDrinks") == 11U);
assert(pset1.exists("ndoDrinks") == false);
assert(pset1.getUntrackedParameter<unsigned>("ndouDrinks") == 11U);
assert(ps.getParameter<double>("test1") == 0.1);
if (testingAutoGeneratedCfi) {
assert(ps.getParameter<double>("test2") == 0.2);
assert(ps.exists("test3") == false);
assert(ps.getParameter<std::string>("testA") == std::string("fooA"));
assert(ps.getParameter<int>("testB") == 100);
assert(ps.getParameter<int>("testC") == 101);
assert(ps.getParameter<int>("oiswitch") == 1);
assert(ps.getParameter<double>("oivalue1") == 101.0);
assert(ps.getParameter<double>("oivalue2") == 101.0);
} else {
assert(!ps.exists("test2"));
assert(!ps.exists("test3"));
assert(!ps.exists("testA"));
assert(!ps.exists("testB"));
assert(!ps.exists("testC"));
assert(!ps.exists("oiswitch"));
assert(!ps.exists("oivalue1"));
assert(!ps.exists("oivalue2"));
}
edm::ParameterSet const& deeplyNestedPSet = pset1.getParameterSet("testDeeplyNested");
if (testingAutoGeneratedCfi) {
assert(!deeplyNestedPSet.exists("ndiswitch"));
assert(!deeplyNestedPSet.exists("ndivalue1"));
assert(!deeplyNestedPSet.exists("ndivalue2"));
} else {
assert(!deeplyNestedPSet.exists("ndiswitch"));
assert(!deeplyNestedPSet.exists("ndivalue1"));
assert(!deeplyNestedPSet.exists("ndivalue2"));
}
assert(deeplyNestedPSet.getParameter<bool>("bswitch") == false);
assert(deeplyNestedPSet.getParameter<double>("bvalue1") == 101.0);
assert(deeplyNestedPSet.getParameter<double>("bvalue2") == 101.0);
assert(!deeplyNestedPSet.exists("bvalue"));
assert(deeplyNestedPSet.getParameter<int>("iswitch") == 1);
assert(deeplyNestedPSet.getParameter<double>("ivalue1") == 101.0);
assert(deeplyNestedPSet.getUntrackedParameter<double>("ivalue2") == 101.0);
assert(!deeplyNestedPSet.exists("ivalue"));
assert(deeplyNestedPSet.getParameter<std::string>("sswitch") == std::string("1"));
assert(deeplyNestedPSet.getParameter<double>("svalue1") == 101.0);
assert(deeplyNestedPSet.getParameter<double>("svalue2") == 101.0);
assert(!deeplyNestedPSet.exists("svalue"));
if (testingAutoGeneratedCfi) {
edm::ParameterSet const& pset11 = ps.getParameterSet("subpset");
assert(pset11.getParameter<int>("xvalue") == 11);
edm::ParameterSet const& pset111 = pset11.getUntrackedParameterSet("bar");
assert(pset111.getParameter<unsigned>("Drinks") == 5U);
assert(pset111.getUntrackedParameter<unsigned>("uDrinks") == 5U);
assert(pset111.getParameter<unsigned>("oDrinks") == 5U);
assert(pset111.getUntrackedParameter<unsigned>("ouDrinks") == 5U);
}
edm::ParameterSet const& psetXor = ps.getParameterSet("xorPset");
assert(psetXor.getParameter<std::string>("name1") == std::string("11"));
assert(!psetXor.exists("name2"));
if (testingAutoGeneratedCfi) {
assert(psetXor.getParameter<std::string>("name") == std::string("11"));
} else {
assert(psetXor.getParameter<unsigned>("name") == 11U);
}
edm::ParameterSet const& psetOr = ps.getParameterSet("orPset");
assert(!psetOr.exists("z1"));
assert(!psetOr.exists("z2"));
if (testingAutoGeneratedCfi) {
assert(psetOr.getParameter<std::string>("x1") == std::string("11"));
assert(!psetOr.exists("x2"));
assert(psetOr.getParameter<std::string>("y1") == std::string("11"));
assert(!psetOr.exists("y2"));
} else {
assert(!psetOr.exists("x1"));
assert(psetOr.getParameter<unsigned>("x2") == 11U);
assert(psetOr.getParameter<std::string>("y1") == std::string("11"));
assert(psetOr.getParameter<unsigned>("y2") == 11U);
}
edm::ParameterSet const& psetAnd = ps.getParameterSet("andPset");
assert(psetAnd.getParameter<std::string>("x1") == std::string("11"));
assert(psetAnd.getParameter<unsigned>("x2") == 11U);
assert(psetAnd.getParameter<std::string>("y1") == std::string("11"));
assert(psetAnd.getParameter<unsigned>("y2") == 11U);
assert(psetAnd.getParameter<std::string>("z1") == std::string("11"));
assert(psetAnd.getParameter<unsigned>("z2") == 11U);
assert(psetAnd.getParameter<std::string>("b1") == std::string("11"));
assert(psetAnd.getParameter<unsigned>("b2") == 11U);
assert(psetAnd.getParameter<unsigned>("b3") == 11U);
assert(psetAnd.getParameter<unsigned>("b4") == 11U);
assert(psetAnd.getParameter<unsigned>("b5") == 11U);
assert(psetAnd.getParameter<unsigned>("b6") == 11U);
if (testingAutoGeneratedCfi) {
assert(!psetAnd.exists("a1"));
assert(!psetAnd.exists("a2"));
} else {
assert(psetAnd.getParameter<std::string>("a1") == std::string("11"));
assert(psetAnd.getParameter<unsigned>("a2") == 11U);
}
edm::ParameterSet const& psetIfExists = ps.getParameterSet("ifExistsPset");
assert(psetIfExists.getParameter<unsigned>("x1") == 11U);
assert(psetIfExists.getParameter<std::string>("x2") == std::string("11"));
assert(psetIfExists.getParameter<unsigned>("z1") == 11U);
assert(psetIfExists.getParameter<std::string>("z2") == std::string("11"));
if (testingAutoGeneratedCfi) {
assert(!psetIfExists.exists("y1"));
assert(!psetIfExists.exists("y2"));
} else {
assert(psetIfExists.getParameter<unsigned>("y1") == 11U);
assert(!psetIfExists.exists("y2"));
}
edm::ParameterSet const& psetAllowed = ps.getParameterSet("allowedLabelsPset");
if (testingAutoGeneratedCfi) {
assert(psetAllowed.getParameter<std::vector<std::string> >("testAllowedLabels") == std::vector<std::string>());
assert(psetAllowed.getUntrackedParameter<std::vector<std::string> >("testAllowedLabelsUntracked") ==
std::vector<std::string>());
assert(!psetAllowed.exists("testOptAllowedLabels"));
assert(!psetAllowed.exists("testOptAllowedLabelsUntracked"));
}
produces<ThingCollection>();
}
ProducerWithPSetDesc::~ProducerWithPSetDesc() { }
void ProducerWithPSetDesc::produce(edm::Event& e, edm::EventSetup const&) {
// This serves no purpose, I just put it here so the module does something
// Probably could just make this method do nothing and it would not
// affect the test.
auto result = std::make_unique<ThingCollection>(); //Empty
e.put(std::move(result));
}
void
ProducerWithPSetDesc::
fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
edm::ParameterSetDescription iDesc;
// Try to exercise the description code by adding all different
// types of parameters with a large range of values. Also
// nested ParameterSets and vectors of them at the end.
iDesc.addOptionalUntracked<bool>("testingAutoGeneratedCfi", true);
edm::ParameterDescriptionNode* pn;
pn = iDesc.add<int>("p_int", 2147483647);
pn->setComment("A big integer. I am trying to test the wrapping of comments in"
" the printed output by putting in a long comment to see if it gets"
" wrapped OK. The comment should get indented to the second column"
" indent on every line. By default newlines should be inserted between"
" words to make the lines fit in the terminal screen width. There is "
"a command line parameter that can be set to override this width to "
"any desired value. If there is no terminal then it should default to "
"80. The logic for setting the width is in edmPluginHelp.cpp");
iDesc.addUntracked<int>("p_int_untracked", -2147483647);
iDesc.addOptional<int>("p_int_opt", 0);
iDesc.addOptionalUntracked<int>("p_int_optuntracked", 7);
iDesc.addOptional<int>("p_int_opt_nd");
iDesc.addOptionalUntracked<int>("p_int_optuntracked_nd");
std::vector<int> vint;
iDesc.add<std::vector<int> >("vint1", vint);
vint.push_back(2147483647);
iDesc.add<std::vector<int> >(std::string("vint2"), vint);
vint.push_back(-2147483647);
iDesc.add<std::vector<int> >("vint3", vint);
vint.push_back(0);
iDesc.add<std::vector<int> >("vint4", vint);
iDesc.add<unsigned>("uint1", 4294967295U);
iDesc.addUntracked<unsigned>("uint2", 0);
std::vector<unsigned> vuint;
iDesc.add<std::vector<unsigned> >("vuint1", vuint);
vuint.push_back(4294967295U);
iDesc.add<std::vector<unsigned> >("vuint2", vuint);
vuint.push_back(0);
iDesc.add<std::vector<unsigned> >("vuint3", vuint);
vuint.push_back(11);
iDesc.add<std::vector<unsigned> >("vuint4", vuint);
vuint.push_back(21);
vuint.push_back(31);
vuint.push_back(41);
iDesc.add<std::vector<unsigned> >("vuint5", vuint);
iDesc.add<long long>("int64v1", 9000000000000000000LL);
iDesc.add<long long>("int64v2", -9000000000000000000LL);
iDesc.add<long long>("int64v3", 0);
std::vector<long long> vint64;
iDesc.add<std::vector<long long> >("vint64v1", vint64);
vint64.push_back(9000000000000000000LL);
iDesc.add<std::vector<long long> >("vint64v2", vint64);
vint64.push_back(-9000000000000000000LL);
iDesc.add<std::vector<long long> >("vint64v3", vint64);
vint64.push_back(0);
iDesc.add<std::vector<long long> >("vint64v4", vint64);
iDesc.add<unsigned long long>("uint64v1", 18000000000000000000ULL);
iDesc.addUntracked<unsigned long long>("uint64v2", 0);
std::vector<unsigned long long> vuint64;
iDesc.add<std::vector<unsigned long long> >("vuint64v1", vuint64);
vuint64.push_back(18000000000000000000ULL);
iDesc.add<std::vector<unsigned long long> >("vuint64v2", vuint64);
vuint64.push_back(0);
iDesc.add<std::vector<unsigned long long> >("vuint64v3", vuint64);
vuint64.push_back(11);
iDesc.add<std::vector<unsigned long long> >("vuint64v4", vuint64);
iDesc.add<double>("doublev1", std::numeric_limits<double>::min());
iDesc.addUntracked<double>("doublev2", 0.0);
iDesc.addUntracked<double>("doublev3", 0.3);
std::vector<double> vdouble;
iDesc.add<std::vector<double> >("vdoublev1", vdouble);
// cmsRun will fail with a value this big
// vdouble.push_back(std::numeric_limits<double>::max());
// This works though
vdouble.push_back(1e+300);
iDesc.add<std::vector<double> >("vdoublev2", vdouble);
vdouble.push_back(0.0);
iDesc.add<std::vector<double> >("vdoublev3", vdouble);
vdouble.push_back(11.0);
iDesc.add<std::vector<double> >("vdoublev4", vdouble);
vdouble.push_back(0.3);
iDesc.add<std::vector<double> >("vdoublev5", vdouble);
iDesc.add<bool>("boolv1", true);
iDesc.add<bool>("boolv2", false);
std::string test("Hello");
iDesc.add<std::string>("stringv1", test);
test.clear();
iDesc.add<std::string>("stringv2", test);
std::vector<std::string> vstring;
iDesc.add<std::vector<std::string> >("vstringv1", vstring);
test = "Hello";
vstring.push_back(test);
iDesc.add<std::vector<std::string> >("vstringv2", vstring);
test = "World";
vstring.push_back(test);
iDesc.add<std::vector<std::string> >("vstringv3", vstring);
test = "";
vstring.push_back(test);
iDesc.add<std::vector<std::string> >("vstringv4", vstring);
edm::EventID eventID(11, 0, 12);
iDesc.add<edm::EventID>("eventIDv1", eventID);
edm::EventID eventID2(101, 0, 102);
iDesc.add<edm::EventID>("eventIDv2", eventID2);
std::vector<edm::EventID> vEventID;
iDesc.add<std::vector<edm::EventID> >("vEventIDv1", vEventID);
edm::EventID eventID3(1000, 0, 1100);
vEventID.push_back(eventID3);
iDesc.add<std::vector<edm::EventID> >("vEventIDv2", vEventID);
edm::EventID eventID4(10000, 0, 11000);
vEventID.push_back(eventID4);
iDesc.add<std::vector<edm::EventID> >("vEventIDv3", vEventID);
edm::EventID eventID5(100000, 0, 110000);
vEventID.push_back(eventID5);
iDesc.add<std::vector<edm::EventID> >("vEventIDv4", vEventID);
edm::LuminosityBlockID luminosityID(11, 12);
iDesc.add<edm::LuminosityBlockID>("luminosityIDv1", luminosityID);
edm::LuminosityBlockID luminosityID2(101, 102);
iDesc.add<edm::LuminosityBlockID>("luminosityIDv2", luminosityID2);
std::vector<edm::LuminosityBlockID> vLuminosityBlockID;
iDesc.add<std::vector<edm::LuminosityBlockID> >("vLuminosityBlockIDv1", vLuminosityBlockID);
edm::LuminosityBlockID luminosityID3(1000, 1100);
vLuminosityBlockID.push_back(luminosityID3);
iDesc.add<std::vector<edm::LuminosityBlockID> >("vLuminosityBlockIDv2", vLuminosityBlockID);
edm::LuminosityBlockID luminosityID4(10000, 11000);
vLuminosityBlockID.push_back(luminosityID4);
iDesc.add<std::vector<edm::LuminosityBlockID> >("vLuminosityBlockIDv3", vLuminosityBlockID);
edm::LuminosityBlockID luminosityID5(100000, 110000);
vLuminosityBlockID.push_back(luminosityID5);
iDesc.add<std::vector<edm::LuminosityBlockID> >("vLuminosityBlockIDv4", vLuminosityBlockID);
edm::LuminosityBlockRange lumiRange(1,1, 9,9);
iDesc.add<edm::LuminosityBlockRange>("lumiRangev1", lumiRange);
edm::LuminosityBlockRange lumiRange2(3,4, 1000,1000);
iDesc.add<edm::LuminosityBlockRange>("lumiRangev2", lumiRange2);
std::vector<edm::LuminosityBlockRange> vLumiRange;
iDesc.add<std::vector<edm::LuminosityBlockRange> >("vLumiRangev1", vLumiRange);
vLumiRange.push_back(lumiRange);
iDesc.add<std::vector<edm::LuminosityBlockRange> >("vLumiRangev2", vLumiRange);
vLumiRange.push_back(lumiRange2);
iDesc.add<std::vector<edm::LuminosityBlockRange> >("vLumiRangev3", vLumiRange);
edm::EventRange eventRange(1,0,1, 8,0,8);
iDesc.add<edm::EventRange>("eventRangev1", eventRange);
edm::EventRange eventRange2(3,0,4, 1001,0,1002);
iDesc.add<edm::EventRange>("eventRangev2", eventRange2);
std::vector<edm::EventRange> vEventRange;
iDesc.add<std::vector<edm::EventRange> >("vEventRangev1", vEventRange);
vEventRange.push_back(eventRange);
iDesc.add<std::vector<edm::EventRange> >("vEventRangev2", vEventRange);
vEventRange.push_back(eventRange2);
iDesc.add<std::vector<edm::EventRange> >("vEventRangev3", vEventRange);
edm::InputTag inputTag("One", "Two", "Three");
iDesc.add<edm::InputTag>("inputTagv1", inputTag);
edm::InputTag inputTag2("One", "Two");
iDesc.add<edm::InputTag>("inputTagv2", inputTag2);
edm::InputTag inputTag3("One");
iDesc.add<edm::InputTag>("inputTagv3", inputTag3);
edm::InputTag inputTag4("One", "", "Three");
iDesc.add<edm::InputTag>("inputTagv4", inputTag4);
std::vector<edm::InputTag> vInputTag;
iDesc.add<std::vector<edm::InputTag> >("vInputTagv1", vInputTag);
vInputTag.push_back(inputTag);
iDesc.add<std::vector<edm::InputTag> >("vInputTagv2", vInputTag);
vInputTag.push_back(inputTag2);
iDesc.add<std::vector<edm::InputTag> >("vInputTagv3", vInputTag);
vInputTag.push_back(inputTag3);
iDesc.add<std::vector<edm::InputTag> >("vInputTagv4", vInputTag);
vInputTag.push_back(inputTag4);
iDesc.add<std::vector<edm::InputTag> >("vInputTagv5", vInputTag);
// For purposes of the test, this just needs to point to any file
// that exists. I guess pointing to itself cannot ever fail ...
edm::FileInPath fileInPath("FWCore/Integration/test/ProducerWithPSetDesc.cc");
iDesc.add<edm::FileInPath>("fileInPath", fileInPath);
edm::EmptyGroupDescription emptyGroup;
iDesc.addNode(emptyGroup);
edm::ParameterSetDescription bar;
bar.add<unsigned int>("Drinks", 5);
bar.addUntracked<unsigned int>("uDrinks", 5);
bar.addOptional<unsigned int>("oDrinks", 5);
bar.addOptionalUntracked<unsigned int>("ouDrinks", 5);
iDesc.add("bar", bar);
edm::ParameterDescription<edm::ParameterSetDescription> test101("test101", bar, true);
iDesc.addOptionalNode(test101, false);
edm::ParameterSetDescription barx;
barx.add<unsigned int>("Drinks", 5);
barx.addUntracked<unsigned int>("uDrinks", 5);
barx.addOptional<unsigned int>("oDrinks", 5);
barx.addOptionalUntracked<unsigned int>("ouDrinks", 5);
barx.addOptional<unsigned int>("ndoDrinks");
barx.addOptionalUntracked<unsigned int>("ndouDrinks");
edm::ParameterDescription<std::vector<edm::ParameterSet> > test102("test102", edm::ParameterSetDescription(), true);
iDesc.addOptionalNode(test102, false);
edm::ParameterDescription<std::vector<edm::ParameterSet> > test103(std::string("test103"), barx, true);
iDesc.addOptionalNode(test103, false);
std::vector<edm::ParameterSet> defaultVPSet104;
defaultVPSet104.push_back(edm::ParameterSet());
edm::ParameterDescription<std::vector<edm::ParameterSet> > test104(std::string("test104"), barx, false, defaultVPSet104);
iDesc.addNode(test104);
std::vector<edm::ParameterSet> defaultVPSet105;
edm::ParameterDescription<std::vector<edm::ParameterSet> > test105(std::string("test105"), barx, false, defaultVPSet105);
iDesc.addNode(test105);
double d1 = 0.1;
double d2 = 0.2;
double d3 = 0.3;
iDesc.addNode(edm::ParameterDescription<double>("test1", d1, true));
iDesc.addOptionalNode(edm::ParameterDescription<double>("test2", d2, true), true);
// The value in the second argument is not used in this case
iDesc.addOptionalNode(edm::ParameterDescription<double>("test3", d3, true), false);
iDesc.addOptionalNode(edm::ParameterDescription<std::string>("testA", "fooA", true) and
edm::ParameterDescription<int>("testB", 100, true)&&
edm::ParameterDescription<int>("testC", 101, true), true);
iDesc.ifValueOptional(edm::ParameterDescription<int>("oiswitch", 1, true),
0 >> edm::ParameterDescription<int>("oivalue", 100, true) or
1 >> (edm::ParameterDescription<double>("oivalue1", 101.0, true) and
edm::ParameterDescription<double>("oivalue2", 101.0, true)) or
2 >> edm::ParameterDescription<std::string>("oivalue", "102", true), true);
edm::ParameterSetDescription deeplyNested;
bool case0 = true;
bool case1 = false;
deeplyNested.ifValue(edm::ParameterDescription<bool>("bswitch", false, true),
case0 >> edm::ParameterDescription<int>("bvalue", 100, true) or
case1 >> (edm::ParameterDescription<double>("bvalue1", 101.0, true) and
edm::ParameterDescription<double>("bvalue2", 101.0, true)));
deeplyNested.ifValue(edm::ParameterDescription<int>("iswitch", 1, true),
0 >> edm::ParameterDescription<int>("ivalue", 100, true) or
1 >> (edm::ParameterDescription<double>("ivalue1", 101.0, true) and
edm::ParameterDescription<double>("ivalue2", 101.0, false)) or
2 >> edm::ParameterDescription<std::string>("ivalue", "102", true));
deeplyNested.ifValue(edm::ParameterDescription<std::string>("sswitch", std::string("1"), true),
std::string("0") >> edm::ParameterDescription<int>("svalue", 100, true) or
"1" >> (edm::ParameterDescription<double>("svalue1", 101.0, true) and
edm::ParameterDescription<double>("svalue2", 101.0, true)) or
"2" >> edm::ParameterDescription<std::string>("svalue", "102", true));
deeplyNested.ifValueOptional(edm::ParameterDescription<int>("ndiswitch", 1, true),
0 >> edm::ParameterDescription<int>("ndivalue", 100, true) or
1 >> (edm::ParameterDescription<double>("ndivalue1", 101.0, true) and
edm::ParameterDescription<double>("ndivalue2", 101.0, true)) or
2 >> edm::ParameterDescription<std::string>("ndivalue", "102", true), false);
deeplyNested.add<int>("testint", 1000);
barx.add("testDeeplyNested", deeplyNested);
iDesc.add("testDeeplyNested2", deeplyNested);
edm::ParameterSetDescription validator;
validator.add<int>("xvalue", 7);
std::vector<edm::ParameterSet> vDefaults;
edm::ParameterSet vDefaults0;
vDefaults.push_back(vDefaults0);
edm::ParameterSet vDefaults1;
vDefaults1.addParameter<int>("xvalue", 100);
vDefaults.push_back(vDefaults1);
barx.addVPSet("anotherVPSet", validator, vDefaults);
std::vector<edm::ParameterSet> defaultVPSet;
edm::ParameterSet psetInVector1;
psetInVector1.addParameter<unsigned int>("oDrinks", 11U);
defaultVPSet.push_back(psetInVector1);
edm::ParameterSet psetInVector2;
psetInVector2.addParameter<unsigned int>("oDrinks", 11U);
psetInVector2.addUntrackedParameter<unsigned int>("ouDrinks", 11U);
psetInVector2.addUntrackedParameter<unsigned int>("ndouDrinks", 11U);
std::vector<edm::ParameterSet> anotherDefaultVPSet;
anotherDefaultVPSet.push_back(edm::ParameterSet());
edm::ParameterSet anotherParameterSet;
anotherParameterSet.addParameter<int>("xvalue", 17);
anotherDefaultVPSet.push_back(anotherParameterSet);
psetInVector2.addParameter<std::vector<edm::ParameterSet> >("anotherVPSet", anotherDefaultVPSet);
edm::ParameterSet defaultForDeeplyNested;
defaultForDeeplyNested.addParameter<int>("testint",2);
psetInVector2.addParameter<edm::ParameterSet>("testDeeplyNested", defaultForDeeplyNested);
defaultVPSet.push_back(psetInVector2);
iDesc.addVPSet("bars", barx, defaultVPSet);
// Alternate way to add a ParameterSetDescription
edm::ParameterDescriptionBase* parDescription;
parDescription = iDesc.addOptional("subpset", edm::ParameterSetDescription());
edm::ParameterSetDescription* subPsetDescription =
parDescription->parameterSetDescription();
subPsetDescription->add<int>("xvalue", 11);
subPsetDescription->addUntracked<edm::ParameterSetDescription>(std::string("bar"), bar);
// -----------------------------------------------
edm::ParameterSetDescription wildcardPset;
wildcardPset.addOptional<unsigned>("p_uint_opt", 0);
wildcardPset.addWildcard<int>("*");
pn = wildcardPset.addWildcardUntracked<double>(std::string("*"));
pn->setComment("A comment for a wildcard parameter");
std::unique_ptr<edm::ParameterDescriptionNode> wnode = std::make_unique<edm::ParameterWildcard<edm::ParameterSetDescription>>("*", edm::RequireExactlyOne, true);
wildcardPset.addOptionalNode(std::move(wnode), false);
edm::ParameterSetDescription wSet1;
wSet1.add<unsigned int>("Drinks", 5);
std::unique_ptr<edm::ParameterDescriptionNode> wnode2 = std::make_unique<edm::ParameterWildcard<edm::ParameterSetDescription>>("*", edm::RequireAtLeastOne, true, wSet1);
wildcardPset.addOptionalNode(std::move(wnode2), false);
std::unique_ptr<edm::ParameterDescriptionNode> wnode3 = std::make_unique<edm::ParameterWildcard<std::vector<edm::ParameterSet>>>("*", edm::RequireExactlyOne, true);
wildcardPset.addOptionalNode(std::move(wnode3), false);
wSet1.add<unsigned int>("Drinks2", 11);
std::unique_ptr<edm::ParameterDescriptionNode> wnode4 = std::make_unique<edm::ParameterWildcard<std::vector<edm::ParameterSet>>>("*", edm::RequireAtLeastOne, true, wSet1);
wildcardPset.addOptionalNode(std::move(wnode4), false);
iDesc.add("wildcardPset", wildcardPset);
// ---------------------------------------------
std::vector<int> testIntVector;
testIntVector.push_back(21);
testIntVector.push_back(22);
edm::ParameterSetDescription switchPset;
pn = switchPset.ifValue(edm::ParameterDescription<int>("iswitch", 1, true),
0 >> edm::ParameterDescription<std::vector<int> >("ivalue", testIntVector, true) or
1 >> (edm::ParameterDescription<double>("ivalue1", 101.0, true) and
edm::ParameterDescription<double>("ivalue2", 101.0, true)) or
2 >> edm::ParameterDescription<std::string>("ivalue", "102", true));
pn->setComment("Comment for a ParameterSwitch");
switchPset.ifValue(edm::ParameterDescription<bool>("addTeVRefits", true, true),
true >> (edm::ParameterDescription<edm::InputTag>("pickySrc", edm::InputTag(), true) and
edm::ParameterDescription<edm::InputTag>("tpfmsSrc", edm::InputTag(), true)) or
false >> edm::EmptyGroupDescription())->setComment("If TeV refits are added, their sources need to be specified");
iDesc.add("switchPset", switchPset);
// -----------------------------------------------
edm::ParameterSetDescription xorPset;
xorPset.addNode(edm::ParameterDescription<std::string>("name", "11", true) xor
edm::ParameterDescription<unsigned int>("name", 11U, true));
xorPset.addNode(edm::ParameterDescription<std::string>("name1", "11", true) xor
edm::ParameterDescription<unsigned int>("name1", 11U, true));
xorPset.addOptionalNode(edm::ParameterDescription<std::string>("name2", "11", true) xor
edm::ParameterDescription<unsigned int>("name2", 11U, true), false);
xorPset.addNode(edm::ParameterDescription<std::string>("name3", "11", true) xor
edm::ParameterDescription<unsigned int>("name4", 11U, true) xor
test101 xor
test103);
iDesc.add("xorPset", xorPset);
// -----------------------------------------
edm::ParameterSetDescription orPset;
orPset.addNode(edm::ParameterDescription<std::string>("x1", "11", true) or
edm::ParameterDescription<unsigned int>("x2", 11U, true));
orPset.addNode(edm::ParameterDescription<std::string>("y1", "11", true) or
edm::ParameterDescription<unsigned int>("y2", 11U, true));
orPset.addOptionalNode(edm::ParameterDescription<std::string>("z1", "11", true) or
edm::ParameterDescription<unsigned int>("z2", 11U, true) or
test101 or
test103, false);
iDesc.add("orPset", orPset);
// ------------------------------------------------
edm::ParameterSetDescription andPset;
andPset.addNode(edm::ParameterDescription<std::string>("x1", "11", true) and
edm::ParameterDescription<unsigned int>("x2", 11U, true));
andPset.addNode(edm::ParameterDescription<std::string>("y1", "11", true) and
edm::ParameterDescription<unsigned int>("y2", 11U, true));
andPset.addNode(edm::ParameterDescription<std::string>("z1", "11", true) and
edm::ParameterDescription<unsigned int>("z2", 11U, true));
andPset.addOptionalNode(edm::ParameterDescription<std::string>("a1", "11", true) and
edm::ParameterDescription<unsigned int>("a2", 11U, true), false);
andPset.addOptionalNode((edm::ParameterDescription<std::string>("b1", "11", true) and
edm::ParameterDescription<unsigned int>("b2", 11U, true)) and
edm::ParameterDescription<unsigned int>("b3", 11U, true) and
(edm::ParameterDescription<unsigned int>("b4", 11U, true) and
(edm::ParameterDescription<unsigned int>("b5", 11U, true) and
edm::ParameterDescription<unsigned int>("b6", 11U, true))), true);
iDesc.add("andPset", andPset);
// --------------------------------------
edm::ParameterSetDescription ifExistsPset;
ifExistsPset.ifExists(edm::ParameterDescription<unsigned int>("x1", 11U, true),
edm::ParameterDescription<std::string>("x2", "11", true));
ifExistsPset.ifExistsOptional(edm::ParameterDescription<unsigned int>("y1", 11U, true),
edm::ParameterDescription<std::string>("y2", "11", true),
false);
ifExistsPset.ifExists(edm::ParameterDescription<unsigned int>("z1", 11U, true),
edm::ParameterDescription<std::string>("z2", "11", true));
iDesc.add("ifExistsPset", ifExistsPset);
// ------------------------------------------
edm::ParameterSetDescription allowedLabelsPset;
allowedLabelsPset.addOptional<int>("p_int_opt", 0);
allowedLabelsPset.labelsFrom<int>("testAllowedLabels");
allowedLabelsPset.labelsFromUntracked<unsigned>(std::string("testAllowedLabelsUntracked"));
allowedLabelsPset.labelsFromOptional<int>("testOptAllowedLabels", false);
allowedLabelsPset.labelsFromOptionalUntracked<unsigned>(std::string("testOptAllowedLabelsUntracked"), false);
allowedLabelsPset.labelsFromOptionalUntracked<edm::ParameterSetDescription>(std::string("testWithSet"), true, bar);
allowedLabelsPset.labelsFromOptionalUntracked<std::vector<edm::ParameterSet> >(std::string("testWithVectorOfSets"), true, bar);
iDesc.add("allowedLabelsPset", allowedLabelsPset);
edm::ParameterSetDescription noDefaultPset3;
noDefaultPset3.addOptional<int>(std::string("noDefault1"));
noDefaultPset3.addOptional<std::vector<int> >("noDefault2");
noDefaultPset3.addOptional<unsigned>("noDefault3");
noDefaultPset3.addOptional<std::vector<unsigned> >("noDefault4");
noDefaultPset3.addOptional<long long>("noDefault5");
noDefaultPset3.addOptional<std::vector<long long> >("noDefault6");
noDefaultPset3.addOptional<unsigned long long>("noDefault7");
noDefaultPset3.addOptional<std::vector<unsigned long long> >("noDefault8");
noDefaultPset3.addOptional<double>("noDefault9");
noDefaultPset3.addOptional<std::vector<double> >("noDefault10");
noDefaultPset3.addOptional<bool>("noDefault11");
noDefaultPset3.addOptional<std::string>("noDefault12");
noDefaultPset3.addOptional<std::vector<std::string> >("noDefault13");
noDefaultPset3.addOptional<edm::EventID>("noDefault14");
noDefaultPset3.addOptional<std::vector<edm::EventID> >("noDefault15");
noDefaultPset3.addOptional<edm::LuminosityBlockID>("noDefault16");
noDefaultPset3.addOptional<std::vector<edm::LuminosityBlockID> >("noDefault17");
noDefaultPset3.addOptional<edm::InputTag>("noDefault18");
noDefaultPset3.addOptional<std::vector<edm::InputTag> >("noDefault19");
noDefaultPset3.addOptional<edm::FileInPath>("noDefault20");
noDefaultPset3.addOptional<edm::LuminosityBlockRange>("noDefault21");
noDefaultPset3.addOptional<std::vector<edm::LuminosityBlockRange> >("noDefault22");
noDefaultPset3.addOptional<edm::EventRange>("noDefault23");
noDefaultPset3.addOptional<std::vector<edm::EventRange> >("noDefault24");
iDesc.add("noDefaultPset3", noDefaultPset3);
edm::ParameterSetDescription noDefaultPset4;
noDefaultPset4.addOptionalUntracked<int>(std::string("noDefault1"));
noDefaultPset4.addOptionalUntracked<std::vector<int> >("noDefault2");
noDefaultPset4.addOptionalUntracked<unsigned>("noDefault3");
noDefaultPset4.addOptionalUntracked<std::vector<unsigned> >("noDefault4");
noDefaultPset4.addOptionalUntracked<long long>("noDefault5");
noDefaultPset4.addOptionalUntracked<std::vector<long long> >("noDefault6");
noDefaultPset4.addOptionalUntracked<unsigned long long>("noDefault7");
noDefaultPset4.addOptionalUntracked<std::vector<unsigned long long> >("noDefault8");
noDefaultPset4.addOptionalUntracked<double>("noDefault9");
noDefaultPset4.addOptionalUntracked<std::vector<double> >("noDefault10");
noDefaultPset4.addOptionalUntracked<bool>("noDefault11");
noDefaultPset4.addOptionalUntracked<std::string>("noDefault12");
noDefaultPset4.addOptionalUntracked<std::vector<std::string> >("noDefault13");
noDefaultPset4.addOptionalUntracked<edm::EventID>("noDefault14");
noDefaultPset4.addOptionalUntracked<std::vector<edm::EventID> >("noDefault15");
noDefaultPset4.addOptionalUntracked<edm::LuminosityBlockID>("noDefault16");
noDefaultPset4.addOptionalUntracked<std::vector<edm::LuminosityBlockID> >("noDefault17");
noDefaultPset4.addOptionalUntracked<edm::InputTag>("noDefault18");
noDefaultPset4.addOptionalUntracked<std::vector<edm::InputTag> >("noDefault19");
noDefaultPset4.addOptionalUntracked<edm::FileInPath>("noDefault20");
noDefaultPset4.addOptionalUntracked<edm::LuminosityBlockRange>("noDefault21");
noDefaultPset4.addOptionalUntracked<std::vector<edm::LuminosityBlockRange> >("noDefault22");
noDefaultPset4.addOptionalUntracked<edm::EventRange>("noDefault23");
noDefaultPset4.addOptionalUntracked<std::vector<edm::EventRange> >("noDefault24");
iDesc.add("noDefaultPset4", noDefaultPset4);
// ------------------------------------------
descriptions.add("testProducerWithPsetDesc", iDesc);
// ------------------------------------------
edm::ParameterSetDescription iDesc1;
iDesc1.add<int>("p_int", 1);
iDesc1.setAllowAnything();
iDesc1.setComment("A comment for a ParameterSetDescription");
edm::ParameterSetDescription noDefaultPset1;
noDefaultPset1.add<int>(std::string("noDefault1"));
noDefaultPset1.add<std::vector<int> >("noDefault2");
noDefaultPset1.add<unsigned>("noDefault3");
noDefaultPset1.add<std::vector<unsigned> >("noDefault4");
noDefaultPset1.add<long long>("noDefault5");
noDefaultPset1.add<std::vector<long long> >("noDefault6");
noDefaultPset1.add<unsigned long long>("noDefault7");
noDefaultPset1.add<std::vector<unsigned long long> >("noDefault8");
noDefaultPset1.add<double>("noDefault9");
noDefaultPset1.add<std::vector<double> >("noDefault10");
noDefaultPset1.add<bool>("noDefault11");
noDefaultPset1.add<std::string>("noDefault12");
noDefaultPset1.add<std::vector<std::string> >("noDefault13");
noDefaultPset1.add<edm::EventID>("noDefault14");
noDefaultPset1.add<std::vector<edm::EventID> >("noDefault15");
noDefaultPset1.add<edm::LuminosityBlockID>("noDefault16");
noDefaultPset1.add<std::vector<edm::LuminosityBlockID> >("noDefault17");
noDefaultPset1.add<edm::InputTag>("noDefault18");
noDefaultPset1.add<std::vector<edm::InputTag> >("noDefault19");
noDefaultPset1.add<edm::FileInPath>("noDefault20");
noDefaultPset1.add<edm::LuminosityBlockRange>("noDefault21");
noDefaultPset1.add<std::vector<edm::LuminosityBlockRange> >("noDefault22");
noDefaultPset1.add<edm::EventRange>("noDefault23");
noDefaultPset1.add<std::vector<edm::EventRange> >("noDefault24");
iDesc1.add("noDefaultPset1", noDefaultPset1);
edm::ParameterSetDescription noDefaultPset2;
noDefaultPset2.addUntracked<int>(std::string("noDefault1"));
noDefaultPset2.addUntracked<std::vector<int> >("noDefault2");
noDefaultPset2.addUntracked<unsigned>("noDefault3");
noDefaultPset2.addUntracked<std::vector<unsigned> >("noDefault4");
noDefaultPset2.addUntracked<long long>("noDefault5");
noDefaultPset2.addUntracked<std::vector<long long> >("noDefault6");
noDefaultPset2.addUntracked<unsigned long long>("noDefault7");
noDefaultPset2.addUntracked<std::vector<unsigned long long> >("noDefault8");
noDefaultPset2.addUntracked<double>("noDefault9");
noDefaultPset2.addUntracked<std::vector<double> >("noDefault10");
noDefaultPset2.addUntracked<bool>("noDefault11");
noDefaultPset2.addUntracked<std::string>("noDefault12");
noDefaultPset2.addUntracked<std::vector<std::string> >("noDefault13");
noDefaultPset2.addUntracked<edm::EventID>("noDefault14");
noDefaultPset2.addUntracked<std::vector<edm::EventID> >("noDefault15");
noDefaultPset2.addUntracked<edm::LuminosityBlockID>("noDefault16");
noDefaultPset2.addUntracked<std::vector<edm::LuminosityBlockID> >("noDefault17");
noDefaultPset2.addUntracked<edm::InputTag>("noDefault18");
noDefaultPset2.addUntracked<std::vector<edm::InputTag> >("noDefault19");
noDefaultPset2.addUntracked<edm::FileInPath>("noDefault20");
noDefaultPset2.addUntracked<edm::LuminosityBlockRange>("noDefault21");
noDefaultPset2.addUntracked<std::vector<edm::LuminosityBlockRange> >("noDefault22");
noDefaultPset2.addUntracked<edm::EventRange>("noDefault23");
noDefaultPset2.addUntracked<std::vector<edm::EventRange> >("noDefault24");
iDesc1.add("noDefaultPset2", noDefaultPset2);
descriptions.add("testLabel1", iDesc1);
// ------------------------------------------
edm::ParameterSetDescription iDesc2;
iDesc2.add<int>("p_int", 2);
descriptions.addDefault(iDesc2);
// ------------------------------------------
edm::ParameterSetDescription iDesc3;
iDesc3.add<int>("p_int", 3);
descriptions.addWithDefaultLabel(iDesc3);
}
}
using edmtest::ProducerWithPSetDesc;
DEFINE_FWK_MODULE(ProducerWithPSetDesc);
|
ClearlyElevated/Memexplorer | events/guildMemberRemove.js | const { members } = require('../data/channels.json');
const Discord = require('discord.js');
module.exports = class {
constructor (client) {
this.client = client;
}
async run (member) {
if(member.guild.id === "533778546288754689"){
const embed = new Discord.RichEmbed()
.setAuthor(`${member.user.tag} (${member.user.id}) left the server`, member.user.displayAvatarURL)
.setFooter(`Created: ${member.user.createdAt}`)
.setColor("#e74c3c");
this.client.channels.get(members).send(embed);
}
}
};
|
jonpe960/ufsm | test/core/test_transition_conflict.c | <filename>test/core/test_transition_conflict.c
#include <stdio.h>
#include <assert.h>
#include <ufsm/ufsm.h>
#include "test_transition_conflict.gen.h"
static bool flag_eA, flag_xA, flag_xB, flag_eC;
static void reset_flags(void)
{
flag_eA = false;
flag_xA = false;
flag_xB = false;
flag_eC = false;
}
void eA(void *ctx)
{
flag_eA = true;
}
void xA(void *ctx)
{
flag_xA = true;
}
void xB(void *ctx)
{
flag_xB = true;
}
void eC(void *ctx)
{
flag_eC = true;
}
int main(void)
{
struct test_transition_conflict_machine machine;
ufsm_debug_machine(&machine.machine);
reset_flags();
test_transition_conflict_machine_initialize(&machine, NULL);
assert("Init" && flag_eA && !flag_xA && !flag_xB && !flag_eC);
test_transition_conflict_machine_process(&machine, EV1);
assert("Step1" && flag_eA && flag_xA && !flag_xB && !flag_eC);
reset_flags();
test_transition_conflict_machine_process(&machine, EV2);
assert("Step2" && flag_eA && !flag_xA && flag_xB && !flag_eC);
test_transition_conflict_machine_process(&machine, EV2);
assert("Step3" && flag_eA && flag_xA && flag_xB && flag_eC);
return 0;
}
|
atomsandbits/atomsandbits | services/webapp/both/imports/components/CalculationOptions/components/FinalDistanceInput/index.js | <reponame>atomsandbits/atomsandbits<gh_stars>1-10
import React from 'react';
import PropTypes from 'prop-types';
import {
branch,
compose,
lifecycle,
onlyUpdateForPropTypes,
renderNothing,
renderComponent,
withProps,
} from 'recompose';
import { OptionContainer, TextField } from '../../styles';
import getOptionsForParameter from '../../getOptionsForParameter';
const enhance = compose(
withProps(({ type, method, setFinalDistance }) => ({
showFinalDistances: getOptionsForParameter({
type,
method,
parameter: 'finalDistance',
}),
onInput: (event) => {
const finalDistance = Number(event.target.value);
setFinalDistance(finalDistance);
},
})),
branch(({ showFinalDistances }) => !showFinalDistances, renderNothing),
branch(
({ finalDistance }) => typeof finalDistance === 'undefined',
renderComponent(({ setFinalDistance }) => {
setFinalDistance(10);
return null;
})
),
lifecycle({
componentWillUnmount() {
const { unsetFinalDistance } = this.props;
unsetFinalDistance();
},
}),
onlyUpdateForPropTypes
);
const FinalDistanceInputPure = ({ onInput, finalDistance }) => (
<OptionContainer>
<TextField
label="Final Distance"
type="number"
onChange={onInput}
value={finalDistance}
inputProps={{
step: 1,
min: 0.0001,
}}
/>
</OptionContainer>
);
FinalDistanceInputPure.propTypes = {
setFinalDistance: PropTypes.func.isRequired,
unsetFinalDistance: PropTypes.func.isRequired,
finalDistance: PropTypes.number.isRequired,
onInput: PropTypes.func.isRequired,
};
const FinalDistanceInput = enhance(FinalDistanceInputPure);
export { FinalDistanceInput };
export default FinalDistanceInput;
|
SevenDayCandle/STS-FoolMod | src/main/java/pinacolada/cards/base/attributes/HPAttribute.java | <reponame>SevenDayCandle/STS-FoolMod
package pinacolada.cards.base.attributes;
import eatyourbeets.cards.base.EYBCard;
import extendedui.utilities.ColoredString;
import pinacolada.cards.base.PCLCard;
import pinacolada.utilities.PCLColors;
public class HPAttribute extends PCLAttribute {
public static HPAttribute Instance = new HPAttribute();
public HPAttribute() {
this.icon = ICONS.HP.Texture();
this.largeIcon = ICONS.HP_L.Texture();
}
@Override
public PCLAttribute SetCard(EYBCard card) {
mainText = card.heal > 0 ? new eatyourbeets.utilities.ColoredString(card.heal, PCLColors.Cream(1.0F)) : null;
iconTag = null;
suffix = null;
return this;
}
@Override
public PCLAttribute SetCard(PCLCard card) {
pclText = card.heal > 0 ? new ColoredString(card.heal, PCLColors.Cream(1.0F)) : null;
iconTag = null;
suffix = null;
return this;
}
public PCLAttribute SetCard(PCLCard card, boolean useMagicNumber) {
if (useMagicNumber) {
pclText = card.GetMagicNumberString();
} else {
pclText = null;
}
iconTag = null;
suffix = null;
return this;
}
}
|
Willy5s/Pirates-Online-Rewritten | pirates/uberdog/DistributedGoldReceipt.py | <gh_stars>10-100
from direct.distributed.ClockDelta import *
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.distributed.DistributedObject import DistributedObject
from pirates.uberdog.UberDogGlobals import *
class DistributedGoldReceipt(DistributedObject):
notify = directNotify.newCategory('GoldReceipt')
def setGoldPaid(self, goldPaid):
self.goldPaid = goldPaid
def setExpirationDate(self, expirationDate):
self.expirationDate = expirationDate |
wayneluzw/google-ads-ruby | examples/remarketing/add_logical_user_list.rb | <reponame>wayneluzw/google-ads-ruby
#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Creates a combination user list containing users that are present on any one
# of the provided user lists.
require 'optparse'
require 'google/ads/google_ads'
require 'date'
def add_logical_user_list(customer_id, user_list_ids)
# GoogleAdsClient will read a config file from
# ENV['HOME']/google_ads_config.rb when called without parameters
client = Google::Ads::GoogleAds::GoogleAdsClient.new
# Creates the UserListLogicalRuleInfo specifying that a user should be added
# to the new list if they are present in any of the provided lists.
user_list_logical_rule_info = client.resource.user_list_logical_rule_info do |info|
# Using ANY means that a user should be added to the combined list if they
# are present on any of the lists targeted in the logical_user_list_operand_info.
# Use ALL to add users present on all of the provided lists or NONE to add
# users that aren't present on any of the targeted lists.
info.operator = :ANY
user_list_ids.each do |list_id|
info.rule_operands << client.resource.logical_user_list_operand_info do |op|
op.user_list = client.path.user_list(customer_id, list_id)
end
end
end
# Creates the new combination user list operation.
operation = client.operation.create_resource.user_list do |ul|
ul.name = "My combination list of other user lists #{(Time.new.to_f * 1000).to_i}"
ul.logical_user_list = client.resource.logical_user_list_info do |info|
info.rules << user_list_logical_rule_info
end
end
# Issues a mutate request to add the user list and prints some information.
response = client.service.user_list.mutate_user_lists(
customer_id: customer_id,
operations: [operation],
)
puts "Created combination user list with resource name "\
"'#{response.results.first.resource_name}'"
end
if __FILE__ == $0
options = {}
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
options[:user_list_ids] = [
'INSERT_USER_LIST_ID_1_HERE',
'INSERT_USER_LIST_ID_2_HERE',
]
OptionParser.new do |opts|
opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__))
opts.separator ''
opts.separator 'Options:'
opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
options[:customer_id] = v
end
opts.on('-U', '--user-list-ids USER-LIST-IDS', String,
'User List IDs (comma separated)') do |v|
options[:user_list_ids] = v.split(',')
end
opts.separator ''
opts.separator 'Help:'
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!
begin
add_logical_user_list(
options.fetch(:customer_id).tr("-", ""),
options.fetch(:user_list_ids),
)
rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
e.failure.errors.each do |error|
STDERR.printf("Error with message: %s\n", error.message)
if error.location
error.location.field_path_elements.each do |field_path_element|
STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
end
end
error.error_code.to_h.each do |k, v|
next if v == :UNSPECIFIED
STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
end
end
raise
end
end
|
nistefan/cmssw | Geometry/EcalAlgo/interface/WriteESAlignments.h | <gh_stars>1-10
#ifndef SOMEPACKAGE_WRITEESALIGNMENTS_H
#define SOMEPACKAGE_WRITEESALIGNMENTS_H 1
namespace edm
{
class EventSetup ;
}
#include "CondFormats/Alignment/interface/Alignments.h"
class WriteESAlignments
{
public:
typedef Alignments* AliPtr ;
typedef std::vector<AlignTransform> AliVec ;
typedef AlignTransform::Translation Trl ;
typedef AlignTransform::Rotation Rot ;
typedef std::vector<double> DVec ;
static const unsigned int k_nA ;
WriteESAlignments( const edm::EventSetup& eventSetup ,
const DVec& alphaVec ,
const DVec& betaVec ,
const DVec& gammaVec ,
const DVec& xtranslVec ,
const DVec& ytranslVec ,
const DVec& ztranslVec ) ;
~WriteESAlignments() ;
private:
void convert( const edm::EventSetup& eS ,
const DVec& a ,
const DVec& b ,
const DVec& g ,
const DVec& x ,
const DVec& y ,
const DVec& z ,
AliVec& va ) ;
void write( AliPtr aliPtr ) ;
};
#endif
|
christianascone/itextpdf | itext/src/test/java/com/itextpdf/text/pdf/TextExpansionTest.java | <gh_stars>1-10
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2018 iText Group NV
Authors: iText Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://itextpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using iText.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the iText software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping iText with a closed
source product.
For more information, please contact iText Software Corp. at this
address: <EMAIL>
*/
package com.itextpdf.text.pdf;
import com.itextpdf.testutils.CompareTool;
import com.itextpdf.text.*;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class TextExpansionTest {
public static final String DEST_FOLDER = "./target/com/itextpdf/test/pdf/TextExpansionTest/";
public static final String SOURCE_FOLDER = "./src/test/resources/com/itextpdf/text/pdf/TextExpansionTest/";
@Before
public void setUp() throws Exception {
new File(DEST_FOLDER).mkdirs();
}
@Test
public void imageTaggingExpansionTest() throws IOException, DocumentException, InterruptedException {
String filename = "TextExpansionTest.pdf";
Document doc = new Document(PageSize.LETTER, 72, 72, 72, 72);
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(DEST_FOLDER+filename));
writer.setTagged();
doc.open();
Chunk c1 = new Chunk("ABC");
c1.setTextExpansion("the alphabet");
Paragraph p1 = new Paragraph();
p1.add(c1);
doc.add(p1);
PdfTemplate t = writer.getDirectContent().createTemplate(6, 6);
t.setLineWidth(1f);
t.circle(3f, 3f, 1.5f);
t.setGrayFill(0);
t.fillStroke();
Image i = Image.getInstance(t);
Chunk c2 = new Chunk(i, 100, -100);
doc.add(c2);
Chunk c3 = new Chunk("foobar");
c3.setTextExpansion("bar bar bar");
Paragraph p3 = new Paragraph();
p3.add(c3);
doc.add(p3);
doc.close();
CompareTool compareTool = new CompareTool();
String error = compareTool.compareByContent(DEST_FOLDER + filename, SOURCE_FOLDER + "cmp_" + filename, DEST_FOLDER, "diff_");
if (error != null) {
Assert.fail(error);
}
}
}
|
sufyan739/AlfaSdk_Android | AlfaSdk/src/main/java/com/example/alfasdk/Models/NetShareModel/NetShareCustody.java | <filename>AlfaSdk/src/main/java/com/example/alfasdk/Models/NetShareModel/NetShareCustody.java
package com.example.alfasdk.Models.NetShareModel;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class NetShareCustody {
@SerializedName("physicalTradable")
@Expose
private String physicalTradable;
@SerializedName("symbol")
@Expose
private String symbol;
@SerializedName("regular")
@Expose
private String regular;
@SerializedName("cdcTradable")
@Expose
private String cdcTradable;
@SerializedName("closeRate")
@Expose
private String closeRate;
@SerializedName("net")
@Expose
private String net;
@SerializedName("corporateActivity")
@Expose
private String corporateActivity;
@SerializedName("spot")
@Expose
private String spot;
@SerializedName("custodyBalance")
@Expose
private String custodyBalance;
@SerializedName("unregistered")
@Expose
private String unregistered;
@SerializedName("forward")
@Expose
private String forward;
@SerializedName("registered")
@Expose
private String registered;
@SerializedName("marketValue")
@Expose
private String marketValue;
@SerializedName("symbolName")
@Expose
private String symbolName;
/**
* No args constructor for use in serialization
*
*/
public NetShareCustody() {
}
/**
*
* @param physicalTradable
* @param symbol
* @param regular
* @param cdcTradable
* @param closeRate
* @param net
* @param corporateActivity
* @param spot
* @param custodyBalance
* @param unregistered
* @param forward
* @param registered
* @param marketValue
* @param symbolName
*/
public NetShareCustody(String physicalTradable, String symbol, String regular, String cdcTradable, String closeRate, String net, String corporateActivity, String spot, String custodyBalance, String unregistered, String forward, String registered, String marketValue, String symbolName) {
super();
this.physicalTradable = physicalTradable;
this.symbol = symbol;
this.regular = regular;
this.cdcTradable = cdcTradable;
this.closeRate = closeRate;
this.net = net;
this.corporateActivity = corporateActivity;
this.spot = spot;
this.custodyBalance = custodyBalance;
this.unregistered = unregistered;
this.forward = forward;
this.registered = registered;
this.marketValue = marketValue;
this.symbolName = symbolName;
}
public String getPhysicalTradable() {
return physicalTradable;
}
public void setPhysicalTradable(String physicalTradable) {
this.physicalTradable = physicalTradable;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getRegular() {
return regular;
}
public void setRegular(String regular) {
this.regular = regular;
}
public String getCdcTradable() {
return cdcTradable;
}
public void setCdcTradable(String cdcTradable) {
this.cdcTradable = cdcTradable;
}
public String getCloseRate() {
return closeRate;
}
public void setCloseRate(String closeRate) {
this.closeRate = closeRate;
}
public String getNet() {
return net;
}
public void setNet(String net) {
this.net = net;
}
public String getCorporateActivity() {
return corporateActivity;
}
public void setCorporateActivity(String corporateActivity) {
this.corporateActivity = corporateActivity;
}
public String getSpot() {
return spot;
}
public void setSpot(String spot) {
this.spot = spot;
}
public String getCustodyBalance() {
return custodyBalance;
}
public void setCustodyBalance(String custodyBalance) {
this.custodyBalance = custodyBalance;
}
public String getUnregistered() {
return unregistered;
}
public void setUnregistered(String unregistered) {
this.unregistered = unregistered;
}
public String getForward() {
return forward;
}
public void setForward(String forward) {
this.forward = forward;
}
public String getRegistered() {
return registered;
}
public void setRegistered(String registered) {
this.registered = registered;
}
public String getMarketValue() {
return marketValue;
}
public void setMarketValue(String marketValue) {
this.marketValue = marketValue;
}
public String getSymbolName() {
return symbolName;
}
public void setSymbolName(String symbolName) {
this.symbolName = symbolName;
}
}
|
lilei-dfjk/mall | mall-portal/src/main/java/com/macro/mall/logistcs/cons/RedisKey.java | package com.macro.mall.logistcs.cons;
public class RedisKey {
public static final String PORTAL_LOGISTICS = "PORTAL_LOGISTICS";
public static final String LOGISTICS_RULE = "'logistics.rule.'";
}
|
mozhe24/study | java/src/main/java/ali/SearchStringByThreadPool.java | <gh_stars>1-10
package ali;
import javafx.util.Pair;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.*;
import java.util.stream.Collectors;
/**
* @author yj
* @version 1.0
* @date 2019/4/28 21:02
*/
public class SearchStringByThreadPool {
public static void main(String[] args) {
try {
//创建5个固定线程的线程池
ExecutorService executorService = Executors.newFixedThreadPool(5);
List<Future<Pair<String, Integer>>> listFile =
//这里是取所传入目录的最多四层,如果不知道这个API的话需要递归去做。
Files.walk(Paths.get("D:\\CUST\\workspace\\JavaCore\\FullStackTraining\\src\\main\\java\\com\\zkn"), 4)
//文件文件夹和不是java的文件
.filter(file -> !Files.isDirectory(file) && file.toString().endsWith("java"))
//创建N多个Callable实现类
.map(file -> (Callable<Pair<String, Integer>>) () -> {
//这里的键值对用pair比用Map更好一些
Pair<String, Integer> pair = null;
try {
Optional optional = Files.lines(file).map(str -> {
int count = 0;
int index = str.indexOf("main");
if (index >= 0) {
//这里需要循环计算,因为可能在某一行中会出现多次
do {
count++;
} while ((index = str.indexOf("main", index + 1)) > 0);
}
return count;
//合并最终的计算结果
}).reduce(Integer::sum);
int count = optional.isPresent() ? (int) optional.get() : 0;
pair = new Pair<>(file.toString(), count);
} catch (IOException e) {
e.printStackTrace();
}
return pair == null ? new Pair<>("", 0) : pair;
})
//提交给线程池进行处理
.map(file -> executorService.submit(file))
.collect(Collectors.toList());
listFile.stream().map(file -> {
Pair<String, Integer> pair = null;
try {
pair = file.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return pair == null ? new Pair<>("", 0) : pair;
//过滤掉不包含字符串的文件
}).filter(file -> file.getValue() > 0)
//从大到小排序
.sorted((s1, s2) -> Integer.compare(s2.getValue(), s1.getValue()))
.forEach(file -> System.out.println(String.format("%d次出现在%s文件中", file.getValue(), file.getKey())));
//关闭线程池
executorService.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
x42/VeeSeeVSTRack | plugins/community/repos/moDllz/src/XBender.cpp | #include "dsp/digital.hpp"
#include "moDllz.hpp"
#include "dsp/filter.hpp"
/*
* XBender
*/
namespace rack_plugin_moDllz {
struct XBender : Module {
enum ParamIds {
XBEND_PARAM,
XBENDCVTRIM_PARAM,
XBENDRANGE_PARAM,
BEND_PARAM,
BENDCVTRIM_PARAM,
AXISXFADE_PARAM,
AXISSLEW_PARAM,
AXISTRNSUP_PARAM,
AXISTRNSDWN_PARAM,
AXISSHIFTTRIM_PARAM,
AXISSELECT_PARAM = 10,
AXISSELECTCV_PARAM = 18,
SNAPAXIS_PARAM,
YCENTER_PARAM,
YZOOM_PARAM,
AUTOZOOM_PARAM,
NUM_PARAMS
};
enum InputIds {
IN_INPUT,
XBENDCV_INPUT = 8,
XBENDRANGE_INPUT,
BENDCV_INPUT,
AXISSELECT_INPUT,
AXISEXT_INPUT,
AXISXFADE_INPUT,
AXISSHIFT_INPUT,
AXISSLEW_INPUT,
NUM_INPUTS
};
enum OutputIds {
OUT_OUTPUT,
AXIS_OUTPUT = 8,
NUM_OUTPUTS
};
enum LightIds {
AXIS_LIGHT,
AUTOZOOM_LIGHT = 8,
SNAPAXIS_LIGHT,
NUM_LIGHTS
};
float inaxis = 0.f;
float slewaxis = 0.f;
int axisTransParam = 0;
float finalAxis = 0.f;
float AxisShift = 0.f;
float axisxfade;
float selectedAxisF = 0.f;
int selectedAxisI = 0;
float dZoom = 1.f;
float dCenter = 0.5f;
int frameAutoZoom = 0;
float slewchanged = 0.f;
SchmittTrigger axisTransUpTrigger;
SchmittTrigger axisTransDwnTrigger;
SchmittTrigger axisSelectTrigger[8];
struct ioXBended {
float inx = 0.0f;
float xout = 0.0f;
bool iactive = false;
};
ioXBended ioxbended[8];
SlewLimiter slewlimiter;
XBender() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS) {}
void step() override;
void onReset() override {
for (int ix = 0; ix < 8 ; ix++){
outputs[OUT_OUTPUT + ix].value = inputs[IN_INPUT + ix].value;
}
}
json_t *toJson() override {
json_t *rootJ = json_object();
json_object_set_new(rootJ, "selectedAxisI", json_integer(selectedAxisI));
json_object_set_new(rootJ, "axisTransParam", json_integer(axisTransParam));
return rootJ;
}
void fromJson(json_t *rootJ) override {
json_t *selectedAxisIJ = json_object_get(rootJ,("selectedAxisI"));
selectedAxisI = json_integer_value(selectedAxisIJ);
json_t *axisTransParamJ = json_object_get(rootJ,("axisTransParam"));
axisTransParam = json_integer_value(axisTransParamJ);
}
};
///////////////////////////////////////////
///////////////STEP //////////////////
/////////////////////////////////////////////
void XBender::step() {
if(inputs[AXISSELECT_INPUT].active) {
if (params[SNAPAXIS_PARAM].value > 0.5f){
selectedAxisI = (clamp(static_cast<int>(inputs[AXISSELECT_INPUT].value * 0.7), 0, 7));
selectedAxisF = static_cast<float>(selectedAxisI);
inaxis = inputs[selectedAxisI].value;
} else {
selectedAxisF = clamp(inputs[AXISSELECT_INPUT].value * 0.7, 0.f, 7.f);
selectedAxisI = static_cast<int>(selectedAxisF);
float ax_float = selectedAxisF - static_cast<float>(selectedAxisI);
inaxis = (inputs[selectedAxisI].value * (1.f - ax_float) + (inputs[selectedAxisI + 1].value * ax_float));
}
}else{
inaxis = inputs[selectedAxisI].value;
}
lights[SNAPAXIS_LIGHT].value = (params[SNAPAXIS_PARAM].value > 0.5f)? 1.f : 0.f;
axisxfade = clamp((params[AXISXFADE_PARAM].value + inputs[AXISXFADE_INPUT].value/ 10.f), 0.f, 1.f);
if (inputs[AXISEXT_INPUT].active){
float axisext = inputs[AXISEXT_INPUT].value;
slewaxis = crossfade(axisext, inaxis, axisxfade);
}else slewaxis = inaxis;
float slewsum = clamp((params[AXISSLEW_PARAM].value + inputs[AXISSLEW_INPUT].value * .1f), 0.f , 1.f);
if (slewchanged != slewsum) {
float slewfloat = 1.0f/(5.0f + slewsum * engineGetSampleRate());
slewlimiter.setRiseFall(slewfloat,slewfloat);
}
finalAxis = slewlimiter.process(slewaxis) + (inputs[AXISSHIFT_INPUT].value * params[AXISSHIFTTRIM_PARAM].value);
AxisShift = (static_cast<float>(axisTransParam)/12.f);
finalAxis += clamp(AxisShift, -12.f,12.f);
float range = clamp((params[XBENDRANGE_PARAM].value + inputs[XBENDRANGE_INPUT].value/2.f), 1.f,5.f);
float xbend = clamp((params[XBEND_PARAM].value + (inputs[XBENDCV_INPUT].value /5.f) * (params[XBENDCVTRIM_PARAM].value /24.f)),-1.f, 1.f);
float bend = clamp((params[BEND_PARAM].value + (inputs[BENDCV_INPUT].value /5.f) * (params[BENDCVTRIM_PARAM].value /60.f)),-1.f, 1.f);
for (int i = 0; i < 8; i++){
if (inputs[IN_INPUT + i].active) {
if (axisSelectTrigger[i].process(params[AXISSELECT_PARAM + i].value)) {
selectedAxisI = i;
selectedAxisF = static_cast<float>(i); // float for display
}
ioxbended[i].iactive= true;
lights[AXIS_LIGHT + i].value = (selectedAxisI == i)? 1.f : 0.01f;
ioxbended[i].inx = inputs[IN_INPUT + i].value;
float diff = (finalAxis - ioxbended[i].inx) * xbend * range;
ioxbended[i].xout = clamp((ioxbended[i].inx + diff + bend * 6.f),-12.f,12.f);
outputs[OUT_OUTPUT + i].value = ioxbended[i].xout;
}else{
lights[AXIS_LIGHT + i].value = 0;
ioxbended[i].iactive=false;
}
} //for loop ix
outputs[AXIS_OUTPUT].value = finalAxis;
if (axisTransUpTrigger.process(params[AXISTRNSUP_PARAM].value))
if (axisTransParam < 48) axisTransParam ++;
if (axisTransDwnTrigger.process(params[AXISTRNSDWN_PARAM].value))
if (axisTransParam > -48) axisTransParam --;
bool autoZoom = (params[AUTOZOOM_PARAM].value > 0.f);
if (autoZoom){
frameAutoZoom ++;
if (frameAutoZoom > 128) {
frameAutoZoom = 0;
float autoZoomMin = 12.f , autoZoomMax = -12.f;
int active = 0;
for (int i = 0; i < 8; i++){
if (inputs[IN_INPUT + i].active) {
active ++;
if (ioxbended[i].inx < autoZoomMin)
autoZoomMin = ioxbended[i].inx;
if (ioxbended[i].xout < autoZoomMin)
autoZoomMin = ioxbended[i].xout;
if (ioxbended[i].inx > autoZoomMax)
autoZoomMax = ioxbended[i].inx;
if (ioxbended[i].xout > autoZoomMax)
autoZoomMax = ioxbended[i].xout;
}
}
if (finalAxis < autoZoomMin)
autoZoomMin = finalAxis;
if (finalAxis > autoZoomMax)
autoZoomMax = finalAxis;
float autoZ = 22.f / clamp((autoZoomMax - autoZoomMin),1.f,24.f);
float autoCenter = 10.f * (autoZoomMin + (autoZoomMax - autoZoomMin) / 2.f);
dZoom = clamp(autoZ, 1.f, 15.f);
dCenter = clamp(autoCenter, -120.f, 120.f);
}
lights[AUTOZOOM_LIGHT].value = 10.f;
}
else {
dCenter = params[XBender::YCENTER_PARAM].value;
dZoom = params[XBender::YZOOM_PARAM].value;
lights[AUTOZOOM_LIGHT].value = 0.f;
}
}//closing STEP
///Displays
struct BenderDisplay : TransparentWidget {
BenderDisplay() {
}
XBender::ioXBended *ioxB;// = new XBender::ioXBended[8];
float *pAxis = NULL;
float *pyCenter ;
float *pyZoom ;
float *pAxisIx;
float *pAxisXfade;
void draw(NVGcontext* vg)
{
const float dispHeight = 228.f;
const float dispCenter = dispHeight / 2.f;
float yZoom = *pyZoom;
float yCenter = *pyCenter * yZoom + dispCenter;
float AxisIx = *pAxisIx;
float keyw = 10.f * yZoom /12.f;
// crop drawing to display
nvgScissor(vg, 0.f, 0.f, 152.f, dispHeight);
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGB(0x2a, 0x2a, 0x2a));
nvgRect(vg, 20.f, yCenter - 120.f * yZoom, 110.f, 20.f * yZoom);
nvgRect(vg, 20.f, yCenter + 100.f * yZoom, 110.f, 20.f * yZoom);
nvgFill(vg);
nvgBeginPath(vg);
if (yZoom > 2.5f) nvgFillColor(vg, nvgRGB(0x2d, 0x2d, 0x2d));
else nvgFillColor(vg, nvgRGB(0x1a, 0x1a, 0x1a));
nvgRect(vg, 20.f, yCenter - 50.f * yZoom, 110.f, 100.f * yZoom );
nvgFill(vg);
for (int i = 0; i < 11; i++){
if (yZoom < 2.5f){
// 1V lines
nvgBeginPath(vg);
nvgStrokeColor(vg, nvgRGB(0x2d,0x2d,0x2d));
nvgMoveTo(vg, 20.f, yCenter - 10.f * yZoom * i);
nvgLineTo(vg, 130.f,yCenter - 10.f * yZoom * i);
nvgMoveTo(vg, 20.f, yCenter + 10.f * yZoom * i);
nvgLineTo(vg, 130.f,yCenter + 10.f * yZoom * i);
nvgStroke(vg);
}else if (i < 5){
// keyboard
float keyPos = yCenter + 10.f * yZoom * i;
// C's highlight
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGB(0x44, 0x44, 0x44));
nvgRect(vg, 20.f, yCenter - 10.f * yZoom * i - keyw * 0.5f, 110.f, keyw);
nvgFill(vg);
/// > center
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGB(0x0, 0x0, 0x0));
nvgRect(vg, 20.f, keyPos + keyw * 1.5f, 110.f, keyw);
nvgFill(vg);
nvgBeginPath(vg);
nvgRect(vg, 20.f, keyPos + keyw * 3.5f , 110.f, keyw);
nvgFill(vg);
nvgBeginPath(vg);
nvgRect(vg, 20.f, keyPos + keyw * 5.5f, 110.f, keyw);
nvgFill(vg);
nvgBeginPath(vg);
nvgRect(vg, 20.f, keyPos + keyw * 8.5f, 110.f, keyw);
nvgFill(vg);
nvgBeginPath(vg);
nvgRect(vg, 20.f, keyPos + keyw * 10.5f, 110.f, keyw);
nvgFill(vg);
/// C's highlight
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGB(0x44, 0x44, 0x44));
nvgRect(vg, 20.f, yCenter + 10.f * yZoom * i - keyw * 0.5f, 110.f, keyw);
nvgFill(vg);
/// < center
keyPos = yCenter - 10.f * yZoom * i;
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGB(0x0, 0x0, 0x0));
nvgRect(vg, 20.f, keyPos - keyw * 1.5f, 110.f, keyw);
nvgFill(vg);
nvgBeginPath(vg);
nvgRect(vg, 20.f, keyPos - keyw * 3.5f , 110.f, keyw);
nvgFill(vg);
nvgBeginPath(vg);
nvgRect(vg, 20.f, keyPos - keyw * 6.5f, 110.f, keyw);
nvgFill(vg);
nvgBeginPath(vg);
nvgRect(vg, 20.f, keyPos - keyw * 8.5f, 110.f, keyw);
nvgFill(vg);
nvgBeginPath(vg);
nvgRect(vg, 20.f, keyPos - keyw * 10.5f, 110.f, keyw);
nvgFill(vg);
}
}
// center 0v...
nvgBeginPath(vg);
if (yZoom < 2.5f){
nvgStrokeColor(vg,nvgRGBA(0x80, 0x00, 0x00 ,0x77));
nvgStrokeWidth(vg,1.f);
nvgMoveTo(vg, 20.f, yCenter);
nvgLineTo(vg, 130.f, yCenter);
nvgStroke(vg);
}//... center C
else {
nvgFillColor(vg, nvgRGBA(0x80, 0x00, 0x00 ,0x77));
nvgRect(vg, 20.f, yCenter - keyw * 0.5f, 110.f, keyw);
nvgFill(vg);
}
float Axis = *pAxis;
///// Bend Lines
const float yfirst = 10.5f;
const float ystep = 26.f;
for (int i = 0; i < 8 ; i++){
//nowactive =;
if (ioxB[i].iactive){
float yport = yfirst + i * ystep;
float yi = yZoom * ioxB[i].inx * -10.f + yCenter ;
float yo = yZoom * ioxB[i].xout * -10.f + yCenter ;
nvgBeginPath(vg);
nvgStrokeWidth(vg,1.f);
nvgStrokeColor(vg,nvgRGBA(0xff, 0xff, 0xff,0x80));
nvgMoveTo(vg, 0.f, yport);
nvgLineTo(vg, 20.f, yi);
nvgLineTo(vg, 130.f, yo);
nvgLineTo(vg, 150.f, yport);
nvgStroke(vg);
if (yZoom > 2.5f){
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(0xff, 0xff, 0xff,0x60));
nvgRoundedRect(vg, 20.f, yi - keyw * 0.5f, 10.f, keyw, 2.f);
nvgFill(vg);
nvgBeginPath(vg);
nvgRoundedRect(vg, 120.f, yo - keyw * 0.5f, 10.f, keyw, 2.f);
nvgFill(vg);
}
}
}
/// Axis Line
NVGcolor extColor = nvgRGBA(0xee, 0xee, 0x00, (1.f - *pAxisXfade) * 0xff);
NVGcolor intColor = nvgRGBA(0xee, 0x00, 0x00, *pAxisXfade * 0xff);
NVGcolor axisColor = nvgRGB(0xee, (1.f - *pAxisXfade) * 0xee, 0x00);
Axis = yZoom * Axis * -10.f + yCenter;
nvgStrokeWidth(vg,1.f);
//ext
nvgBeginPath(vg);
nvgStrokeColor(vg,extColor);
nvgMoveTo(vg, 0.f, 228.f);
nvgLineTo(vg, 20.f, Axis);
nvgStroke(vg);
// int
nvgBeginPath(vg);
nvgStrokeColor(vg,intColor);
nvgMoveTo(vg, 0.f, yfirst + AxisIx * ystep);
nvgLineTo(vg, 20.f, Axis);
nvgStroke(vg);
// axis
nvgBeginPath(vg);
nvgStrokeColor(vg,axisColor);
nvgMoveTo(vg, 20.f, Axis);
nvgLineTo(vg, 130.f, Axis);
nvgLineTo(vg, 150.f, 222.f);
nvgStroke(vg);
}
};
struct AxisDisplay : TransparentWidget {
AxisDisplay() {
font = Font::load(FONT_FILE);
}
float mdfontSize = 11.f;
std::string s;
std::shared_ptr<Font> font;
int *pAxisTransP = 0;
int frame = 0 ;
void draw(NVGcontext* vg)
{
if (frame ++ > 8 )
{
s = std::to_string(*pAxisTransP);
frame = 0;
}
NVGcolor backgroundColor = nvgRGB(0x22, 0x22, 0x22);
nvgBeginPath(vg);
nvgRoundedRect(vg, 0, 0, box.size.x, box.size.y, 3.0f);
nvgFillColor(vg, backgroundColor);
nvgFill(vg);
nvgFillColor(vg, nvgRGB(0xff,0xff,0xff));
nvgFontSize(vg, mdfontSize);
nvgFontFaceId(vg, font->handle);
nvgTextAlign(vg, NVG_ALIGN_CENTER);
nvgTextLetterSpacing(vg, 0.0f);
nvgTextBox(vg, 0.f, 14.0f,box.size.x, s.c_str(), NULL);
}
};
struct RangeSelector: moDllzSmSelector{
RangeSelector(){
minAngle = -0.4*M_PI;
maxAngle = 0.4*M_PI;
}
};
struct xbendKnob : SVGKnob {
xbendKnob() {
minAngle = -0.83*M_PI;
maxAngle = 0.83*M_PI;
setSVG(SVG::load(assetPlugin(plugin, "res/xbendKnob.svg")));
shadow->opacity = 0.f;
}
};
struct zTTrim : SVGKnob {
zTTrim() {
minAngle = 0;
maxAngle = 1.75*M_PI;
setSVG(SVG::load(assetPlugin(plugin, "res/zTTrim.svg")));
shadow->opacity = 0.f;
}
};
struct cTTrim : SVGKnob {
cTTrim() {
minAngle = -0.83*M_PI;
maxAngle = 0.83*M_PI;
snap = true;
setSVG(SVG::load(assetPlugin(plugin, "res/cTTrim.svg")));
shadow->opacity = 0.f;
}
};
struct autoZoom : SVGSwitch, ToggleSwitch {
autoZoom() {
addFrame(SVG::load(assetPlugin(plugin, "res/autoButton.svg")));
addFrame(SVG::load(assetPlugin(plugin, "res/autoButton.svg")));
}
};
struct snapAxisButton : SVGSwitch, ToggleSwitch {
snapAxisButton() {
addFrame(SVG::load(assetPlugin(plugin, "res/snapButton.svg")));
addFrame(SVG::load(assetPlugin(plugin, "res/snapButton.svg")));
}
};
struct XBenderWidget : ModuleWidget {
XBenderWidget(XBender *module): ModuleWidget(module){
setPanel(SVG::load(assetPlugin(plugin, "res/XBender.svg")));
float xPos;
float yPos;
float xyStep = 26.f ;
//Screws
addChild(Widget::create<ScrewBlack>(Vec(0, 0)));
addChild(Widget::create<ScrewBlack>(Vec(box.size.x - 15, 0)));
addChild(Widget::create<ScrewBlack>(Vec(0, 365)));
addChild(Widget::create<ScrewBlack>(Vec(box.size.x - 15, 365)));
xPos = 73.f;
yPos = 22.f;
{
BenderDisplay *benderDisplay = new BenderDisplay();
benderDisplay->box.pos = Vec(xPos, yPos);
benderDisplay->box.size = {152.f, 228.f};
benderDisplay->ioxB = &(module->ioxbended[0]);
benderDisplay->pAxis = &(module->finalAxis);
benderDisplay->pAxisIx = &(module->selectedAxisF);
benderDisplay->pyCenter = &(module->dCenter);
benderDisplay->pyZoom = &(module->dZoom);
benderDisplay->pAxisXfade = &(module->axisxfade);
addChild(benderDisplay);
}
xPos = 170.f;
yPos = 252.f;
/// View Center Zoom
addParam(ParamWidget::create<cTTrim>(Vec(xPos,yPos), module, XBender::YCENTER_PARAM, -120.f, 120.f, 0.f));
xPos = 203;
addParam(ParamWidget::create<zTTrim>(Vec(xPos,yPos), module, XBender::YZOOM_PARAM, 1.f, 15.f, 1.f));
yPos += 1.5f;
xPos = 125.f;
addParam(ParamWidget::create<autoZoom>(Vec(xPos, yPos ), module, XBender::AUTOZOOM_PARAM, 0.0f, 1.0f, 1.0f));
addChild(ModuleLightWidget::create<TinyLight<RedLight>>(Vec(xPos + 17.f, yPos + 4.f), module, XBender::AUTOZOOM_LIGHT));
/// IN - Axis select - OUTS
xPos = 12.f;
yPos = 22.f;
for (int i = 0; i < 8; i++){
// IN leds OUT
addInput(Port::create<moDllzPort>(Vec(xPos, yPos), Port::INPUT, module, XBender::IN_INPUT + i));
addParam(ParamWidget::create<moDllzRoundButton>(Vec(xPos + 37.f, yPos + 5.f), module, XBender::AXISSELECT_PARAM + i, 0.0f, 1.0f, 0.0f));
addChild(ModuleLightWidget::create<TinyLight<RedLight>>(Vec(xPos + 42.5f, yPos + 10.5f), module, XBender::AXIS_LIGHT + i));
addOutput(Port::create<moDllzPort>(Vec(234.8f, yPos), Port::OUTPUT, module, XBender::OUT_OUTPUT + i));
yPos += xyStep;
}
yPos = 248.f;
//// AXIS out >>>> on the Right
addOutput(Port::create<moDllzPort>(Vec(234.8f, yPos), Port::OUTPUT, module, XBender::AXIS_OUTPUT));
yPos = 249.f;
/// AXIS select in
addInput(Port::create<moDllzPort>(Vec(xPos, yPos), Port::INPUT, module, XBender::AXISSELECT_INPUT));
addParam(ParamWidget::create<snapAxisButton>(Vec(xPos + 22.5f, yPos + 2.f ), module, XBender::SNAPAXIS_PARAM, 0.0f, 1.0f, 0.0f));
addChild(ModuleLightWidget::create<TinyLight<RedLight>>(Vec(xPos + 40.f, yPos + 4.f), module, XBender::SNAPAXIS_LIGHT));
/// AXIS EXT - XFADE
yPos += 25.f;
addInput(Port::create<moDllzPort>(Vec(xPos, yPos), Port::INPUT, module, XBender::AXISXFADE_INPUT));
addParam(ParamWidget::create<moDllzKnob26>(Vec(36.f,280.f), module, XBender::AXISXFADE_PARAM, 0.f, 1.f, 1.f));
yPos += 25.f;
addInput(Port::create<moDllzPort>(Vec(xPos, yPos), Port::INPUT, module, XBender::AXISEXT_INPUT));
/// AXIS Slew
yPos += 25.f;
addInput(Port::create<moDllzPort>(Vec(xPos, yPos), Port::INPUT, module, XBender::AXISSLEW_INPUT));
addParam(ParamWidget::create<moDllzKnob26>(Vec(34.f, 324.f), module, XBender::AXISSLEW_PARAM, 0.f, 1.f, 0.f));
//AXIS Mod Shift
addInput(Port::create<moDllzPort>(Vec(xPos + 53.f,yPos), Port::INPUT, module, XBender::AXISSHIFT_INPUT));
addParam(ParamWidget::create<moDllzKnob26>(Vec(87.f, 324.f), module, XBender::AXISSHIFTTRIM_PARAM, 0.0f, 1.0f, 0.f));
//AXIS Transp
xPos = 73.5f;
yPos = 278.5f;
addParam(ParamWidget::create<moDllzPulseUp>(Vec(xPos + 31.f,yPos - 1.f), module, XBender::AXISTRNSUP_PARAM, 0.0f, 1.0f, 0.0f));
addParam(ParamWidget::create<moDllzPulseDwn>(Vec(xPos + 31.f ,yPos + 10.f), module, XBender::AXISTRNSDWN_PARAM, 0.0f, 1.0f, 0.0f));
{
AxisDisplay *axisDisplay = new AxisDisplay();
axisDisplay->box.pos = Vec(xPos, yPos);
axisDisplay->box.size = {30.f, 20};
axisDisplay->pAxisTransP = &(module->axisTransParam);
addChild(axisDisplay);
}
/// Knobs
//XBEND
xPos = 124.f;
yPos = 272.f;
addParam(ParamWidget::create<xbendKnob>(Vec(xPos, yPos), module, XBender::XBEND_PARAM, -1.f, 1.f, 0.f));
xPos = 127.5f;
yPos = 328.f;
addInput(Port::create<moDllzPort>(Vec(xPos,yPos), Port::INPUT, module, XBender::XBENDCV_INPUT));
addParam(ParamWidget::create<TTrimSnap>(Vec(xPos + 26.5f,yPos + 7.f), module, XBender::XBENDCVTRIM_PARAM, 0.f, 24.f, 24.f));
//XBEND RANGE
xPos = 181.f;
yPos = 288.f;
addParam(ParamWidget::create<RangeSelector>(Vec(xPos, yPos), module, XBender::XBENDRANGE_PARAM, 1.f, 5.f, 1.f));
xPos = 187.5f;
yPos = 328.f;
addInput(Port::create<moDllzPort>(Vec(xPos,yPos), Port::INPUT, module, XBender::XBENDRANGE_INPUT));
//BEND
xPos = 219.f;
yPos = 288.f;
addParam(ParamWidget::create<moDllzKnobM>(Vec(xPos, yPos), module, XBender::BEND_PARAM, -1.f, 1.f, 0.f));
xPos = 218.5f;
yPos = 328.f;
addInput(Port::create<moDllzPort>(Vec(xPos,yPos), Port::INPUT, module, XBender::BENDCV_INPUT));
addParam(ParamWidget::create<TTrimSnap>(Vec(xPos + 26.5f,yPos + 7.f), module, XBender::BENDCVTRIM_PARAM, 0.f, 60.f, 12.f));
}
};
// Specify the Module and ModuleWidget subclass, human-readable
// manufacturer name for categorization, module slug (should never
// change), human-readable module name, and any number of tags
// (found in `include/tags.hpp`) separated by commas.
} // namespace rack_plugin_moDllz
using namespace rack_plugin_moDllz;
RACK_PLUGIN_MODEL_INIT(moDllz, XBender) {
Model *modelXBender = Model::create<XBender, XBenderWidget>("moDllz", "XBender", "Poly X Bender",MULTIPLE_TAG ,EFFECT_TAG);
return modelXBender;
}
|
robertdavidgraham/squirrel-wifi | src/module/pcaplive.c | /* Copyright (c) 2007 by Errata Security, All Rights Reserved
* Programer(s): <NAME> [rdg]
*/
/*
PCAPLIVE
This code links the 'libpcap' module at RUNTIME rather than LOADTIME.
This allows us to:
(a) run this program on capture files without needing libpcap installed.
(b) give more user friendly diagnostic to the users who don't realize
that they need to install libpcap separately.
On Windows, this uses the LoadLibrary/GetProcAddress functions to
load the library.
On Linux, this uses the dlopen/dlsym functions to do essentially
the same thing.
*/
#include "platform.h"
#if _MSC_VER==1200
#pragma warning(disable:4115 4201)
#include <winerror.h>
#endif
#include "pcaplive.h"
#ifdef WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#endif
#include <stdio.h>
#include <string.h>
#include <errno.h>
static void seterr(char *errbuf, const char *msg)
{
size_t length = strlen(msg);
if (length > PCAP_ERRBUF_SIZE-1)
length = PCAP_ERRBUF_SIZE-1;
memcpy(errbuf, msg, length);
errbuf[length] = '\0';
}
static void null_PCAP_CLOSE(void *hPcap)
{
#ifdef STATICPCAP
pcap_close(hPcap);
return;
#endif
UNUSEDPARM(hPcap);
}
static unsigned null_PCAP_DATALINK(void *hPcap)
{
#ifdef STATICPCAP
return pcap_datalink(hPcap);
#endif
UNUSEDPARM(hPcap);
return 0;
}
static unsigned null_PCAP_DISPATCH(void *hPcap, unsigned how_many_packets, PCAP_HANDLE_PACKET handler, void *handle_data)
{
#ifdef STATICPCAP
return pcap_dispatch(hPcap, how_many_packets, handler, handle_data);
#endif
UNUSEDPARM(hPcap);UNUSEDPARM(how_many_packets);UNUSEDPARM(handler);UNUSEDPARM(handle_data);
return 0;
}
static int null_PCAP_FINDALLDEVS(pcap_if_t **alldevs, char *errbuf)
{
#ifdef STATICPCAP
return pcap_findalldevs(alldevs, errbuf);
#endif
*alldevs = 0;
seterr(errbuf, "libpcap not loaded");
return -1;
}
static void null_PCAP_FREEALLDEVS(pcap_if_t *alldevs)
{
#ifdef STATICPCAP
return pcap_freealldevs(alldevs);
#endif
UNUSEDPARM(alldevs);
return;
}
static char *null_PCAP_LOOKUPDEV(char *errbuf)
{
#ifdef STATICPCAP
return pcap_lookupdev(errbuf);
#endif
seterr(errbuf, "libpcap not loaded");
return "";
}
static int null_PCAP_MAJOR_VERSION(void *p)
{
#ifdef STATICPCAP
return pcap_major_version(p);
#endif
UNUSEDPARM(p);
return 0;
}
static int null_PCAP_MINOR_VERSION(void *p)
{
#ifdef STATICPCAP
return pcap_minor_version(p);
#endif
UNUSEDPARM(p);
return 0;
}
static const char *null_PCAP_LIB_VERSION(void)
{
#ifdef STATICPCAP
return pcap_lib_version();
#endif
return "stub/0.0";
}
static int null_PCAP_SET_DATALINK(void *hPcap, int datalink)
{
return -1;
}
static pcap_t *null_PCAP_CREATE(const char *source, char *errbuf) {fprintf(stderr, "pcap_create() error\n"); return 0;}
static int (*null_PCAP_SET_SNAPLEN)(pcap_t *p, int snaplen);
static int (*null_PCAP_SET_PROMISC)(pcap_t *p, int promisc);
static int (*null_PCAP_SET_TIMEOUT)(pcap_t *p, int to_ms);
static int (*null_PCAP_SET_IMMEDIATE_MODE)(pcap_t *p, int immediate_mode);
static int (*null_PCAP_SET_BUFFER_SIZE)(pcap_t *p, int buffer_size);
static int (*null_PCAP_SET_RFMON)(pcap_t *p, int rfmon);
static int (*null_PCAP_CAN_SET_RFMON)(pcap_t *p);
static int (*null_PCAP_ACTIVATE)(pcap_t *p);
#ifdef WIN32
static void *null_PCAP_GET_AIRPCAP_HANDLE(void *p)
{
UNUSEDPARM(p);
return NULL;
}
#endif
#ifdef WIN32
static unsigned null_AIRPCAP_SET_DEVICE_CHANNEL(void *p, unsigned channel)
{
UNUSEDPARM(p);UNUSEDPARM(channel);
return 0; /*0=failure, 1=success*/
}
#endif
static unsigned null_CAN_TRANSMIT(const char *devicename)
{
#if WIN32
struct DeviceCapabilities {
unsigned AdapterId; /* An Id that identifies the adapter model.*/
char AdapterModelName; /* String containing a printable adapter model.*/
unsigned AdapterBus; /* The type of bus the adapter is plugged to. */
unsigned CanTransmit; /* TRUE if the adapter is able to perform frame injection.*/
unsigned CanSetTransmitPower; /* TRUE if the adapter's transmit power is can be specified by the user application.*/
unsigned ExternalAntennaPlug; /* TRUE if the adapter supports plugging one or more external antennas.*/
unsigned SupportedMedia;
unsigned SupportedBands;
} caps;
void * (*myopen)(const char *devicename, char *errbuf);
void (*myclose)(void *h);
unsigned (*mycapabilities)(void *h, struct DeviceCapabilities *caps);
unsigned result = 0;
void *hAirpcap;
hAirpcap = LoadLibraryA("airpcap.dll");
if (hAirpcap == NULL)
return 0;
myopen = (void * (*)(const char *, char*))GetProcAddress(hAirpcap, "AirpcapOpen");
myclose = (void (*)(void*))GetProcAddress(hAirpcap, "AirpcapClose");
mycapabilities = (unsigned (*)(void*, struct DeviceCapabilities *))GetProcAddress(hAirpcap, "AirpcapGetDeviceCapabilities");
if (myopen && mycapabilities && myclose ) {
void *h = myopen(devicename, NULL);
if (h) {
if (mycapabilities(h, &caps)) {
result = caps.CanTransmit;
}
myclose(h);
}
}
FreeLibrary(hAirpcap);
return result;
#elif __GNUC__
return 0;
#endif
}
/**
* Runtime-load the libpcap shared-object or the winpcap DLL. We
* load at runtime rather than loadtime to allow this program to
* be used to process offline content, and to provide more helpful
* messages to people who don't realize they need to install PCAP.
*/
void pcaplive_init(struct PCAPLIVE *pl)
{
#ifdef WIN32
HMODULE hPacket;
HMODULE hLibpcap;
HMODULE hAirpcap;
pl->is_available = 0;
pl->is_printing_debug = 1;
/* Look for the Packet.dll */
hPacket = LoadLibraryA("Packet.dll");
if (hPacket == NULL) {
if (pl->is_printing_debug)
switch (GetLastError()) {
case ERROR_MOD_NOT_FOUND:
fprintf(stderr, "%s: not found\n", "Packet.dll", GetLastError());
return;
default:
fprintf(stderr, "%s: couldn't load %d\n", "Packet.dll", GetLastError());
return;
}
}
/* Look for the Packet.dll */
hLibpcap = LoadLibraryA("wpcap.dll");
if (hLibpcap == NULL) {
if (pl->is_printing_debug)
fprintf(stderr, "%s: couldn't load %d\n", "wpcap.dll", GetLastError());
return;
}
/* Look for the Packet.dll */
hAirpcap = LoadLibraryA("airpcap.dll");
if (hLibpcap == NULL) {
if (pl->is_printing_debug)
fprintf(stderr, "%s: couldn't load %d\n", "airpcap.dll", GetLastError());
return;
}
#define DOLINK(PCAP_DATALINK, datalink) \
pl->datalink = (PCAP_DATALINK)GetProcAddress(hLibpcap, "pcap_"#datalink); \
if (pl->datalink == NULL) pl->func_err=1, pl->datalink = null_##PCAP_DATALINK;
#endif
#ifndef WIN32
#ifndef STATICPCAP
void *hLibpcap;
unsigned initial_failure=0;
pl->is_available = 0;
pl->is_printing_debug = 1;
#ifdef __APPLE__
hLibpcap = dlopen("libpcap.dylib", RTLD_LAZY);
#else
hLibpcap = dlopen("libpcap.so", RTLD_LAZY);
#endif
if (hLibpcap == NULL) {
fprintf(stderr, "%s: %s\n", "libpcap.so", dlerror());
fprintf(stderr, "Searching elsewhere for libpcap\n");
initial_failure = 1;
}
if (hLibpcap==NULL)
hLibpcap = dlopen("libpcap.so.0.9.5", RTLD_LAZY);
if (hLibpcap==NULL)
hLibpcap = dlopen("libpcap.so.0.9.4", RTLD_LAZY);
if (hLibpcap==NULL)
hLibpcap = dlopen("libpcap.so.0.8", RTLD_LAZY);
if (hLibpcap == NULL) {
if (pl->is_printing_debug) {
fprintf(stderr, "%s: couldn't load %d (%s)\n", "libpcap.so", errno, strerror(errno));
}
} else if (initial_failure) {
fprintf(stderr, "Found libpcap\n");
}
#define DOLINK(PCAP_DATALINK, datalink) \
pl->datalink = (PCAP_DATALINK)dlsym(hLibpcap, "pcap_"#datalink); \
if (pl->datalink == NULL) { pl->func_err=1, pl->datalink = null_##PCAP_DATALINK; fprintf(stderr, "error loading pcap_"#datalink);}
#else
#define DOLINK(PCAP_DATALINK, datalink) \
pl->func_err=0, pl->datalink = pcap_##datalink;
#endif
#endif
#ifdef WIN32
DOLINK(PCAP_GET_AIRPCAP_HANDLE, get_airpcap_handle);
if (pl->func_err) {
pl->func_err = 0;
}
if (hAirpcap) {
pl->airpcap_set_device_channel = (AIRPCAP_SET_DEVICE_CHANNEL)GetProcAddress(hAirpcap, "AirpcapSetDeviceChannel");
if (pl->airpcap_set_device_channel == NULL)
pl->airpcap_set_device_channel = null_AIRPCAP_SET_DEVICE_CHANNEL;
}
#endif
DOLINK(PCAP_CLOSE , close);
DOLINK(PCAP_DATALINK , datalink);
DOLINK(PCAP_DISPATCH , dispatch);
DOLINK(PCAP_FINDALLDEVS , findalldevs);
DOLINK(PCAP_FREEALLDEVS , freealldevs);
DOLINK(PCAP_LIB_VERSION , lib_version);
DOLINK(PCAP_LOOKUPDEV , lookupdev);
DOLINK(PCAP_MAJOR_VERSION , major_version);
DOLINK(PCAP_MINOR_VERSION , minor_version);
//DOLINK(PCAP_OPEN_LIVE , open_live);
#ifdef WIN32
DOLINK(PCAP_GET_AIRPCAP_HANDLE, get_airpcap_handle);
#endif
//DOLINK(PCAP_CAN_SET_RFMON , can_set_rfmon);
//DOLINK(PCAP_SET_RFMON , set_rfmon);
DOLINK(PCAP_SET_DATALINK , set_datalink);
DOLINK(PCAP_CREATE , create);
DOLINK(PCAP_SET_SNAPLEN , set_snaplen);
DOLINK(PCAP_SET_PROMISC , set_promisc);
DOLINK(PCAP_SET_TIMEOUT , set_timeout);
DOLINK(PCAP_SET_IMMEDIATE_MODE , set_immediate_mode);
DOLINK(PCAP_SET_BUFFER_SIZE , set_buffer_size);
DOLINK(PCAP_SET_RFMON , set_rfmon);
DOLINK(PCAP_CAN_SET_RFMON , can_set_rfmon);
DOLINK(PCAP_ACTIVATE , activate);
//DOLINK(PCAP_OPEN_LIVE , open_live);
pl->can_transmit = null_CAN_TRANSMIT;
if (!pl->func_err)
pl->is_available = 1;
else
pl->is_available = 0;
}
|
DEIPworld/deip-chain | libraries/chain/include/deip/chain/services/dbs_contract_agreement.hpp | #pragma once
#include "dbs_base_impl.hpp"
#include <deip/chain/schema/contract_agreement_object.hpp>
namespace deip {
namespace chain {
class dbs_contract_agreement : public dbs_base
{
friend class dbservice_dbs_factory;
dbs_contract_agreement() = delete;
protected:
explicit dbs_contract_agreement(database& db);
public:
using refs_type = std::vector<std::reference_wrapper<const contract_agreement_object>>;
using optional_ref_type = fc::optional<std::reference_wrapper<const contract_agreement_object>>;
const contract_agreement_object& create(const external_id_type& external_id,
const account_name_type& creator,
const flat_set<account_name_type>& parties,
const std::string& hash,
const fc::time_point_sec& start_time,
const fc::optional<fc::time_point_sec>& end_time);
const bool exists(const external_id_type& external_id) const;
const optional_ref_type get_if_exists(const external_id_type& id) const;
const refs_type get_by_creator(const account_name_type& creator) const;
const contract_agreement_object& accept_by(const contract_agreement_object& contract,
const account_name_type& party);
const contract_agreement_object& reject_by(const contract_agreement_object& contract,
const account_name_type& party);
};
} // namespace chain
} // namespace deip
|
YangHao666666/hawq | tools/bin/pythonSrc/pychecker-0.8.18/pychecker/checker.py | #!/usr/bin/env python
# Copyright (c) 2001-2004, MetaSlash Inc. All rights reserved.
# Portions Copyright (c) 2005, Google, Inc. All rights reserved.
"""
Check python source code files for possible errors and print warnings
Contact Info:
http://pychecker.sourceforge.net/
<EMAIL>
"""
import string
import types
import sys
import imp
import os
import glob
import traceback
import re
# see __init__.py for meaning, this must match the version there
LOCAL_MAIN_VERSION = 3
def setupNamespace(path) :
# remove pychecker if it's the first component, it needs to be last
if sys.path[0][-9:] == 'pychecker' :
del sys.path[0]
# make sure pychecker is last in path, so we can import
checker_path = os.path.dirname(os.path.dirname(path))
if checker_path not in sys.path :
sys.path.append(checker_path)
def setupSysPathForDevelopment():
import pychecker
this_module = sys.modules[__name__]
this_path = os.path.normpath(os.path.dirname(this_module.__file__))
pkg_path = os.path.normpath(os.path.dirname(pychecker.__file__))
if pkg_path != this_path:
# pychecker was probably found in site-packages, insert this
# directory before the other one so we can do development and run
# our local version and not the version from site-packages.
pkg_dir = os.path.dirname(pkg_path)
i = 0
for p in sys.path:
if os.path.normpath(p) == pkg_dir:
sys.path.insert(i-1, os.path.dirname(this_path))
break
i = i + 1
del sys.modules['pychecker']
if __name__ == '__main__' :
setupNamespace(sys.argv[0])
setupSysPathForDevelopment()
from pychecker import utils
from pychecker import printer
from pychecker import warn
from pychecker import OP
from pychecker import Config
from pychecker import function
from pychecker import msgs
from pychecker import pcmodules
from pychecker.Warning import Warning
_cfg = None
# Constants
_DEFAULT_MODULE_TOKENS = ('__builtins__', '__doc__', '__file__', '__name__',
'__path__')
_DEFAULT_CLASS_TOKENS = ('__doc__', '__name__', '__module__')
# When using introspection on objects from some C extension modules,
# the interpreter will crash. Since pychecker exercises these bugs we
# need to blacklist the objects and ignore them. For more info on how
# to determine what object is causing the crash, search for this
# comment below (ie, it is also several hundred lines down):
#
# README if interpreter is crashing:
# FIXME: the values should indicate the versions of these modules
# that are broken. We shouldn't ignore good modules.
_EVIL_C_OBJECTS = {
'matplotlib.axes.BinOpType': None, # broken on versions <= 0.83.2
# broken on versions at least 2.5.5 up to 2.6
'wx.TheClipboard': None,
'wx._core.TheClipboard': None,
'wx._misc.TheClipboard': None,
}
_VERSION_MISMATCH_ERROR = '''
There seem to be two versions of PyChecker being used.
One is probably in python/site-packages, the other in a local directory.
If you want to run the local version, you must remove the version
from site-packages. Or you can install the current version
by doing python setup.py install.
'''
def cfg() :
return utils.cfg()
def _flattenList(list) :
"Returns a list which contains no lists"
new_list = []
for element in list :
if type(element) == types.ListType :
new_list.extend(_flattenList(element))
else :
new_list.append(element)
return new_list
def getModules(arg_list) :
"""
arg_list is a list of arguments to pychecker; arguments can represent
a module name, a filename, or a wildcard file specification.
Returns a list of (module name, dirPath) that can be imported, where
dirPath is the on-disk path to the module name for that argument.
dirPath can be None (in case the given argument is an actual module).
"""
new_arguments = []
for arg in arg_list :
# is this a wildcard filespec? (necessary for windows)
if '*' in arg or '?' in arg or '[' in arg :
arg = glob.glob(arg)
new_arguments.append(arg)
PY_SUFFIXES = ['.py']
PY_SUFFIX_LENS = [3]
if _cfg.quixote:
PY_SUFFIXES.append('.ptl')
PY_SUFFIX_LENS.append(4)
modules = []
for arg in _flattenList(new_arguments) :
# if arg is an actual module, return None for the directory
arg_dir = None
# is it a .py file?
for suf, suflen in zip(PY_SUFFIXES, PY_SUFFIX_LENS):
if len(arg) > suflen and arg[-suflen:] == suf:
arg_dir = os.path.dirname(arg)
if arg_dir and not os.path.exists(arg) :
print 'File or pathname element does not exist: "%s"' % arg
continue
module_name = os.path.basename(arg)[:-suflen]
arg = module_name
modules.append((arg, arg_dir))
return modules
def _q_file(f):
# crude hack!!!
# imp.load_module requires a real file object, so we can't just
# fiddle def lines and yield them
import tempfile
fd, newfname = tempfile.mkstemp(suffix=".py", text=True)
newf = os.fdopen(fd, 'r+')
os.unlink(newfname)
for line in f:
mat = re.match(r'(\s*def\s+\w+\s*)\[(html|plain)\](.*)', line)
if mat is None:
newf.write(line)
else:
newf.write(mat.group(1)+mat.group(3)+'\n')
newf.seek(0)
return newf
def _q_find_module(p, path):
if not _cfg.quixote:
return imp.find_module(p, path)
else:
for direc in path:
try:
return imp.find_module(p, [direc])
except ImportError:
f = os.path.join(direc, p+".ptl")
if os.path.exists(f):
return _q_file(file(f)), f, ('.ptl', 'U', 1)
def _findModule(name, moduleDir=None) :
"""Returns the result of an imp.find_module(), ie, (file, filename, smt)
name can be a module or a package name. It is *not* a filename."""
path = sys.path[:]
if moduleDir:
path.insert(0, moduleDir)
packages = string.split(name, '.')
for p in packages :
# smt = (suffix, mode, type)
file, filename, smt = _q_find_module(p, path)
if smt[-1] == imp.PKG_DIRECTORY :
try :
# package found - read path info from init file
m = imp.load_module(p, file, filename, smt)
finally :
if file is not None :
file.close()
# importing xml plays a trick, which replaces itself with _xmlplus
# both have subdirs w/same name, but different modules in them
# we need to choose the real (replaced) version
if m.__name__ != p :
try :
file, filename, smt = _q_find_module(m.__name__, path)
m = imp.load_module(p, file, filename, smt)
finally :
if file is not None :
file.close()
new_path = m.__path__
if type(new_path) == types.ListType :
new_path = filename
if new_path not in path :
path.insert(1, new_path)
elif smt[-1] != imp.PY_COMPILED:
if p is not packages[-1] :
if file is not None :
file.close()
raise ImportError, "No module named %s" % packages[-1]
return file, filename, smt
# in case we have been given a package to check
return file, filename, smt
class Variable :
"Class to hold all information about a variable"
def __init__(self, name, type):
self.name = name
self.type = type
self.value = None
def __str__(self) :
return self.name
__repr__ = utils.std_repr
def _filterDir(object, ignoreList) :
"Return a list of tokens (attributes) in a class, except for ignoreList"
tokens = dir(object)
for token in ignoreList :
if token in tokens :
tokens.remove(token)
return tokens
def _getClassTokens(c) :
return _filterDir(c, _DEFAULT_CLASS_TOKENS)
class Class :
"Class to hold all information about a class"
def __init__(self, name, pcmodule) :
"""
@type pcmodule: PyCheckerModule
"""
self.name = name
module = pcmodule.module
self.classObject = getattr(module, name)
modname = getattr(self.classObject, '__module__', None)
if modname is None:
# hm, some ExtensionClasses don't have a __module__ attribute
# so try parsing the type output
typerepr = repr(type(self.classObject))
mo = re.match("^<type ['\"](.+)['\"]>$", typerepr)
if mo:
modname = ".".join(mo.group(1).split(".")[:-1])
# TODO(nnorwitz): this check for __name__ might not be necessary
# any more. Previously we checked objects as if they were classes.
# This problem is fixed by not adding objects as if they are classes.
# zope.interface for example has Provides and Declaration that
# look a lot like class objects but do not have __name__
if not hasattr(self.classObject, '__name__'):
if modname not in cfg().blacklist:
sys.stderr.write("warning: no __name__ attribute "
"for class %s (module name: %s)\n"
% (self.classObject, modname))
self.classObject.__name__ = name
# later pychecker code uses this
self.classObject__name__ = self.classObject.__name__
self.module = sys.modules.get(modname)
# if the pcmodule has moduleDir, it means we processed it before,
# and deleted it from sys.modules
if not self.module and not pcmodule.moduleDir:
self.module = module
if modname not in cfg().blacklist:
sys.stderr.write("warning: couldn't find real module "
"for class %s (module name: %s)\n"
% (self.classObject, modname))
self.ignoreAttrs = 0
self.methods = {}
self.members = { '__class__': types.ClassType,
'__doc__': types.StringType,
'__dict__': types.DictType, }
self.memberRefs = {}
self.statics = {}
self.lineNums = {}
def __str__(self) :
return self.name
__repr__ = utils.std_repr
def getFirstLine(self) :
"Return first line we can find in THIS class, not any base classes"
lineNums = []
classDir = dir(self.classObject)
for m in self.methods.values() :
if m != None and m.function.func_code.co_name in classDir:
lineNums.append(m.function.func_code.co_firstlineno)
if lineNums :
return min(lineNums)
return 0
def allBaseClasses(self, c = None) :
"Return a list of all base classes for this class and it's subclasses"
baseClasses = []
if c == None :
c = self.classObject
for base in getattr(c, '__bases__', None) or ():
baseClasses = baseClasses + [ base ] + self.allBaseClasses(base)
return baseClasses
def __getMethodName(self, func_name, className = None) :
if func_name[0:2] == '__' and func_name[-2:] != '__' :
if className == None :
className = self.name
if className[0] != '_' :
className = '_' + className
func_name = className + func_name
return func_name
def addMethod(self, method, methodName = None) :
if type(method) == types.StringType :
self.methods[method] = None
else :
assert methodName is not None, "must supply methodName"
self.methods[methodName] = function.Function(method, 1)
def addMethods(self, classObject) :
for classToken in _getClassTokens(classObject) :
token = getattr(classObject, classToken, None)
if token is None:
continue
# Looks like a method. Need to code it this way to
# accommodate ExtensionClass and Python 2.2. Yecchh.
if (hasattr(token, "func_code") and
hasattr(token.func_code, "co_argcount")):
self.addMethod(token, token.__name__)
elif hasattr(token, '__get__') and \
not hasattr(token, '__set__') and \
type(token) is not types.ClassType :
self.addMethod(getattr(token, '__name__', classToken))
else :
self.members[classToken] = type(token)
self.memberRefs[classToken] = None
self.cleanupMemberRefs()
# add standard methods
for methodName in ('__class__',) :
self.addMethod(methodName, self.classObject__name__)
def addMembers(self, classObject) :
if not cfg().onlyCheckInitForMembers :
for classToken in _getClassTokens(classObject) :
method = getattr(classObject, classToken, None)
if type(method) == types.MethodType :
self.addMembersFromMethod(method.im_func)
else:
try:
self.addMembersFromMethod(classObject.__init__.im_func)
except AttributeError:
pass
def addMembersFromMethod(self, method) :
if not hasattr(method, 'func_code') :
return
func_code, code, i, maxCode, extended_arg = OP.initFuncCode(method)
stack = []
while i < maxCode :
op, oparg, i, extended_arg = OP.getInfo(code, i, extended_arg)
if op >= OP.HAVE_ARGUMENT :
operand = OP.getOperand(op, func_code, oparg)
if OP.LOAD_CONST(op) or OP.LOAD_FAST(op) or OP.LOAD_GLOBAL(op):
stack.append(operand)
elif OP.LOAD_DEREF(op):
try:
operand = func_code.co_cellvars[oparg]
except IndexError:
index = oparg - len(func_code.co_cellvars)
operand = func_code.co_freevars[index]
stack.append(operand)
elif OP.STORE_ATTR(op) :
if len(stack) > 0 :
if stack[-1] == cfg().methodArgName:
value = None
if len(stack) > 1 :
value = type(stack[-2])
self.members[operand] = value
self.memberRefs[operand] = None
stack = []
self.cleanupMemberRefs()
def cleanupMemberRefs(self) :
try :
del self.memberRefs[Config.CHECKER_VAR]
except KeyError :
pass
def abstractMethod(self, m):
"""Return 1 if method is abstract, None if not
An abstract method always raises an exception.
"""
if not self.methods.get(m, None):
return None
func_code, bytes, i, maxCode, extended_arg = \
OP.initFuncCode(self.methods[m].function)
# abstract if the first opcode is RAISE_VARARGS and it raises
# NotImplementedError
arg = ""
while i < maxCode:
op, oparg, i, extended_arg = OP.getInfo(bytes, i, extended_arg)
if OP.LOAD_GLOBAL(op):
arg = func_code.co_names[oparg]
elif OP.RAISE_VARARGS(op):
# if we saw NotImplementedError sometime before the raise
# assume it's related to this raise stmt
return arg == "NotImplementedError"
if OP.conditional(op):
break
return None
def isAbstract(self):
"""Return the method names that make a class abstract.
An abstract class has at least one abstract method."""
result = []
for m in self.methods.keys():
if self.abstractMethod(m):
result.append(m)
return result
def _getLineInFile(moduleName, moduleDir, linenum):
line = ''
file, filename, smt = _findModule(moduleName, moduleDir)
if file is None:
return ''
try:
lines = file.readlines()
line = string.rstrip(lines[linenum - 1])
except (IOError, IndexError):
pass
file.close()
return line
def importError(moduleName, moduleDir=None):
exc_type, exc_value, tb = sys.exc_info()
# First, try to get a nice-looking name for this exception type.
exc_name = getattr(exc_type, '__name__', None)
if not exc_name:
# either it's a string exception or a user-defined exception class
# show string or fully-qualified class name
exc_name = utils.safestr(exc_type)
# Print a traceback, unless this is an ImportError. ImportError is
# presumably the most common import-time exception, so this saves
# the clutter of a traceback most of the time. Also, the locus of
# the error is usually irrelevant for ImportError, so the lack of
# traceback shouldn't be a problem.
if exc_type is SyntaxError:
# SyntaxErrors are special, we want to control how we format
# the output and make it consistent for all versions of Python
e = exc_value
msg = '%s (%s, line %d)' % (e.msg, e.filename, e.lineno)
line = _getLineInFile(moduleName, moduleDir, e.lineno)
offset = e.offset
if type(offset) is not types.IntType:
offset = 0
exc_value = '%s\n %s\n %s^' % (msg, line, ' ' * offset)
elif exc_type is not ImportError:
sys.stderr.write(" Caught exception importing module %s:\n" %
moduleName)
try:
tbinfo = traceback.extract_tb(tb)
except:
tbinfo = []
sys.stderr.write(" Unable to format traceback\n")
for filename, line, func, text in tbinfo[1:]:
sys.stderr.write(" File \"%s\", line %d" % (filename, line))
if func != "?":
sys.stderr.write(", in %s()" % func)
sys.stderr.write("\n")
if text:
sys.stderr.write(" %s\n" % text)
# And finally print the exception type and value.
# Careful formatting exc_value -- can fail for some user exceptions
sys.stderr.write(" %s: " % exc_name)
try:
sys.stderr.write(utils.safestr(exc_value) + '\n')
except:
sys.stderr.write('**error formatting exception value**\n')
def _getPyFile(filename):
"""Return the file and '.py' filename from a filename which could
end with .py, .pyc, or .pyo"""
if filename[-1] in 'oc' and filename[-4:-1] == '.py':
return filename[:-1]
return filename
class PyCheckerModule :
"Class to hold all information for a module"
def __init__(self, moduleName, check = 1, moduleDir=None) :
"""
@param moduleDir: if specified, the directory where the module can
be loaded from; allows discerning between modules
with the same name in a different directory
"""
self.moduleName = moduleName
self.moduleDir = moduleDir
self.variables = {}
self.functions = {}
self.classes = {}
self.modules = {}
self.moduleLineNums = {}
self.attributes = [ '__dict__' ]
self.main_code = None
self.module = None
self.check = check
# key on a combination of moduleName and moduleDir so we have separate
# entries for modules with the same name but in different directories
pcmodules.addPCModule(self)
def __str__(self) :
return self.moduleName
__repr__ = utils.std_repr
def addVariable(self, var, varType) :
self.variables[var] = Variable(var, varType)
def addFunction(self, func) :
self.functions[func.__name__] = function.Function(func)
def __addAttributes(self, c, classObject) :
for base in getattr(classObject, '__bases__', None) or ():
self.__addAttributes(c, base)
c.addMethods(classObject)
c.addMembers(classObject)
def addClass(self, name) :
self.classes[name] = c = Class(name, self)
try:
objName = utils.safestr(c.classObject)
except TypeError:
# this can happen if there is a goofy __getattr__
c.ignoreAttrs = 1
else:
packages = string.split(objName, '.')
c.ignoreAttrs = packages[0] in cfg().blacklist
if not c.ignoreAttrs :
self.__addAttributes(c, c.classObject)
def addModule(self, name, moduleDir=None) :
module = pcmodules.getPCModule(name, moduleDir)
if module is None :
self.modules[name] = module = PyCheckerModule(name, 0)
if imp.is_builtin(name) == 0:
module.load()
else :
globalModule = globals().get(name)
if globalModule :
module.attributes.extend(dir(globalModule))
else :
self.modules[name] = module
def filename(self) :
try :
filename = self.module.__file__
except AttributeError :
filename = self.moduleName
# FIXME: this would be nice to have, but changes output of
# NOT PROCESSED UNABLE TO IMPORT like in test8
#if self.moduleDir:
# filename = self.moduleDir + ': ' + filename
return _getPyFile(filename)
def load(self):
try :
# there's no need to reload modules we already have if no moduleDir
# is specified for this module
if not self.moduleDir:
module = sys.modules.get(self.moduleName)
if module :
if not pcmodules.getPCModule(self.moduleName).module :
return self._initModule(module)
return 1
return self._initModule(self.setupMainCode())
except (SystemExit, KeyboardInterrupt) :
exc_type, exc_value, exc_tb = sys.exc_info()
raise exc_type, exc_value
except :
importError(self.moduleName, self.moduleDir)
return cfg().ignoreImportErrors
def initModule(self, module) :
if not self.module:
filename = _getPyFile(module.__file__)
if string.lower(filename[-3:]) == '.py':
try:
file = open(filename)
except IOError:
pass
else:
self._setupMainCode(file, filename, module)
return self._initModule(module)
return 1
def _initModule(self, module):
self.module = module
self.attributes = dir(self.module)
pychecker_attr = getattr(module, Config.CHECKER_VAR, None)
if pychecker_attr is not None :
utils.pushConfig()
utils.updateCheckerArgs(pychecker_attr, 'suppressions', 0, [])
for tokenName in _filterDir(self.module, _DEFAULT_MODULE_TOKENS) :
if _EVIL_C_OBJECTS.has_key('%s.%s' % (self.moduleName, tokenName)):
continue
# README if interpreter is crashing:
# Change 0 to 1 if the interpretter is crashing and re-run.
# Follow the instructions from the last line printed.
if _cfg.findEvil:
print "Add the following line to _EVIL_C_OBJECTS or the string to evil in a config file:\n" \
" '%s.%s': None, " % (self.moduleName, tokenName)
token = getattr(self.module, tokenName)
if isinstance(token, types.ModuleType) :
# get the real module name, tokenName could be an alias
self.addModule(token.__name__)
elif isinstance(token, types.FunctionType) :
self.addFunction(token)
elif isinstance(token, types.ClassType) or \
hasattr(token, '__bases__') and \
issubclass(type(token), type):
self.addClass(tokenName)
else :
self.addVariable(tokenName, type(token))
if pychecker_attr is not None :
utils.popConfig()
return 1
def setupMainCode(self) :
file, filename, smt = _findModule(self.moduleName, self.moduleDir)
# FIXME: if the smt[-1] == imp.PKG_DIRECTORY : load __all__
# HACK: to make sibling imports work, we add self.moduleDir to sys.path
# temporarily, and remove it later
if self.moduleDir:
oldsyspath = sys.path[:]
sys.path.insert(0, self.moduleDir)
module = imp.load_module(self.moduleName, file, filename, smt)
if self.moduleDir:
sys.path = oldsyspath
# to make sure that subsequent modules with the same moduleName
# do not persist, and get their namespace clobbered, delete it
del sys.modules[self.moduleName]
self._setupMainCode(file, filename, module)
return module
def _setupMainCode(self, file, filename, module):
try :
self.main_code = function.create_from_file(file, filename, module)
finally :
if file != None :
file.close()
def getAllModules() :
"Returns a list of all modules that should be checked."
modules = []
for module in pcmodules.getPCModules():
if module.check :
modules.append(module)
return modules
_BUILTIN_MODULE_ATTRS = { 'sys': [ 'ps1', 'ps2', 'tracebacklimit',
'exc_type', 'exc_value', 'exc_traceback',
'last_type', 'last_value', 'last_traceback',
],
}
def fixupBuiltinModules(needs_init=0):
for moduleName in sys.builtin_module_names :
# Skip sys since it will reset sys.stdout in IDLE and cause
# stdout to go to the real console rather than the IDLE console.
# FIXME: this breaks test42
# if moduleName == 'sys':
# continue
if needs_init:
_ = PyCheckerModule(moduleName, 0)
# builtin modules don't have a moduleDir
module = pcmodules.getPCModule(moduleName)
if module is not None :
try :
m = imp.init_builtin(moduleName)
except ImportError :
pass
else :
extra_attrs = _BUILTIN_MODULE_ATTRS.get(moduleName, [])
module.attributes = [ '__dict__' ] + dir(m) + extra_attrs
def _printWarnings(warnings, stream=None):
if stream is None:
stream = sys.stdout
warnings.sort()
lastWarning = None
for warning in warnings :
if lastWarning is not None:
# ignore duplicate warnings
if cmp(lastWarning, warning) == 0:
continue
# print blank line between files
if lastWarning.file != warning.file:
stream.write("\n")
lastWarning = warning
warning.output(stream)
class NullModule:
def __getattr__(self, unused_attr):
return None
def install_ignore__import__():
_orig__import__ = None
def __import__(name, globals=None, locals=None, fromlist=None):
if globals is None:
globals = {}
if locals is None:
locals = {}
if fromlist is None:
fromlist = ()
try:
pymodule = _orig__import__(name, globals, locals, fromlist)
except ImportError:
pymodule = NullModule()
if not _cfg.quiet:
modname = '.'.join((name,) + fromlist)
sys.stderr.write("Can't import module: %s, ignoring.\n" % modname)
return pymodule
# keep the orig __import__ around so we can call it
import __builtin__
_orig__import__ = __builtin__.__import__
__builtin__.__import__ = __import__
def processFiles(files, cfg = None, pre_process_cb = None) :
# insert this here, so we find files in the local dir before std library
if sys.path[0] != '' :
sys.path.insert(0, '')
# ensure we have a config object, it's necessary
global _cfg
if cfg is not None :
_cfg = cfg
elif _cfg is None :
_cfg = Config.Config()
if _cfg.ignoreImportErrors:
install_ignore__import__()
warnings = []
utils.initConfig(_cfg)
for file, (moduleName, moduleDir) in zip(files, getModules(files)) :
if callable(pre_process_cb) :
pre_process_cb("module %s (%s)" % (moduleName, file))
oldsyspath = sys.path[:]
sys.path.insert(0, moduleDir)
module = PyCheckerModule(moduleName, moduleDir=moduleDir)
if not module.load() :
w = Warning(module.filename(), 1,
msgs.Internal("NOT PROCESSED UNABLE TO IMPORT"))
warnings.append(w)
sys.path = oldsyspath
utils.popConfig()
return warnings
def getWarnings(files, cfg = None, suppressions = None):
warnings = processFiles(files, cfg)
fixupBuiltinModules()
return warnings + warn.find(getAllModules(), _cfg, suppressions)
def _print_processing(name) :
if not _cfg.quiet :
sys.stderr.write("Processing %s...\n" % name)
def main(argv) :
__pychecker__ = 'no-miximport'
import pychecker
if LOCAL_MAIN_VERSION != pychecker.MAIN_MODULE_VERSION :
sys.stderr.write(_VERSION_MISMATCH_ERROR)
sys.exit(100)
# remove empty arguments
argv = filter(None, argv)
# if the first arg starts with an @, read options from the file
# after the @ (this is mostly for windows)
if len(argv) >= 2 and argv[1][0] == '@':
# read data from the file
command_file = argv[1][1:]
try:
f = open(command_file, 'r')
command_line = f.read()
f.close()
except IOError, err:
sys.stderr.write("Unable to read commands from file: %s\n %s\n" % \
(command_file, err))
sys.exit(101)
# convert to an argv list, keeping argv[0] and the files to process
argv = argv[:1] + string.split(command_line) + argv[2:]
global _cfg
_cfg, files, suppressions = Config.setupFromArgs(argv[1:])
if not files :
return 0
# Now that we've got the args, update the list of evil C objects
for evil_doer in _cfg.evil:
_EVIL_C_OBJECTS[evil_doer] = None
# insert this here, so we find files in the local dir before std library
sys.path.insert(0, '')
importWarnings = processFiles(files, _cfg, _print_processing)
fixupBuiltinModules()
if _cfg.printParse :
for module in getAllModules() :
printer.module(module)
warnings = warn.find(getAllModules(), _cfg, suppressions)
if not _cfg.quiet :
print "\nWarnings...\n"
if warnings or importWarnings :
_printWarnings(importWarnings + warnings)
return 1
if not _cfg.quiet :
print "None"
return 0
if __name__ == '__main__' :
try :
sys.exit(main(sys.argv))
except Config.UsageError :
sys.exit(127)
else :
_orig__import__ = None
_suppressions = None
_warnings_cache = {}
def _get_unique_warnings(warnings):
for i in range(len(warnings)-1, -1, -1):
w = warnings[i].format()
if _warnings_cache.has_key(w):
del warnings[i]
else:
_warnings_cache[w] = 1
return warnings
def __import__(name, globals=None, locals=None, fromlist=None):
if globals is None:
globals = {}
if locals is None:
locals = {}
if fromlist is None:
fromlist = []
check = not sys.modules.has_key(name) and name[:10] != 'pychecker.'
pymodule = _orig__import__(name, globals, locals, fromlist)
if check :
try :
# FIXME: can we find a good moduleDir ?
module = PyCheckerModule(pymodule.__name__)
if module.initModule(pymodule):
warnings = warn.find([module], _cfg, _suppressions)
_printWarnings(_get_unique_warnings(warnings))
else :
print 'Unable to load module', pymodule.__name__
except Exception:
name = getattr(pymodule, '__name__', utils.safestr(pymodule))
# FIXME: can we use it here ?
importError(name)
return pymodule
def _init() :
global _cfg, _suppressions, _orig__import__
args = string.split(os.environ.get('PYCHECKER', ''))
_cfg, files, _suppressions = Config.setupFromArgs(args)
utils.initConfig(_cfg)
fixupBuiltinModules(1)
# keep the orig __import__ around so we can call it
import __builtin__
_orig__import__ = __builtin__.__import__
__builtin__.__import__ = __import__
if not os.environ.get('PYCHECKER_DISABLED') :
_init()
|
aekryz1993/system-administration | client/auth/validate.js | import { isEmpty } from '../utils/validations';
const validate = values => {
const { username, password } = values;
const errors = {};
if(isEmpty(username)) errors.username = 'Username Required';
if(isEmpty(password)) errors.password = '<PASSWORD>';
return errors;
};
export default validate; |
bshawk/clappr | src/components/iframe_player/iframe_player.js | <reponame>bshawk/clappr<gh_stars>1-10
// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var BaseObject = require('base_object')
var $ = require('jquery')
var Player = require('../player')
class IframePlayer extends BaseObject {
constructor(options) {
super(options)
this.options = options
this.createIframe()
}
createIframe() {
this.iframe = document.createElement("iframe")
this.iframe.setAttribute("frameborder", 0)
this.iframe.setAttribute("id", this.uniqueId)
this.iframe.setAttribute("allowfullscreen", true)
this.iframe.setAttribute("scrolling", "no")
this.iframe.setAttribute("src", "http://cdn.clappr.io/latest/assets/iframe.htm" + this.buildQueryString())
this.iframe.setAttribute('width', this.options.width)
this.iframe.setAttribute('height', this.options.height)
}
attachTo(element) {
element.appendChild(this.iframe)
}
addEventListeners() {
this.iframe.contentWindow.addEventListener("fullscreenchange", () => this.updateSize())
this.iframe.contentWindow.addEventListener("webkitfullscreenchange", () => this.updateSize())
this.iframe.contentWindow.addEventListener("mozfullscreenchange", () => this.updateSize())
}
buildQueryString() {
var result = ""
for (var param in this.options) {
result += !!result? "&" : "?"
result += encodeURIComponent(param) + "=" + encodeURIComponent(this.options[param])
}
return result
}
}
module.exports = IframePlayer
|
liszekei/eggroll | jvm/core/main/scala/com/webank/eggroll/core/schedule/TaskPlan.scala | <filename>jvm/core/main/scala/com/webank/eggroll/core/schedule/TaskPlan.scala
/*
* Copyright (c) 2019 - now, Eggroll Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package com.webank.eggroll.core.schedule
import com.webank.eggroll.core.command.CommandURI
import com.webank.eggroll.core.datastructure.TaskPlan
import com.webank.eggroll.core.meta.ErJob
abstract class BaseTaskPlan(_uri: CommandURI, _job: ErJob) extends TaskPlan {
override def job: ErJob = _job
override def uri: CommandURI = _uri
}
class MapTaskPlan(uri: CommandURI, job: ErJob) extends BaseTaskPlan(uri, job) {
override def shouldShuffle = true
}
class ReduceTaskPlan(uri: CommandURI, job: ErJob) extends BaseTaskPlan(uri, job) {
override def isAggregate: Boolean = true
}
class ShuffleTaskPlan(uri: CommandURI, job: ErJob) extends BaseTaskPlan(uri, job) {
override def shouldShuffle: Boolean = true
}
class JoinTaskPlan(uri: CommandURI, job: ErJob) extends BaseTaskPlan(uri, job)
class AggregateTaskPlan(uri: CommandURI, job: ErJob) extends BaseTaskPlan(uri, job) {
override def isAggregate: Boolean = true
}
class DestroyTaskPlan(uri: CommandURI, job: ErJob) extends BaseTaskPlan(uri, job)
class FlatMapTaskPlan(uri: CommandURI, job: ErJob) extends BaseTaskPlan(uri, job)
class GlomTaskPlan(uri: CommandURI, job: ErJob) extends BaseTaskPlan(uri, job)
class SampleTaskPlan(uri: CommandURI, job: ErJob) extends BaseTaskPlan(uri, job)
class FilterTaskPlan(uri: CommandURI, job: ErJob) extends BaseTaskPlan(uri, job)
class SubtractByKeyTaskPlan(uri: CommandURI, job: ErJob) extends BaseTaskPlan(uri, job)
class UnionTaskPlan(uri: CommandURI, job: ErJob) extends BaseTaskPlan(uri, job)
class PutAllTaskPlan(uri: CommandURI, job: ErJob) extends BaseTaskPlan(uri, job)
class GetAllTaskPlan(uri: CommandURI, job: ErJob) extends BaseTaskPlan(uri, job)
class CollapsePartitionsTaskPlan(uri: CommandURI, job: ErJob) extends BaseTaskPlan(uri, job)
class MapValuesTaskPlan(uri: CommandURI, job: ErJob) extends BaseTaskPlan(uri, job)
class MapPartitionsTaskPlan(uri: CommandURI, job: ErJob) extends ShuffleTaskPlan(uri, job)
|
vishalbelsare/Gaffer | library/spark/spark-accumulo-library/src/test/java/uk/gov/gchq/gaffer/sparkaccumulo/operation/handler/javardd/GetJavaRDDOfElementsInRangesHandlerTest.java | /*
* Copyright 2016-2018 Crown Copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.gchq.gaffer.sparkaccumulo.operation.handler.javardd;
import org.apache.hadoop.conf.Configuration;
import org.apache.spark.api.java.JavaRDD;
import uk.gov.gchq.gaffer.accumulostore.operation.handler.GetElementsInRangesHandlerTest;
import uk.gov.gchq.gaffer.commonutil.pair.Pair;
import uk.gov.gchq.gaffer.data.element.Element;
import uk.gov.gchq.gaffer.data.element.id.DirectedType;
import uk.gov.gchq.gaffer.data.element.id.ElementId;
import uk.gov.gchq.gaffer.data.elementdefinition.view.View;
import uk.gov.gchq.gaffer.operation.graph.SeededGraphFilters.IncludeIncomingOutgoingType;
import uk.gov.gchq.gaffer.sparkaccumulo.operation.handler.AbstractGetRDDHandler;
import uk.gov.gchq.gaffer.sparkaccumulo.operation.javardd.GetJavaRDDOfElementsInRanges;
import uk.gov.gchq.gaffer.store.operation.handler.OutputOperationHandler;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class GetJavaRDDOfElementsInRangesHandlerTest extends GetElementsInRangesHandlerTest {
private final String configurationString;
public GetJavaRDDOfElementsInRangesHandlerTest() {
final Configuration configuration = new Configuration();
try {
configurationString = AbstractGetRDDHandler.convertConfigurationToString(configuration);
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
@Override
protected OutputOperationHandler createHandler() {
return new GetJavaRDDOfElementsInRangesHandler();
}
@Override
protected GetJavaRDDOfElementsInRanges createOperation(final Set<Pair<ElementId, ElementId>> simpleEntityRanges, final View view, final IncludeIncomingOutgoingType inOutType, final DirectedType directedType) {
return new GetJavaRDDOfElementsInRanges.Builder()
.input(simpleEntityRanges)
.view(view)
.directedType(directedType)
.inOutType(inOutType)
.option(AbstractGetRDDHandler.HADOOP_CONFIGURATION_KEY, configurationString)
.build();
}
@Override
protected List<Element> parseResults(final Object results) {
return new ArrayList<>(((JavaRDD<Element>) results).collect());
}
}
|
nhojpatrick/nhojpatrick-cucumber | json-core/src/test/java/com/github/nhojpatrick/cucumber/json/core/exceptions/tests/NullPathElementExceptionTest.java | package com.github.nhojpatrick.cucumber.json.core.exceptions.tests;
import com.github.nhojpatrick.cucumber.json.core.exceptions.NullPathElementException;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.api.function.Executable;
import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
public class NullPathElementExceptionTest {
@TestFactory
public Collection<DynamicTest> exceptions() {
return Arrays.asList(
dynamicTest("message", () -> {
final Executable testMethod = () -> {
throw new NullPathElementException();
};
final NullPathElementException thrown = assertThrows(NullPathElementException.class, testMethod);
assertAll(
() -> assertThat(thrown.getMessage(), is(equalTo("Null Path Element."))),
() -> assertThat(thrown.getCause(), is(nullValue()))
);
})
);
}
}
|
FilipaDurao/FEUP_SDIS | src/proj/peer/operations/DeleteFileOperation.java | <filename>src/proj/peer/operations/DeleteFileOperation.java<gh_stars>0
package proj.peer.operations;
import proj.peer.Peer;
import proj.peer.log.NetworkLogger;
import java.util.logging.Level;
public class DeleteFileOperation implements Runnable {
private Peer peer;
private String filename;
public DeleteFileOperation(Peer peer, String filename) {
this.peer = peer;
this.filename = filename;
}
@Override
public void run() {
try {
this.peer.getFileManager().deleteFile(filename);
NetworkLogger.printLog(Level.INFO, "File " + filename.substring(0, 5) + " deleted from memory");
} catch (Exception e) {
NetworkLogger.printLog(Level.WARNING, "Failed to erase file - " + e.getMessage());
}
}
}
|
JCWasmx86/java-gtk | java-gtk/src/main/java/ch/bailu/gtk/helper/BuilderHelper.java | <filename>java-gtk/src/main/java/ch/bailu/gtk/helper/BuilderHelper.java<gh_stars>1-10
package ch.bailu.gtk.helper;
import java.io.File;
import ch.bailu.gtk.exception.AllocationError;
import ch.bailu.gtk.gtk.Builder;
import ch.bailu.gtk.type.CPointer;
import ch.bailu.gtk.type.Str;
public class BuilderHelper {
private final Builder builder = new Builder();
public BuilderHelper(String path, String file) throws AllocationError {
this(new File(path, file));
}
public BuilderHelper(File file) throws AllocationError {
Str path = new Str(file.getAbsolutePath());
builder.addFromFile(path);
path.destroy();
}
public CPointer getObject(String name) {
var n = new Str(name);
var result = builder.getObject(n).cast();
n.destroy();
return result;
}
}
|
dwt/capybara.py | capybara/tests/session/test_has_select.py | import pytest
class HasSelectTestCase:
@pytest.fixture(autouse=True)
def setup_session(self, session):
session.visit("/form")
class TestHasSelect(HasSelectTestCase):
def test_is_true_if_the_field_is_on_the_page(self, session):
assert session.has_select("Locale")
assert session.has_select("form_region")
assert session.has_select("Languages")
def test_is_false_if_the_field_is_not_on_the_page(self, session):
assert not session.has_select("Monkey")
class TestHasSelectWithSelected(HasSelectTestCase):
def test_is_true_if_a_field_with_the_given_value_is_on_the_page(self, session):
assert session.has_select("form_locale", selected="English")
assert session.has_select("Region", selected="Norway")
assert session.has_select("Underwear", selected=[
"Boxerbriefs", "Briefs", "Commando", "Frenchman's Pantalons", "Long Johns"])
def test_is_false_if_the_given_field_is_not_on_the_page(self, session):
assert not session.has_select("Locale", selected="Swedish")
assert not session.has_select("Does not exist", selected="John")
assert not session.has_select("City", selected="Not there")
assert not session.has_select("Underwear", selected=[
"Boxerbriefs", "Briefs", "Commando", "Frenchman's Pantalons", "Long Johns",
"Nonexistant"])
assert not session.has_select("Underwear", selected=[
"Boxerbriefs", "Briefs", "Boxers", "Commando", "Frenchman's Pantalons", "Long Johns"])
assert not session.has_select("Underwear", selected=[
"Boxerbriefs", "Briefs", "Commando", "Frenchman's Pantalons"])
def test_is_true_after_the_given_value_is_selected(self, session):
session.select("Swedish", field="Locale")
assert session.has_select("Locale", selected="Swedish")
def test_is_false_after_a_different_value_is_selected(self, session):
session.select("Swedish", field="Locale")
assert not session.has_select("Locale", selected="English")
def test_is_true_after_the_given_values_are_selected(self, session):
session.select("Boxers", field="Underwear")
assert session.has_select("Underwear", selected=[
"Boxerbriefs", "Briefs", "Boxers", "Commando", "Frenchman's Pantalons", "Long Johns"])
def test_is_false_after_one_of_the_values_is_unselected(self, session):
session.unselect("Briefs", field="Underwear")
assert not session.has_select("Underwear", selected=[
"Boxerbriefs", "Briefs", "Commando", "Frenchman's Pantalons", "Long Johns"])
def test_is_true_even_when_the_selected_option_is_invisible_regardless_of_select_visibility(self, session):
assert session.has_select("Icecream", visible=False, selected="Chocolate")
assert session.has_select("Sorbet", selected="Vanilla")
class TestHasSelectWithExactOptions(HasSelectTestCase):
def test_is_true_if_a_field_with_the_given_options_is_on_the_page(self, session):
assert session.has_select("Region", options=["Norway", "Sweden", "Finland"])
assert session.has_select("Tendency", options=[])
def test_is_false_if_the_given_field_is_not_on_the_page(self, session):
assert not session.has_select("Locale", options=["Swedish"])
assert not session.has_select("Does not exist", options=["John"])
assert not session.has_select("City", options=["London", "Made up city"])
assert not session.has_select("Region", options=["Norway", "Sweden"])
assert not session.has_select("Region", options=["Norway", "Norway", "Norway"])
def test_is_true_even_when_the_options_are_invisible_if_the_select_is_invisible(self, session):
assert session.has_select("Icecream", visible=False, options=["Chocolate", "Vanilla", "Strawberry"])
class TestHasSelectWithPartialOptions(HasSelectTestCase):
def test_is_true_if_a_field_with_the_given_partial_options_is_on_the_page(self, session):
assert session.has_select("Region", with_options=["Norway", "Sweden"])
assert session.has_select("City", with_options=["London"])
def test_is_false_if_a_field_with_the_given_partial_options_is_not_on_the_page(self, session):
assert not session.has_select("Locale", with_options=["Uruguayan"])
assert not session.has_select("Does not exist", with_options=["John"])
assert not session.has_select("Region", with_options=["Norway", "Sweden", "Finland", "Latvia"])
def test_is_true_even_when_the_options_are_invisible_if_the_select_itself_is_invisible(self, session):
assert session.has_select("Icecream", visible=False, with_options=["Vanilla", "Strawberry"])
class TestHasSelectMultiple(HasSelectTestCase):
def test_finds_multiple_selects_if_true(self, session):
assert session.has_select("form_languages", multiple=True)
assert not session.has_select("form_other_title", multiple=True)
def test_does_not_find_multiple_selects_if_false(self, session):
assert not session.has_select("form_languages", multiple=False)
assert session.has_select("form_other_title", multiple=False)
def test_finds_both_if_not_specified(self, session):
assert session.has_select("form_languages")
assert session.has_select("form_other_title")
class TestHasNoSelect(HasSelectTestCase):
def test_is_false_if_the_field_is_on_the_page(self, session):
assert not session.has_no_select("Locale")
assert not session.has_no_select("form_region")
assert not session.has_no_select("Languages")
def test_is_true_if_the_field_is_not_on_the_page(self, session):
assert session.has_no_select("Monkey")
class TestHasNoSelectWithSelected(HasSelectTestCase):
def test_is_false_if_a_field_with_the_given_value_is_on_the_page(self, session):
assert not session.has_no_select("form_locale", selected="English")
assert not session.has_no_select("Region", selected="Norway")
assert not session.has_no_select("Underwear", selected=[
"Boxerbriefs", "Briefs", "Commando", "Frenchman's Pantalons", "Long Johns"])
def test_is_true_if_the_given_field_is_not_on_the_page(self, session):
assert session.has_no_select("Locale", selected="Swedish")
assert session.has_no_select("Does not exist", selected="John")
assert session.has_no_select("City", selected="Not there")
assert session.has_no_select("Underwear", selected=[
"Boxerbriefs", "Briefs", "Commando", "Frenchman's Pantalons", "Long Johns", "Nonexistant"])
assert session.has_no_select("Underwear", selected=[
"Boxerbriefs", "Briefs", "Boxers", "Commando", "Frenchman's Pantalons", "Long Johns"])
assert session.has_no_select("Underwear", selected=[
"Boxerbriefs", "Briefs", "Commando", "Frenchman's Pantalons"])
def test_is_false_after_the_given_value_is_selected(self, session):
session.select("Swedish", field="Locale")
assert not session.has_no_select("Locale", selected="Swedish")
def test_is_true_after_a_different_value_is_selected(self, session):
session.select("Swedish", field="Locale")
assert session.has_no_select("Locale", selected="English")
def test_is_false_after_the_given_values_are_selected(self, session):
session.select("Boxers", field="Underwear")
assert not session.has_no_select("Underwear", selected=[
"Boxerbriefs", "Briefs", "Boxers", "Commando", "Frenchman's Pantalons", "Long Johns"])
def test_is_true_after_one_of_the_values_is_unselected(self, session):
session.unselect("Briefs", field="Underwear")
assert session.has_no_select("Underwear", selected=[
"Boxerbriefs", "Briefs", "Commando", "Frenchman's Pantalons", "Long Johns"])
class TestHasNoSelectWithExactOptions(HasSelectTestCase):
def test_is_false_if_a_field_with_the_given_options_is_on_the_page(self, session):
assert not session.has_no_select("Region", options=["Norway", "Sweden", "Finland"])
def test_is_true_if_the_given_field_is_not_on_the_page(self, session):
assert session.has_no_select("Locale", options=["Swedish"])
assert session.has_no_select("Does not exist", options=["John"])
assert session.has_no_select("City", options=["London", "Made up city"])
assert session.has_no_select("Region", options=["Norway", "Sweden"])
assert session.has_no_select("Region", options=["Norway", "Norway", "Norway"])
class TestHasNoSelectWithPartialOptions(HasSelectTestCase):
def test_is_false_if_a_field_with_the_given_partial_options_is_on_the_page(self, session):
assert not session.has_no_select("Region", with_options=["Norway", "Sweden"])
assert not session.has_no_select("City", with_options=["London"])
def test_is_true_if_a_field_with_the_given_partial_options_is_not_on_the_page(self, session):
assert session.has_no_select("Locale", with_options=["Uruguayan"])
assert session.has_no_select("Does not exist", with_options=["John"])
assert session.has_no_select("Region", with_options=["Norway", "Sweden", "Finland", "Latvia"])
|
Usuario001/carbon_footprint | src/components/Quiz/business-quiz.js | import React, { useState, useReducer } from 'react';
import styled from 'styled-components';
import Quiz from './quiz';
import quizData from '../../data/business-carbon-data';
import BuisnessHeader from './BusinessQuiz/buisness-header';
import BuisnessBody from './BusinessQuiz/buisness-body';
import ButtonRows from './BusinessQuiz/button-rows';
const BuisnessWrapper = styled.div`
height: 100%;
width: inherit;
&.next-enter {
transform: translateX(100vw);
${({ theme }) =>
theme.query.bigMobile({
transform: 'translateX(180vw)',
})}
}
&.next-enter-active {
transform: translateX(0%);
transition: transform 1000ms ease-in-out;
${({ theme }) =>
theme.query.bigMobile({
transform: 'translateX(0vw)',
transition: 'transform 1000ms ease-in-out',
})}
}
&.next-exit {
transform: translateX(-50vw);
${({ theme }) =>
theme.query.bigMobile({
transform: 'translateX(-80vw)',
})}
}
&.next-exit-active {
transform: translateX(-200vw);
transition: transform 1000ms ease-in-out;
${({ theme }) =>
theme.query.bigMobile({
transform: 'translateX(-200vw)',
transition: 'transform 1000ms ease-in-out',
})}
}
&.back-enter {
transform: translateX(-100vw);
}
&.back-enter-active {
transform: translateX(0%);
transition: transform 1000ms ease-in-out;
}
&.back-exit {
transform: translateX(-50vw);
${({ theme }) =>
theme.query.bigMobile({
transform: 'translateX(-80vw)',
})}
}
&.back-exit-active {
transform: translateX(100vw);
transition: transform 1000ms ease-in-out;
}
`;
const reducer = (state, action) => {
let newState = { ...state };
let questionIndex = state.questionIndex;
let currentQuizState = newState.quizData[questionIndex];
switch (action.type) {
case 'next':
const questionsLenght = Object.keys(state.quizData).length - 1;
if (state.questionIndex === questionsLenght) return state;
return { ...state, questionIndex: questionIndex + 1 };
case 'done':
return state;
case 'back':
if (questionIndex === 0) return state;
return { ...state, questionIndex: questionIndex - 1 };
case 'reset':
return { ...state, questionIndex: 0 };
case 'addRow':
const newRow = { ...currentQuizState.rowStructure[0] };
currentQuizState.rowStructure.push(newRow);
currentQuizState.savedValue.push(newRow);
console.log(newState);
return newState;
case 'deleteRow':
if (currentQuizState.rowStructure.length <= 2) return newState;
currentQuizState.rowStructure.pop();
currentQuizState.savedValue.pop();
return newState;
case 'handleInput':
currentQuizState.savedValue[action.row][action.name] = action.value;
return newState;
default:
throw new Error('Unexpected action');
}
};
const initialState = {
quizData: { ...quizData },
questionIndex: 0,
};
const BusinessQuiz = () => {
const [state, dispatch] = useReducer(reducer, initialState);
// const handleAddRow = () => {
// const newScreenState = {
// ...formState[questionIndex],
// rowStructure: [...formState[questionIndex].rowStructure, { ...formState[questionIndex].rowsType[0] }],
// };
// setFormState({
// ...formState,
// [questionIndex]: newScreenState,
// });
// };
// const handleDeleteQuestion = () => {
// const newScreenState = {
// ...formState[questionIndex],
// };
// newScreenState.rowStructure.pop();
// setFormState({
// ...formState,
// [questionIndex]: newScreenState,
// });
// };
return (
<Quiz state={state} dispatch={dispatch}>
<BuisnessWrapper>
<BuisnessHeader state={state} />
<BuisnessBody state={state} dispatch={dispatch} />
<ButtonRows dispatch={dispatch} />
</BuisnessWrapper>
</Quiz>
);
};
export default BusinessQuiz;
|
patrickfischer1/WebAPI | src/main/java/org/ohdsi/webapi/cohortresults/mapper/TornadoMapper.java | <filename>src/main/java/org/ohdsi/webapi/cohortresults/mapper/TornadoMapper.java
package org.ohdsi.webapi.cohortresults.mapper;
import org.ohdsi.webapi.cohortresults.TornadoRecord;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TornadoMapper implements RowMapper<TornadoRecord> {
@Override
public TornadoRecord mapRow(ResultSet rs, int rowNum)
throws SQLException {
TornadoRecord record = new TornadoRecord();
record.setAgeGroup(rs.getInt("age_group"));
record.setGenderConceptId(rs.getLong("gender_concept_id"));
record.setPersonCount(rs.getLong("person_count"));
return record;
}
}
|
hzwoo/fusepay | lib/models/sql/gateway-merchant-route.js | /**
* lib/models/sql/gateway-merchant-route.js
*/
'use strict';
const SqlTable = require('../sql-table');
class GatewayMerchantRoute extends SqlTable {
constructor(db) {
super(db);
this.name = 't_gateway_merchant_route';
this.sql = this.db(this.name);
}
}
module.exports = GatewayMerchantRoute; |
mulberry-mail/mulberry4-client | Linux/Sources/Application/Rules/Dialog/CRulesTarget.h | <reponame>mulberry-mail/mulberry4-client<filename>Linux/Sources/Application/Rules/Dialog/CRulesTarget.h
/*
Copyright (c) 2007 <NAME>. 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.
*/
// Header for CRulesTarget class
#ifndef __CRULESTARGET__MULBERRY__
#define __CRULESTARGET__MULBERRY__
#include "CCriteriaBase.h"
#include "CFilterTarget.h"
#include "HPopupMenu.h"
// Constants
// Classes
class JXTextButton;
class CMailboxPopupButton;
class CTextInputField;
class CTargetsDialog;
class CRulesTarget : public CCriteriaBase
{
public:
CRulesTarget(JXContainer* enclosure,
const HSizingOption hSizing, const VSizingOption vSizing,
const JCoordinate x, const JCoordinate y,
const JCoordinate w, const JCoordinate h);
virtual ~CRulesTarget();
virtual void OnCreate(CTargetsDialog* dlog);
CFilterTarget* GetFilterTarget() const;
void SetFilterTarget(const CFilterTarget* spec);
protected:
virtual CCriteriaBaseList& GetList();
virtual void SwitchWith(CCriteriaBase* other);
private:
// begin JXLayout1
JXMultiImageButton* mUp;
JXMultiImageButton* mDown;
HPopupMenu* mPopup1;
HPopupMenu* mPopup2;
HPopupMenu* mPopup3;
CTextInputField* mText;
CMailboxPopupButton* mMailboxPopup;
// end JXLayout1
CTargetsDialog* mDlog;
virtual void Receive(JBroadcaster* sender, const Message& message);
void InitCabinetMenu(); // Set up cabinet menu
void InitAccountMenu(); // Set up account menu
void OnSetTarget(JIndex nID);
void OnMailboxPopup(JIndex nID);
};
#endif
|
anticipasean/girakkafunc | func-futurestream/src/test/java/cyclops/async/reactive/futurestream/reactivestreams/TckSynchronousPublisherTest.java | package cyclops.async.reactive.futurestream.reactivestreams;
import cyclops.async.reactive.futurestream.LazyReact;
import cyclops.reactive.companion.ThreadPools;
import org.reactivestreams.Publisher;
import org.reactivestreams.tck.PublisherVerification;
import org.reactivestreams.tck.TestEnvironment;
import org.testng.annotations.Test;
@Test
public class TckSynchronousPublisherTest extends PublisherVerification<Long> {
public TckSynchronousPublisherTest() {
super(new TestEnvironment(300L));
}
@Override
public Publisher<Long> createPublisher(long elements) {
return new LazyReact(ThreadPools.getCommonFreeThread()).iterate(0l,
i -> i + 1l)
.sync()
.limit(elements);
}
@Override
public Publisher<Long> createFailedPublisher() {
return null; //not possible to forEachAsync to failed Stream
}
}
|
cedinu/tsduck | src/utest/utestFatal.cpp | //----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2005-2021, <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
//----------------------------------------------------------------------------
//
// TSUnit test suite for tsFatal.h
//
// Since the purpose of this test is to crash the application, we don't do
// it blindly! The crash is effective only if the environment variable
// UTEST_FATAL_CRASH_ALLOWED is defined.
//
//----------------------------------------------------------------------------
#include "tsFatal.h"
#include "tsSysUtils.h"
#include "tsunit.h"
//----------------------------------------------------------------------------
// The test fixture
//----------------------------------------------------------------------------
class FatalTest: public tsunit::Test
{
public:
virtual void beforeTest() override;
virtual void afterTest() override;
void testWithoutCrash();
void testCrash();
TSUNIT_TEST_BEGIN(FatalTest);
TSUNIT_TEST(testWithoutCrash);
TSUNIT_TEST(testCrash);
TSUNIT_TEST_END();
};
TSUNIT_REGISTER(FatalTest);
//----------------------------------------------------------------------------
// Initialization.
//----------------------------------------------------------------------------
// Test suite initialization method.
void FatalTest::beforeTest()
{
}
// Test suite cleanup method.
void FatalTest::afterTest()
{
}
//----------------------------------------------------------------------------
// Unitary tests.
//----------------------------------------------------------------------------
void FatalTest::testWithoutCrash()
{
int i = 0;
// Shall not crash with a non_null address.
ts::CheckNonNull(&i);
}
void FatalTest::testCrash()
{
if (ts::EnvironmentExists(u"UTEST_FATAL_CRASH_ALLOWED")) {
std::cerr << "FatalTest: CheckNonNull(0) : should fail !" << std::endl
<< "Unset UTEST_FATAL_CRASH_ALLOWED to skip the crash test" << std::endl;
ts::CheckNonNull(nullptr);
TSUNIT_FAIL("Should not get there, should have crashed");
}
else {
debug() << "FatalTest: crash test skipped, define UTEST_FATAL_CRASH_ALLOWED to force it" << std::endl;
}
}
|
BrotherSharper/fxmaster | rollup.config.js | <gh_stars>0
import copy from "@guanghechen/rollup-plugin-copy";
import sourcemaps from "rollup-plugin-sourcemaps";
import styles from "rollup-plugin-styles";
import { terser } from "rollup-plugin-terser";
import { distDirectory, name, sourceDirectory } from "./tools/const.mjs";
const staticFiles = ["assets", "lang", "libs", "packs", "templates", "module.json"];
const isProduction = process.env.NODE_ENV === "production";
/**
* @type {import('rollup').RollupOptions}
*/
const config = {
input: { [`module/${name}`]: `${sourceDirectory}/module/${name}.js` },
output: {
dir: distDirectory,
format: "es",
sourcemap: true,
assetFileNames: "[name].[ext]",
},
plugins: [
sourcemaps(),
styles({
mode: ["extract", `css/${name}.css`],
url: false,
sourceMap: true,
minimize: isProduction,
}),
copy({
targets: [{ src: staticFiles.map((file) => `${sourceDirectory}/${file}`), dest: distDirectory }],
}),
isProduction && terser({ ecma: 2020, keep_fnames: true }),
],
};
export default config;
|
jufeng98/b2c-master | maven-parent/b2c-cloud-test-learn-java/src/main/java/com/javamaster/b2c/cloud/test/learn/java/test/EmojiTest.java | package com.javamaster.b2c.cloud.test.learn.java.test;
import com.vdurmont.emoji.EmojiParser;
import org.junit.Test;
/**
* @author yudong
* @date 2019/5/9
*/
public class EmojiTest {
@Test
public void test(){
String str = "An 😀awesome 😃string with a few 😉emojis!";
String result = EmojiParser.parseToAliases(str);
System.out.println(result);
System.out.println(EmojiParser.parseToHtmlHexadecimal(str));
System.out.println(EmojiParser.removeAllEmojis(str));
}
}
|
marcomoesman/Qora | src/main/java/qora/web/ServletUtils.java | <reponame>marcomoesman/Qora
package qora.web;
import javax.servlet.http.HttpServletRequest;
public class ServletUtils {
public static boolean isRemoteRequest(HttpServletRequest servletRequestOpt)
{
if(servletRequestOpt != null)
{
String ipAdress = getRemoteAddress(servletRequestOpt);
if (!ipAdress.equals("127.0.0.1")) {
return true;
}
}
return false;
}
public static String getRemoteAddress(
HttpServletRequest servletRequest) {
String ipAdress = servletRequest.getHeader("X-FORWARDED-FOR");
if (ipAdress == null) {
ipAdress = servletRequest.getRemoteAddr();
}
return ipAdress;
}
}
|
iht/fpinscala | src/test/scala/chap05/ex01Spec.scala | <gh_stars>1-10
/*
* Copyright (c) 2014-2019 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// ---------------------
// Test for example 5.01
// ---------------------
package chap05
import org.specs2.mutable._
import adt._
object Ex01Spec extends Specification {
"The toList function" should {
"return Nil with Empty stream" in {
Empty.toList mustEqual Nil
}
"return a list of Ints" in {
Stream(1,2,3,5).toList mustEqual List(1,2,3,5)
}
"return a list of Double" in {
Stream(1.2,2.3,3.5).toList mustEqual List(1.2,2.3,3.5)
}
"return a list of Options" in {
Stream(None,Some(1),None,Some(2),None,Some(3)).toList mustEqual List(None,Some(1),None,Some(2),None,Some(3))
}
}
}
|
anasamo92/sagess-core | search/index.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.actionBuilder = exports.builtInStore = undefined;
var _builtInStore = require('./built-in-store');
var _builtInStore2 = _interopRequireDefault(_builtInStore);
var _actionBuilder = require('./action-builder');
var _actionBuilder2 = _interopRequireDefault(_actionBuilder);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.builtInStore = _builtInStore2.default;
exports.actionBuilder = _actionBuilder2.default;
exports.default = {
builtInStore: _builtInStore2.default,
actionBuilder: _actionBuilder2.default
};
//# sourceMappingURL=data:application/json;charset=utf-8;base64,<KEY> |
xiaolanchong/call_to_power2 | ctp2_code/libs/anet/demo/chat/chat.c | /*
Copyright (C) 1995-2001 Activision, Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*-------------------------------------------------------------------------
Chat Program started using dp session from a freeze file.
-------------------------------------------------------------------------*/
#include <stdio.h>
#include <crtdbg.h>
#include <direct.h>
#include "anet.h"
#include "dppack1.h"
#include "raw.h"
#include "eclock.h"
#define CHAT_PACKET_ID dppt_MAKE('C', 'H')
#define MAX_MESSAGE 200
dpid_t my_id = dp_ID_NONE;
int quitState = 0; /* set to 1 to start quit sequence */
/* Any program that gets compressed by pecomp must import these two function,
* but doesn't need really to call them.
* If you use the /MDd option with visual C, it won't for some reason
* import them by default, so you have to explicitly.
* Must export this to avoid dead code elimination.
*/
DP_API void foo()
{
LoadLibrary(NULL);
GetProcAddress(NULL, NULL);
}
/*-------------------------------------------------------------------------
Call to quit chat.
-------------------------------------------------------------------------*/
static void quit(dp_t *myDP, int exit_code)
{
if (myDP) {
dpDestroy(myDP, 0); /* go ahead and hang up */
}
raw_end();
printf("chat: Exiting with status %d.\n", exit_code);
if (exit_code) {
printf("Press any key to continue\n");
getch();
}
exit(exit_code);
}
/*-------------------------------------------------------------------------
Call to send chat message.
-------------------------------------------------------------------------*/
dp_result_t chat_broadcast(dp_t *myDP, char *message)
{
struct {
dp_packetType_t type;
char buf[MAX_MESSAGE];
char skip[6];
} pkt;
dp_result_t err;
pkt.type = CHAT_PACKET_ID;
strcpy(pkt.buf, message);
err = dpSend(myDP, my_id, dp_ID_BROADCAST, dp_SEND_RELIABLE, &pkt, sizeof(pkt) - sizeof(pkt.skip));
return err;
}
/*-------------------------------------------------------------------------
Show command line usage
------------------------------------------------------------------------*/
void usage()
{
printf("\
Usage: chat(d) [filename]\n\
Starts chat session according to parameters in given file\n\
created by anetdrop (default: freeze.dat)\n");
exit(1);
}
/*--------------------------------------------------------------------------
Convert a object delta status to human readable form.
--------------------------------------------------------------------------*/
static const char *status2a(dp_result_t status)
{
switch (status) {
case dp_RES_CREATED:
return "created";
case dp_RES_CHANGED:
return "changed";
case dp_RES_DELETED:
return "deleted";
default:
printf("chat: bad status\n");
quit(NULL, 1);
}
}
/*-------------------------------------------------------------------------
cd to the directory of the executable. Web browsers start
helper apps in a random directory, which makes the helper app very unhappy
if it expected to find its own data files in the current working
directory. Call this function at the beginning of a helper app to fix
this.
Returns 0 on error
1 on success
-------------------------------------------------------------------------*/
static int cdToAppDir(void)
{
char dir[MAX_PATH];
char *chop;
if (!GetModuleFileName(NULL, dir, sizeof(dir)))
return 0;
chop = strrchr(dir, '\\');
if (chop)
*chop = 0;
else
return 0;
return (SetCurrentDirectory(dir));
}
/*--------------------------------------------------------------------------
The standard argv under Windows was computed without regard to quotes.
In order to support filenames with spaces, ignore the standard argv,
and compute one that obeys double quotes.
--------------------------------------------------------------------------*/
static int getargv(char argv[][MAX_PATH], int maxargc)
{
char *p, *q;
int argc;
p = GetCommandLine();
printf("Command line:%s\n", p);
for (argc = 0; (argc < maxargc) && *p; argc++) {
// Skip to beginning of next argument
while (*p && isspace(*p))
p++;
if (!*p)
break;
// Copy next argument; handle quoted string correctly
if (*p == '"') {
p++; // skip quote
for (q=argv[argc]; *p && (*p != '"'); )
*q++ = *p++;
*q = 0;
p++; // skip quote
} else {
for (q=argv[argc]; *p && !isspace(*p); )
*q++ = *p++;
*q = 0;
}
}
return argc;
}
#define MAX_ARGS 2
/*-------------------------------------------------------------------------
Initialize session and run main chat loop
------------------------------------------------------------------------*/
int chat(int sysargc, char **sysargv)
{
char argv[MAX_ARGS][MAX_PATH];
int argc;
int exitCode = 0;
dp_t *myDP;
dp_result_t err = dp_RES_OK;
char freezefile[100];
char kbuf[MAX_MESSAGE] = "";
char masterHostName[64];
int keylen;
char key[dp_MAX_ADR_LEN + 3];
dp_session_t sess;
char cwdbuf[MAX_PATH];
argc = getargv(argv, MAX_ARGS);
raw_init();
if (argc == 1)
strcpy(freezefile, "freeze.dat");
else if ((argc == 2) && (argv[1][0] != '-'))
strcpy(freezefile, argv[1]);
else
usage();
printf("cwd is %s\n", getcwd(cwdbuf, MAX_PATH));
cdToAppDir();
printf("cwd is %s\n", getcwd(cwdbuf, MAX_PATH));
err = dpCreate(&myDP, NULL, NULL, freezefile);
if (err != dp_RES_OK) {
printf("chat: error %d thawing %s.\n", err, freezefile);
quit(myDP, 1);
}
#if 0
keylen = 1;
key[0] = dp_KEY_PLAYER_LATENCIES;
err = dpRequestObjectDeltas(myDP, TRUE, key, keylen);
if (err != dp_RES_OK) {
printf("error %d requesting latency deltas\n", err);
quit(myDP, 1);
}
#endif
keylen = 1;
key[0] = dp_KEY_SESSIONS;
err = dpRequestObjectDeltas(myDP, TRUE, key, keylen);
if (err != dp_RES_OK) {
printf("error %d requesting session deltas\n", err);
quit(myDP, 1);
}
err = dpGetSessionDesc(myDP, &sess, NULL);
if (err != dp_RES_OK) {
printf("error %d getting current session\n", err);
quit(myDP, 1);
}
err = dpGetSessionId(myDP, &sess, &key[1], &keylen);
if (err != dp_RES_OK) {
printf("error %d getting current session ID\n", err);
quit(myDP, 1);
}
key[0] = dp_KEY_PLAYERS;
keylen++;
err = dpRequestObjectDeltas(myDP, TRUE, key, keylen);
if (err != dp_RES_OK) {
printf("error %d requesting player deltas\n", err);
quit(myDP, 1);
}
printf("You're in session %s", sess.sessionName);
#if 0
{
char key[dp_KEY_MAXLEN];
int keylen;
int i;
printf(" (id=");
dpGetSessionId(myDP, &sess, key, &keylen);
for (i = 0; i < keylen; i++) {
printf("%x.", key[i] & 0xFF);
}
printf(")");
}
#endif
if (dpGetGameServerEx(myDP, masterHostName, sizeof(masterHostName), NULL) ==dp_RES_OK) {
printf(", on server %s", masterHostName);
}
printf("\n");
printf("To leave this session, press ^D.\n");
printf("To force a divide-by-zero crash, press ^X.\n");
while(1) { /* input and receive loop */
dpid_t idFrom;
dpid_t idTo;
struct {
dp_packetType_t type PACK;
union {
dp_objectDelta_packet_t delta;
unsigned char buf[dpio_MAXLEN_UNRELIABLE];
} u PACK;
} pkt;
size_t pktsize;
if (quitState == 1) {
/* Shutdown and quit out of chat */
err = dpShutdown(myDP, 3000, 3000, 0);
if (dp_RES_OK == err) {
return 0;
}
}
if (raw_kbhit()) {
int len = strlen(kbuf);
int ch = 0;
if (len >= MAX_MESSAGE) {
printf("\nchat: Message too long. Truncating and sending.\n");
err = chat_broadcast(myDP, kbuf);
if (err != dp_RES_OK) {
printf("chat: error %d sending message.\n", err);
}
kbuf[0] = '\0';
continue;
}
ch = raw_getc();
if (ch == -1) {
/* guess kbhit was wrong */
continue;
}
if (ch == 4) { /* ^D */
printf("\nquitting ....\n");
quitState = 1;
if (ch == 17) {
exitCode = 1; /* if stub exists, tell it to die */
}
continue;
}
if (ch == 24) { /* ^X - force divide-by-zero crash */
int i, j;
j = 10;
i = (int)strchr("a", 'b'); /* result is zero, but compiler doesn't know that */
j /= i;
printf("Result of division by zero is %d\n", j);
}
putchar(ch);
fflush(stdout);
if (ch == '\r') { /* ^M */
putchar('\n');
}
if (ch == 8) { /* BSp */
if (len > 0)
kbuf[len-1] = 0;
continue;
}
if (ch != '\r' && ch != '\n') {
/* Append to buffer. */
kbuf[len++] = ch;
kbuf[len] = 0;
continue;
}
/* Process the keyboard buffer. */
if (!kbuf[0])
continue;
err = chat_broadcast(myDP, kbuf);
if (err != dp_RES_OK) {
printf("chat: error %d sending message.\n", err);
}
/* Empty it. */
kbuf[0] = 0;
}
/* Receive and process packets */
pktsize = sizeof(pkt);
err = dpReceive(myDP, &idFrom, &idTo, 0, &pkt, &pktsize);
assert(_CrtCheckMemory());
switch (err) {
case dp_RES_MODEM_NORESPONSE:
printf("chat: modem reports NO CARRIER!\n");
continue;
case dp_RES_HOST_NOT_RESPONDING:
printf("chat: connection to game server lost!\n");
continue;
case dp_RES_EMPTY:
continue;
case dp_RES_OK:
break;
default :
printf("chat: error %d receiving packet.\n", err);
continue;
}
switch (pkt.type) {
case dp_OBJECTDELTA_PACKET_ID:
if (pkt.u.delta.key[0] == dp_KEY_PLAYERS) {
dp_objectDelta_packet_t *delta = &pkt.u.delta;
const char *op;
op = status2a(delta->status);
if (dp_OBJECTDELTA_FLAG_LOCAL & delta->flags) {
char *msg = "";
if (dp_OBJECTDELTA_FLAG_ISHOST & delta->flags)
msg = " -- and you're the host";
printf("***: Player id:%d %s %s -- and it's you%s!\n",
delta->data.p.id, delta->data.p.name, op, msg);
my_id = delta->data.p.id;
} else {
printf("***: Player id:%d %s %s: latency:%dms, loss:%d%%, flags:%lx\n",
delta->data.p.id, delta->data.p.name, op,
delta->latency, delta->pktloss, delta->flags);
}
} else if (pkt.u.delta.key[0] == dp_KEY_SESSIONS) {
dp_objectDelta_packet_t *delta = &pkt.u.delta;
const char *op;
op = status2a(delta->status);
printf("session %s (sessType %d, k%d u%x f%x, cur %d, max %d) %s\n",
delta->data.sess.sessionName, delta->data.sess.sessionType,
delta->data.sess.karma, delta->data.sess.dwUser1,
delta->data.sess.flags,
delta->data.sess.currentPlayers,
delta->data.sess.maxPlayers, op);
}
break;
case dp_USER_HOST_PACKET_ID:
printf("chat: Host is dead. You are now host.\n");
break;
case CHAT_PACKET_ID:
{
char nameBuf[256];
char chatBuf[dpio_MAXLEN_UNRELIABLE]; /* overkill */
size_t chatLen;
err = dpGetPlayerName(myDP, idFrom, nameBuf, sizeof(nameBuf));
if (err != dp_RES_OK) {
printf("chat: chat packet from unknown id %d.\n", idFrom);
}
chatLen = pktsize-sizeof(dp_packetType_t);
assert(chatLen < sizeof(chatBuf));
memcpy(chatBuf, pkt.u.buf, chatLen);
chatBuf[chatLen] = 0; /* Nul terminate */
DPRINT(("%s: %s\n", nameBuf, chatBuf));
printf("%s: %s\n", nameBuf, chatBuf);
break;
}
case dp_SESSIONLOST_PACKET_ID:
printf("Sorry session lost, you might as well quit\n");
break;
default:
break;
}
}
quit(myDP, exitCode);
return 1;
}
static LONG __cdecl Debug_ExceptionFilter(LPEXCEPTION_POINTERS ep)
{
dpReportCrash(ep);
if (ep->ExceptionRecord->ExceptionCode == aeh_ASSERTION_CODE)
return EXCEPTION_CONTINUE_EXECUTION;
return (EXCEPTION_CONTINUE_SEARCH);
}
int _cdecl main( int argc, char *argv[] )
{
int retVal = 0;
__try {
retVal = chat(argc, argv);
} __except(Debug_ExceptionFilter(GetExceptionInformation())) {
;
}
return retVal; /* to make compiler happy */
}
|
fruitxiang/smartapp-openapi-java | src/test/java/com/baidu/mapp/tp/api/impl/FeedServiceImplTest.java | <reponame>fruitxiang/smartapp-openapi-java
package com.baidu.mapp.tp.api.impl;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.baidu.mapp.common.SmartAppPageB;
import com.baidu.mapp.tp.bean.feed.AccessResource;
import com.baidu.mapp.util.SmartAppHttpUtil;
@RunWith(PowerMockRunner.class)
@PrepareForTest(SmartAppHttpUtil.class)
public class FeedServiceImplTest {
@InjectMocks
FeedServiceImpl feedServiceImpl;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testAccessResourceSubmit() throws Exception {
String response = "{\n"
+ " \"errno\": 0,\n"
+ " \"msg\": \"success\",\n"
+ " \"data\": \"ok\"\n"
+ "}";
// mock 包含静态方法的类
PowerMockito.mockStatic(SmartAppHttpUtil.class);
PowerMockito.when(SmartAppHttpUtil.sendHttpPost(anyString(), any())).thenReturn(response);
String string = new String("ok");
String result = feedServiceImpl
.accessResourceSubmit("accessToken", "title", "body", "path", "images", 1L,
1L, "feedType", "feedSubType", "tags", "ext");
Assert.assertNotNull(result);
Assert.assertEquals(string, result);
}
@Test
public void testAccessResourceQuery() throws Exception {
String response = "{\n"
+ " \"errno\": 0,\n"
+ " \"msg\": \"success\",\n"
+ " \"data\": {\n"
+ " \"page\": 1,\n"
+ " \"pageSize\": 5,\n"
+ " \"count\": 9,\n"
+ " \"list\": [\n"
+ " {\n"
+ " \"rid\": \"11902716467688469563\",\n"
+ " \"app_id\": 17182748,\n"
+ " \"title\": \"1009-内容-问答-1009\",\n"
+ " \"create_time\": \"1569244816\",\n"
+ " \"status\": \"审核中\",\n"
+ " \"audit_time\": \"1569244816\",\n"
+ " \"source\": \"Api提交\"\n"
+ " },\n"
+ " {\n"
+ " \"rid\": \"10521637653310175733\",\n"
+ " \"app_id\": 17182748,\n"
+ " \"title\": \"1007-内容-本地生活图文-1007\",\n"
+ " \"create_time\": \"1569244764\",\n"
+ " \"status\": \"审核中\",\n"
+ " \"audit_time\": \"1569244764\",\n"
+ " \"source\": \"Api提交\"\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ "}\n";
// mock 包含静态方法的类
PowerMockito.mockStatic(SmartAppHttpUtil.class);
PowerMockito.when(SmartAppHttpUtil.sendHttpGet(anyString(), any())).thenReturn(response);
AccessResource accessResource = new AccessResource();
accessResource.setRid("11902716467688469563");
accessResource.setAppId(17182748L);
accessResource.setTitle("1009-内容-问答-1009");
accessResource.setCreateTime("1569244816");
accessResource.setStatus("审核中");
accessResource.setAuditTime("1569244816");
accessResource.setSource("Api提交");
AccessResource accessResource1 = new AccessResource();
accessResource1.setRid("10521637653310175733");
accessResource1.setAppId(17182748L);
accessResource1.setTitle("1007-内容-本地生活图文-1007");
accessResource1.setCreateTime("1569244764");
accessResource1.setStatus("审核中");
accessResource1.setAuditTime("1569244764");
accessResource1.setSource("Api提交");
List<AccessResource> accessResources = new ArrayList<>();
accessResources.add(accessResource);
accessResources.add(accessResource1);
SmartAppPageB<AccessResource> accessResourceSmartAppPageB = new SmartAppPageB<>();
accessResourceSmartAppPageB.setPage(1L);
accessResourceSmartAppPageB.setPageSize(5);
accessResourceSmartAppPageB.setCount(9L);
accessResourceSmartAppPageB.setList(accessResources);
SmartAppPageB<AccessResource> result = feedServiceImpl
.accessResourceQuery("accessToken", "title", 0, 1L,
1L, 0, 0, 0);
Assert.assertNotNull(result);
Assert.assertEquals(accessResourceSmartAppPageB, result);
}
@Test
public void testDeleteResource() throws Exception {
String response = "{\n"
+ " \"errno\": 0,\n"
+ " \"msg\": \"success\"\n"
+ "}\n";
// mock 包含静态方法的类
PowerMockito.mockStatic(SmartAppHttpUtil.class);
PowerMockito.when(SmartAppHttpUtil.sendHttpPost(anyString(), any())).thenReturn(response);
Object result = feedServiceImpl.deleteResource("accessToken", 0L, "path");
Assert.assertNull(result);
}
@Test
public void testSubmitSitemap() throws Exception {
String response = "{\n"
+ "\t\"errno\": 0,\n"
+ "\t\"msg\": \"success\"\n"
+ "}";
// mock 包含静态方法的类
PowerMockito.mockStatic(SmartAppHttpUtil.class);
PowerMockito.when(SmartAppHttpUtil.sendHttpPost(anyString(), any())).thenReturn(response);
Boolean result = feedServiceImpl
.submitSitemap("accessToken", 0L, "desc", 0L, 0L, "url");
Assert.assertNull(result);
}
@Test
public void testDeleteSitemap() throws Exception {
String response = "{\n"
+ "\t\"errno\": 0,\n"
+ "\t\"msg\": \"success\"\n"
+ "}";
// mock 包含静态方法的类
PowerMockito.mockStatic(SmartAppHttpUtil.class);
PowerMockito.when(SmartAppHttpUtil.sendHttpPost(anyString(), any())).thenReturn(response);
Object result = feedServiceImpl.deleteSitemap("accessToken", anyLong(), anyString());
Assert.assertNull(result);
}
}
|
dram/metasfresh | backend/de.metas.adempiere.adempiere/base/src/main/java-gen/org/compiere/model/I_M_Attribute.java | <reponame>dram/metasfresh<gh_stars>1000+
package org.compiere.model;
import java.math.BigDecimal;
import javax.annotation.Nullable;
import org.adempiere.model.ModelColumn;
/** Generated Interface for M_Attribute
* @author metasfresh (generated)
*/
@SuppressWarnings("unused")
public interface I_M_Attribute
{
String Table_Name = "M_Attribute";
// /** AD_Table_ID=562 */
// int Table_ID = org.compiere.model.MTable.getTable_ID(Table_Name);
/**
* Get Client.
* Client/Tenant for this installation.
*
* <br>Type: TableDir
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getAD_Client_ID();
String COLUMNNAME_AD_Client_ID = "AD_Client_ID";
/**
* Set Java Class.
*
* <br>Type: Table
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setAD_JavaClass_ID (int AD_JavaClass_ID);
/**
* Get Java Class.
*
* <br>Type: Table
* <br>Mandatory: false
* <br>Virtual Column: false
*/
int getAD_JavaClass_ID();
ModelColumn<I_M_Attribute, Object> COLUMN_AD_JavaClass_ID = new ModelColumn<>(I_M_Attribute.class, "AD_JavaClass_ID", null);
String COLUMNNAME_AD_JavaClass_ID = "AD_JavaClass_ID";
/**
* Set Organisation.
* Organisational entity within client
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setAD_Org_ID (int AD_Org_ID);
/**
* Get Organisation.
* Organisational entity within client
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getAD_Org_ID();
String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
/**
* Set Dynamische Validierung.
* Regel für die dynamische Validierung
*
* <br>Type: TableDir
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setAD_Val_Rule_ID (int AD_Val_Rule_ID);
/**
* Get Dynamische Validierung.
* Regel für die dynamische Validierung
*
* <br>Type: TableDir
* <br>Mandatory: false
* <br>Virtual Column: false
*/
int getAD_Val_Rule_ID();
@Nullable org.compiere.model.I_AD_Val_Rule getAD_Val_Rule();
void setAD_Val_Rule(@Nullable org.compiere.model.I_AD_Val_Rule AD_Val_Rule);
ModelColumn<I_M_Attribute, org.compiere.model.I_AD_Val_Rule> COLUMN_AD_Val_Rule_ID = new ModelColumn<>(I_M_Attribute.class, "AD_Val_Rule_ID", org.compiere.model.I_AD_Val_Rule.class);
String COLUMNNAME_AD_Val_Rule_ID = "AD_Val_Rule_ID";
/**
* Set Attribute Value Type.
* Type of Attribute Value
*
* <br>Type: List
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setAttributeValueType (java.lang.String AttributeValueType);
/**
* Get Attribute Value Type.
* Type of Attribute Value
*
* <br>Type: List
* <br>Mandatory: true
* <br>Virtual Column: false
*/
java.lang.String getAttributeValueType();
ModelColumn<I_M_Attribute, Object> COLUMN_AttributeValueType = new ModelColumn<>(I_M_Attribute.class, "AttributeValueType", null);
String COLUMNNAME_AttributeValueType = "AttributeValueType";
/**
* Get Created.
* Date this record was created
*
* <br>Type: DateTime
* <br>Mandatory: true
* <br>Virtual Column: false
*/
java.sql.Timestamp getCreated();
ModelColumn<I_M_Attribute, Object> COLUMN_Created = new ModelColumn<>(I_M_Attribute.class, "Created", null);
String COLUMNNAME_Created = "Created";
/**
* Get Created By.
* User who created this records
*
* <br>Type: Table
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getCreatedBy();
String COLUMNNAME_CreatedBy = "CreatedBy";
/**
* Set UOM.
* Unit of Measure
*
* <br>Type: TableDir
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setC_UOM_ID (int C_UOM_ID);
/**
* Get UOM.
* Unit of Measure
*
* <br>Type: TableDir
* <br>Mandatory: false
* <br>Virtual Column: false
*/
int getC_UOM_ID();
String COLUMNNAME_C_UOM_ID = "C_UOM_ID";
/**
* Set Description.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setDescription (@Nullable java.lang.String Description);
/**
* Get Description.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
@Nullable java.lang.String getDescription();
ModelColumn<I_M_Attribute, Object> COLUMN_Description = new ModelColumn<>(I_M_Attribute.class, "Description", null);
String COLUMNNAME_Description = "Description";
/**
* Set Description Pattern.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setDescriptionPattern (@Nullable java.lang.String DescriptionPattern);
/**
* Get Description Pattern.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
@Nullable java.lang.String getDescriptionPattern();
ModelColumn<I_M_Attribute, Object> COLUMN_DescriptionPattern = new ModelColumn<>(I_M_Attribute.class, "DescriptionPattern", null);
String COLUMNNAME_DescriptionPattern = "DescriptionPattern";
/**
* Set Active.
* The record is active in the system
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setIsActive (boolean IsActive);
/**
* Get Active.
* The record is active in the system
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
boolean isActive();
ModelColumn<I_M_Attribute, Object> COLUMN_IsActive = new ModelColumn<>(I_M_Attribute.class, "IsActive", null);
String COLUMNNAME_IsActive = "IsActive";
/**
* Set Always Updateable.
* The column is always updateable, even if the record is not active or processed
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setIsAlwaysUpdateable (boolean IsAlwaysUpdateable);
/**
* Get Always Updateable.
* The column is always updateable, even if the record is not active or processed
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
boolean isAlwaysUpdateable();
ModelColumn<I_M_Attribute, Object> COLUMN_IsAlwaysUpdateable = new ModelColumn<>(I_M_Attribute.class, "IsAlwaysUpdateable", null);
String COLUMNNAME_IsAlwaysUpdateable = "IsAlwaysUpdateable";
/**
* Set Auf Belegen auszuweisen.
* Wenn ein Attribute auf Belegen auszuweisen ist, bedeutet das, das Lieferposionen mit unterschiedlichen Attributwerten nicht zu einer Rechnungszeile zusammengefasst werden können.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setIsAttrDocumentRelevant (boolean IsAttrDocumentRelevant);
/**
* Get Auf Belegen auszuweisen.
* Wenn ein Attribute auf Belegen auszuweisen ist, bedeutet das, das Lieferposionen mit unterschiedlichen Attributwerten nicht zu einer Rechnungszeile zusammengefasst werden können.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
boolean isAttrDocumentRelevant();
ModelColumn<I_M_Attribute, Object> COLUMN_IsAttrDocumentRelevant = new ModelColumn<>(I_M_Attribute.class, "IsAttrDocumentRelevant", null);
String COLUMNNAME_IsAttrDocumentRelevant = "IsAttrDocumentRelevant";
/**
* Set High Volume.
* Use Search instead of Pick list
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setIsHighVolume (boolean IsHighVolume);
/**
* Get High Volume.
* Use Search instead of Pick list
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
boolean isHighVolume();
ModelColumn<I_M_Attribute, Object> COLUMN_IsHighVolume = new ModelColumn<>(I_M_Attribute.class, "IsHighVolume", null);
String COLUMNNAME_IsHighVolume = "IsHighVolume";
/**
* Set Instanz-Attribut.
* The product attribute is specific to the instance (like Serial No, Lot or Guarantee Date)
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setIsInstanceAttribute (boolean IsInstanceAttribute);
/**
* Get Instanz-Attribut.
* The product attribute is specific to the instance (like Serial No, Lot or Guarantee Date)
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
boolean isInstanceAttribute();
ModelColumn<I_M_Attribute, Object> COLUMN_IsInstanceAttribute = new ModelColumn<>(I_M_Attribute.class, "IsInstanceAttribute", null);
String COLUMNNAME_IsInstanceAttribute = "IsInstanceAttribute";
/**
* Set Pflichtangabe.
* Data entry is required in this column
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setIsMandatory (boolean IsMandatory);
/**
* Get Pflichtangabe.
* Data entry is required in this column
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
boolean isMandatory();
ModelColumn<I_M_Attribute, Object> COLUMN_IsMandatory = new ModelColumn<>(I_M_Attribute.class, "IsMandatory", null);
String COLUMNNAME_IsMandatory = "IsMandatory";
/**
* Set isPricingRelevant.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setIsPricingRelevant (boolean IsPricingRelevant);
/**
* Get isPricingRelevant.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
boolean isPricingRelevant();
ModelColumn<I_M_Attribute, Object> COLUMN_IsPricingRelevant = new ModelColumn<>(I_M_Attribute.class, "IsPricingRelevant", null);
String COLUMNNAME_IsPricingRelevant = "IsPricingRelevant";
/**
* Set Read Only.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setIsReadOnlyValues (boolean IsReadOnlyValues);
/**
* Get Read Only.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
boolean isReadOnlyValues();
ModelColumn<I_M_Attribute, Object> COLUMN_IsReadOnlyValues = new ModelColumn<>(I_M_Attribute.class, "IsReadOnlyValues", null);
String COLUMNNAME_IsReadOnlyValues = "IsReadOnlyValues";
/**
* Set Ist HU-Bestandsrelevant.
* Is used to do attibute matching between storage attributes and order line attributes (ASIs).
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setIsStorageRelevant (boolean IsStorageRelevant);
/**
* Get Ist HU-Bestandsrelevant.
* Is used to do attibute matching between storage attributes and order line attributes (ASIs).
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
boolean isStorageRelevant();
ModelColumn<I_M_Attribute, Object> COLUMN_IsStorageRelevant = new ModelColumn<>(I_M_Attribute.class, "IsStorageRelevant", null);
String COLUMNNAME_IsStorageRelevant = "IsStorageRelevant";
/**
* Set Merkmal.
* Product Attribute
*
* <br>Type: ID
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setM_Attribute_ID (int M_Attribute_ID);
/**
* Get Merkmal.
* Product Attribute
*
* <br>Type: ID
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getM_Attribute_ID();
ModelColumn<I_M_Attribute, Object> COLUMN_M_Attribute_ID = new ModelColumn<>(I_M_Attribute.class, "M_Attribute_ID", null);
String COLUMNNAME_M_Attribute_ID = "M_Attribute_ID";
/**
* Set Merkmal-Suche.
* Common Search Attribute
*
* <br>Type: TableDir
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setM_AttributeSearch_ID (int M_AttributeSearch_ID);
/**
* Get Merkmal-Suche.
* Common Search Attribute
*
* <br>Type: TableDir
* <br>Mandatory: false
* <br>Virtual Column: false
*/
int getM_AttributeSearch_ID();
@Nullable org.compiere.model.I_M_AttributeSearch getM_AttributeSearch();
void setM_AttributeSearch(@Nullable org.compiere.model.I_M_AttributeSearch M_AttributeSearch);
ModelColumn<I_M_Attribute, org.compiere.model.I_M_AttributeSearch> COLUMN_M_AttributeSearch_ID = new ModelColumn<>(I_M_Attribute.class, "M_AttributeSearch_ID", org.compiere.model.I_M_AttributeSearch.class);
String COLUMNNAME_M_AttributeSearch_ID = "M_AttributeSearch_ID";
/**
* Set Name.
*
* <br>Type: String
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setName (java.lang.String Name);
/**
* Get Name.
*
* <br>Type: String
* <br>Mandatory: true
* <br>Virtual Column: false
*/
java.lang.String getName();
ModelColumn<I_M_Attribute, Object> COLUMN_Name = new ModelColumn<>(I_M_Attribute.class, "Name", null);
String COLUMNNAME_Name = "Name";
/**
* Get Updated.de
* Date this record was updated
*
* <br>Type: DateTime
* <br>Mandatory: true
* <br>Virtual Column: false
*/
java.sql.Timestamp getUpdated();
ModelColumn<I_M_Attribute, Object> COLUMN_Updated = new ModelColumn<>(I_M_Attribute.class, "Updated", null);
String COLUMNNAME_Updated = "Updated";
/**
* Get Updated By.
* User who updated this records
*
* <br>Type: Table
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getUpdatedBy();
String COLUMNNAME_UpdatedBy = "UpdatedBy";
/**
* Set Search Key.
* Search key for the record in the format required - must be unique
*
* <br>Type: String
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setValue (java.lang.String Value);
/**
* Get Search Key.
* Search key for the record in the format required - must be unique
*
* <br>Type: String
* <br>Mandatory: true
* <br>Virtual Column: false
*/
java.lang.String getValue();
ModelColumn<I_M_Attribute, Object> COLUMN_Value = new ModelColumn<>(I_M_Attribute.class, "Value", null);
String COLUMNNAME_Value = "Value";
/**
* Set Max. Wert.
* Maximum Value for a field
*
* <br>Type: Amount
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setValueMax (@Nullable BigDecimal ValueMax);
/**
* Get Max. Wert.
* Maximum Value for a field
*
* <br>Type: Amount
* <br>Mandatory: false
* <br>Virtual Column: false
*/
BigDecimal getValueMax();
ModelColumn<I_M_Attribute, Object> COLUMN_ValueMax = new ModelColumn<>(I_M_Attribute.class, "ValueMax", null);
String COLUMNNAME_ValueMax = "ValueMax";
/**
* Set Min. Wert.
* Minimum Value for a field
*
* <br>Type: Amount
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setValueMin (@Nullable BigDecimal ValueMin);
/**
* Get Min. Wert.
* Minimum Value for a field
*
* <br>Type: Amount
* <br>Mandatory: false
* <br>Virtual Column: false
*/
BigDecimal getValueMin();
ModelColumn<I_M_Attribute, Object> COLUMN_ValueMin = new ModelColumn<>(I_M_Attribute.class, "ValueMin", null);
String COLUMNNAME_ValueMin = "ValueMin";
}
|
AnneLivia/URI-Online | Data Structures/Hash Table/Hash Table (Implemented With Struct)/hashTable.cpp | #include "hashTable.h"
// Creating a hash table
Hash* createHashTable(int tableSize) {
// allocating memory for the hash table
Hash *hashTable = (Hash*) malloc(sizeof(Worker));
// if it succeeded, then:
if(hashTable != nullptr) {
// assign the number of elements to 0, since there's no element yet
hashTable->numberOfElements = 0;
// assign the size of the table as tableSize
hashTable->tableSize = tableSize;
// Allocate memory of the array and assign to its position the null value
hashTable->w = (Worker **)malloc(sizeof(Worker *) * tableSize);
// if it succeeded
if(hashTable->w != nullptr) {
// assign to all elements, value null
for (int i = 0; i < tableSize; i++) {
hashTable->w[i] = nullptr;
}
} else {
// doesn't succeeded, so free table and assign to it null
free(hashTable);
hashTable = nullptr;
}
}
// Return the hash table
return hashTable;
}
// Destruct the hash table: run through all the array and verify if exists an element to be deallocate.
void freeHashTable(Hash *hashTable) {
// If hashTable exits
if(hashTable != nullptr) {
for (int i = 0; i < hashTable->tableSize; i++) {
// If the data at the position i is different of null, it means
// that there's a value assign to it
if(hashTable->w[i] != nullptr) {
// deallocate it
free(hashTable->w[i]);
}
}
// deallocate the hashTable w
free(hashTable->w);
// deallocate the hashTable itself
free(hashTable);
// assign it to null to avoid dangling pointer
hashTable = nullptr;
}
}
// converting a string value to a key
int stringValue(string str) {
int value = 7; // to initialize the sum
for (int i = 0; i < (int)str.size(); i++) {
// using the value 31 which some studies says that it is a good number to multiply
value = 31 * value + (int)str[i];
}
return value;
}
/*
Calculating key position:
For insertion and search, it's necessary to calculate the position of the data
in the hash bucket;
Calculating the position of the key:
Data
A --------| |-> [B]
B --------|==:> Keys Position |-> [ ]
----------------> Hashing Function ---->>> |-> [A]
C --------|==:> |-> [C]
D --------| |-> [D]
Hashing function:
- Allow to calculate one position from a key chosen from the data
- it's extremely important for the good performance of the table
- It's responsible for distribute the information in a equilibrated way
through the hash table
A hashing function must follow the following conditions:
- Be simple and cheap to calculate
- Guarantee that different values produces different positions (avoid collisions)
- Generate a equilibrate distribution of data in the table, i.e. each position of the table
has the same chance to receive a key (maximum distribution)
- is deterministic. h(k)should always return the same value for a given k
Important:
The implementation of the hashing function depends upon the prior knowledge of the nature and
domain of the key to be used to.
Same problem as the prime number 5 be used for multiples of 5. Although is good to choose a prime
number, in this case that won't be good.
Some methods to be used in a hashing function:
Division method
Multiplication method
*/
/*
Division method:
- The division method is one way to create hash functions.
It consist in calculate the remainder of the integer value that
represents the element by the size of the table.
- It's simple and straightforward
The functions take the form:
h(k) = k mod m;
*/
int keyUsingDivisionMethod(int key, int tableSize) {
/*
0x7FFFFFFF = 01111111111111111111111111111111 = 2147483647
the maximum number a simple int can have.
we do the & operation of the key with it to avoid the risk of getting
an overflow and get a negative number.
*/
return (key & 0x7FFFFFFF) % tableSize;
}
/*
The multiplication method is another way to create hash functions.
The functions take the form:
h(k) = [m (kA mod 1)]
Where for A: 0 < A < 1. This is used to multiply the value of the key that
represents the element. following, the fractional part is multiplied by the size
of the table to calculate the position of the element.
Example, suppose we want to calculate the position of the key 123456
the fractional constant A is 0.618
the size of the table is 1024
Steps we follow are:
Multiply the A with the key
result = 123456 * 0.618 = 76295.808
Now we take the fractional part of the result
result = 76295.808 - (int) 76295.808, which is 76295
result is 0.808
now we multiply the size of the table by the result
position = (int)result(0.808) * tableSize(1024) = (827.392)
position is 827
*/
int keyUsingMultiplicationMethod(int key, int tableSize) {
float A = 0.6180339887; // constant A where: 0 < A < 1
// multiply by A
float fractionalPart = key * A;
// the fractional part is taken
fractionalPart = fractionalPart - (int)fractionalPart;
// then return the size of the table multiplied by the resulting number
return (int) (tableSize * fractionalPart);
}
/* insertion without collision treatment
- Calculate the position of the keys in the array
- allocate space for the data
- store the data in the position calculated
*/
int insert_WithoutCollision(Hash *hashTable, Worker w) {
// first verify if the hashTable exists and it's not full
if(hashTable == nullptr || hashTable->tableSize == hashTable->numberOfElements)
return 0;
// using the id of the worker to get the position to store in the table
int position = keyUsingDivisionMethod(w.id, hashTable->tableSize);
// it could be the a string using the string function
// int position = stringValue(w.name);
// allocating the memory location for the data
Worker* newWorker = new Worker();
// Allocation not succeeded
if(newWorker == nullptr)
return 0;
// I'm getting an error here
*newWorker = w;
// assign the newWorker to the calculated position
hashTable->w[position] = newWorker;
// increment the number of elements
hashTable->numberOfElements++;
// return 1 so that everything got right
return 1;
}
int search_WithoutCollision(Hash *hashTable, int id, Worker& w) {
// if hashTable is not empty and exist
if(hashTable != nullptr && hashTable->numberOfElements != 0) {
// calculate position
int position = keyUsingDivisionMethod(id, hashTable->tableSize);
// verify if there's a data at the position
if(hashTable->w[position] != nullptr) {
// return value
w = *(hashTable->w[position]);
} else {
return 0;
}
} else {
return 0;
}
// not error
return 1;
}
/*
Ways to avoid collision:
We can use a universal Hashing which is a strategy to minimize the collisions in a hash table.
universal hashing (in a randomized algorithm or data structure) refers to selecting a hash function
at random from a family of hash functions with a certain mathematical property.
We choose in run time randomly a hash function to be used.
To do this, we can construct a set of hash functions.
There are a lot of ways to create a family, one example could be:
Choose a prime number p such that the value in any key K to be inserted in the table
is less than p and greater or equal to 0.
p is greater than the table size
Choose randomly 2 integer numbers, A and B.
- 0 < a <= p
- 0 <= b <= p
We are use random numbers generated at the beginning of the application, so that
the hash function is not deterministic
h(k) _ {a,} = ((aK + b) % p) % TABLE_SIZE
Depending on the size of the table and the values inserted, we can classify a hash function as:
Imperfect:
For two different keys, the output of the function can be the same position
the collision of keys in the table is not extremely bad, it just something undesirable
because it decrease the performance of the system
Many hashTables uses other data structures to handle collisions
Perfect:
Guarantee that there won't be collisions of key inside the table, that is, different keys
are going to produce different positions in the table.
in the worst case the insertion and search is O(1)
This hashing is utilized when collision is not tolerate
It's refereed to a very specific type of application such as a set of reserved words from
a programming language.
In this case, we have prior knowledge of what the data that is.
The creation of a hash table consists of two things:
creating of a hashing function
an approach to handle collisions
Collision are in theory inevitable
The some ways to handle collisions:
- Open addressing or rehash:
In case of a collision, it run thorough the table in search of an
empty position.
Avoid using linked list
Some Advantages:
The search is done in the table itself, which increases performance
Some disadvantages:
Insertion is O(N) when all elements are in collision
- Separate Chaining
It doesn't search for empty position
Store in each position of the table the start of a dynamic linked list
the collisions are store inside those linked list
Advantages:
Words case of insertion is O(1) if the list is not ordered
Disadvantages:
The search is done by traversing the list.
memory complexity is big: pointers of lists are stored.
........
*/
/*
Opening Address:
There are three most used strategies:
Linear probing:
Try to spread the elements in a sequential way from the calculated
position.
Steps:
The first element I is inserted in the position obtained by the hash function:
second element (collision) is inserted at the position pos+1
third element (collision) is inserted at the position pos+2
When the table gets full, the time complexity increases
Quadratic Probing:
try to spread the elements utilizing a second degree equation
pos + (c1 * i) + (c2 * i^2)
where pos is the position obtained by the hashing function
i is the current try
c1 and c2 are the coefficients of the equation
Steps:
First element is inserted at the pos return by the hashing function
second element (collision) is inserted at pos + (c1 * 1) + (c2 * i^2)
third element (collision) is inserted at pos + (c1 * 2) + (c2 * i^2)
...
All the keys that produces the same initial position in the table also produces
the same position in the quadratic probing.
double hashing:
try to spread the element utilizing two hashing functions
H1 + i + h2
where:
h1 is used to calculate initial position
h2 is used to calculate dislocations according to the initial position in case
of a collision
we only use the second function if it occurred a collision
steps:
first element i = 0, is placed in the position obtained by the h1
second element in case of collision is placed at the position h1 + 1 + h2
third element in case of a collision is place at the position h1 + 2 + h2
....
it's necessary two different hashing functions and the second one cannot return 0 function
a tip is to use the size of the table a little bit small and add up
....
*/
int linearProbing(int pos, int i, int tableSize) {
// 0x7FFFFFFF to avoid overflow
return ((pos + i) & 0x7FFFFFFF) % tableSize;
}
int quadraticProbing(int pos, int i, int tableSize) {
// 0x7FFFFFFF to avoid overflow
// applying the equation formula using random coefficients
pos = pos + 2 * i + 5 * i * i;
return ((pos + i) & 0x7FFFFFFF) % tableSize;
}
int doubleHashing(int h1, int key, int i, int tableSize) {
// 0x7FFFFFFF to avoid overflow
// h1 was obtained by another hashing function
int h2 = keyUsingDivisionMethod(key, tableSize - 1) + 1;
return ((h1 + i * h2) & 0x7FFFFFFF) % tableSize;
}
int insert_OpenningAddressing(Hash *hashTable, Worker w) {
// Verify if hashTable exists and if it's not empty
if(hashTable == nullptr || hashTable->numberOfElements == 0)
return 0;
int key = w.id; // id is the key here
int position, newPosision;
// getting the position
position = keyUsingDivisionMethod(key, hashTable->tableSize);
// checking if there's collision
for (int i = 0; i < hashTable->tableSize; i++) {
// using linear probing strategy
newPosision = linearProbing(position, i, hashTable->tableSize);
// if it's an empty place, insert it there
if(hashTable->w[newPosision] == nullptr) {
Worker *newW = new Worker();
// any memory was allocated
if(newW == nullptr)
return 0;
// assign data to it
*newW = w;
// increment number of items
hashTable->numberOfElements++;
// insert element in the newPos of the table
hashTable->w[newPosision] = newW;
return 1; // success
}
}
// error
return 0;
}
int search_OpenningAddressing(Hash *hashTable, int id, Worker& w) {
// calculate position of the key in the array
// verify if there's data in the position and if the data is combined with the key
// recalculate position while data are different from the key
// return data
// checking if hash exist
if(hashTable == nullptr || hashTable->numberOfElements == 0)
return 0;
int position = keyUsingDivisionMethod(id, hashTable->tableSize);
for (int i = 0; i < hashTable->tableSize; i++) {
int newPosition = linearProbing(position, i, hashTable->tableSize);
// element does not exist here
if(hashTable->w[newPosition] == nullptr)
return 0;
if(hashTable->w[newPosition]->id == id) {
w = *(hashTable->w[newPosition]);
return 1; // element exist
}
}
return 0; // element does not exist
}
// Function to show all the data in the table
void showData(Hash *hashTable) {
for (int i = 0; i < hashTable->tableSize; i++) {
if(hashTable->w[i] != nullptr) {
cout << "Worker " << i << ":\n";
cout << "Name: " << hashTable->w[i]->name << endl;
cout << "Job: " << hashTable->w[i]->job << endl;
cout << "Company: " << hashTable->w[i]->company << endl;
cout << "Age: " << hashTable->w[i]->age << endl;
cout << "Id: " << hashTable->w[i]->id << endl;
cout << "Salary: " << hashTable->w[i]->salary << endl << endl;
}
}
}
|
akac0297/PETLAB | MRI segmentation/Register-b50-to-b50.py | #!/usr/bin/env python
# coding: utf-8
import pathlib
import numpy as np
import SimpleITK as sitk
import matplotlib.pyplot as plt
from platipy.imaging import ImageVisualiser
from platipy.imaging.label.utils import get_com
from platipy.imaging.registration.linear import linear_registration
from platipy.imaging.registration.deformable import fast_symmetric_forces_demons_registration
from platipy.imaging.registration.utils import apply_transform
template_b50 = sitk.ReadImage("/home/alicja/PET_LAB_PROCESSED/WES_010/IMAGES/WES_010_TIMEPOINT_1_MRI_DWI_B50.nii.gz")
new_b50=sitk.ReadImage("/home/alicja/PET_LAB_PROCESSED/WES_007/IMAGES/WES_007_TIMEPOINT_1_MRI_DWI_B50.nii.gz")
template_b50_to_new_rigid, tfm_template_to_new = linear_registration(
new_b50,
template_b50,
shrink_factors= [10,5],
smooth_sigmas= [2,1],
sampling_rate= 1,
final_interp= 2,
metric= 'mean_squares',
optimiser= 'gradient_descent_line_search',
reg_method='rigid',
default_value=0
)
vis = ImageVisualiser(new_b50, cut=get_com(new_b50), figure_size_in=5)
vis.add_comparison_overlay(template_b50_to_new_rigid)
fig = vis.show()
fig.savefig(f"/home/alicja/PET_LAB_PROCESSED/template_b50_to_new_b50_rigid.jpeg",dpi=400)
sitk.WriteImage(template_b50_to_new_rigid,"/home/alicja/PET_LAB_PROCESSED/test_rigid_reg_template_b50_to_new.nii.gz")
img_affine, tfm_img_affine,_=fast_symmetric_forces_demons_registration(
new_b50,
template_b50_to_new_rigid,
resolution_staging=[4,2],
iteration_staging=[3,3])
vis = ImageVisualiser(new_b50, cut=get_com(new_b50), figure_size_in=5)
vis.add_comparison_overlay(img_affine)
fig = vis.show()
fig.savefig(f"/home/alicja/PET_LAB_PROCESSED/template_b50_to_new_b50_affine.jpeg",dpi=400)
sitk.WriteImage(img_affine,"/home/alicja/PET_LAB_PROCESSED/test_affine_reg_template_b50_to_new.nii.gz") |
zhangkn/iOS14Header | System/Library/PrivateFrameworks/StoreKitUI.framework/SKUIInteractiveSegmentedControl.h | <filename>System/Library/PrivateFrameworks/StoreKitUI.framework/SKUIInteractiveSegmentedControl.h
/*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:44:34 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/StoreKitUI.framework/StoreKitUI
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <StoreKitUI/StoreKitUI-Structs.h>
#import <UIKitCore/UIControl.h>
@class NSMutableArray, NSArray;
@interface SKUIInteractiveSegmentedControl : UIControl {
NSMutableArray* _dividerViews;
/*^block*/id _dividerCreationBlock;
double _dividerWidth;
NSArray* _segments;
double _selectionProgress;
}
@property (nonatomic,copy) id dividerCreationBlock; //@synthesize dividerCreationBlock=_dividerCreationBlock - In the implementation block
@property (assign,nonatomic) double dividerWidth; //@synthesize dividerWidth=_dividerWidth - In the implementation block
@property (nonatomic,copy) NSArray * segments; //@synthesize segments=_segments - In the implementation block
@property (assign,nonatomic) double selectionProgress; //@synthesize selectionProgress=_selectionProgress - In the implementation block
-(id)initWithFrame:(CGRect)arg1 ;
-(void)dealloc;
-(void)layoutSubviews;
-(CGSize)sizeThatFits:(CGSize)arg1 ;
-(id)hitTest:(CGPoint)arg1 withEvent:(id)arg2 ;
-(void)setSegments:(NSArray *)arg1 ;
-(NSArray *)segments;
-(double)dividerWidth;
-(void)setDividerWidth:(double)arg1 ;
-(void)setSelectionProgress:(double)arg1 ;
-(void)setDividerCreationBlock:(id)arg1 ;
-(double)selectionProgress;
-(void)_unregisterForObservationOfSegment:(id)arg1 ;
-(id)_createDividerViewWithFrame:(CGRect)arg1 ;
-(long long)selectedSegmentIndexForSelectionProgress:(double)arg1 ;
-(double)relativeSelectionProgressForSelectionProgress:(double)arg1 segmentIndex:(long long)arg2 ;
-(void)_registerForObservationOfSegment:(id)arg1 ;
-(double)selectionProgressForRelativeSectionProgress:(double)arg1 segmentIndex:(long long)arg2 ;
-(BOOL)_setSelectionProgress:(double)arg1 ;
-(void)_applySelectionProgressToSegments;
-(void)_notifyClientsOfSelectionProgressChange;
-(double)selectionProgressForSelectedSegmentAtIndex:(long long)arg1 ;
-(void)_segmentControlTouchUpInsideAction:(id)arg1 ;
-(id)dividerCreationBlock;
@end
|
tomasdavidorg/kie-cloud-tests | test-cloud/test-cloud-optaweb/src/test/java/org/kie/cloud/optaweb/testprovider/OptawebEmployeeRosteringTestProvider.java | <reponame>tomasdavidorg/kie-cloud-tests
/*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.kie.cloud.optaweb.testprovider;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.Set;
import org.assertj.core.api.Assertions;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.kie.cloud.optaweb.rest.OptaWebObjectMapperResolver;
import org.optaweb.employeerostering.restclient.ServiceClientFactory;
import org.optaweb.employeerostering.shared.employee.Employee;
import org.optaweb.employeerostering.shared.employee.EmployeeAvailabilityState;
import org.optaweb.employeerostering.shared.employee.EmployeeRestService;
import org.optaweb.employeerostering.shared.employee.view.EmployeeAvailabilityView;
import org.optaweb.employeerostering.shared.roster.RosterRestService;
import org.optaweb.employeerostering.shared.roster.RosterState;
import org.optaweb.employeerostering.shared.roster.view.ShiftRosterView;
import org.optaweb.employeerostering.shared.shift.ShiftRestService;
import org.optaweb.employeerostering.shared.shift.view.ShiftView;
import org.optaweb.employeerostering.shared.skill.Skill;
import org.optaweb.employeerostering.shared.skill.SkillRestService;
import org.optaweb.employeerostering.shared.spot.Spot;
import org.optaweb.employeerostering.shared.spot.SpotRestService;
import org.optaweb.employeerostering.shared.tenant.Tenant;
import org.optaweb.employeerostering.shared.tenant.TenantRestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OptawebEmployeeRosteringTestProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(OptawebEmployeeRosteringTestProvider.class);
private static final int ROSTER_YEAR = 2019;
private static final int ROSTER_MONTH = 1;
private static final int ROSTER_START_DAY = 2;
private Integer tenantId;
private TenantRestService tenantRestService;
private SkillRestService skillRestService;
private EmployeeRestService employeeRestService;
private SpotRestService spotRestService;
private ShiftRestService shiftRestService;
private RosterRestService rosterRestService;
public OptawebEmployeeRosteringTestProvider(URL baseUrl) {
LOGGER.info("Connecting to " + baseUrl.toExternalForm());
ResteasyClient resteasyClient = new ResteasyClientBuilder().register(OptaWebObjectMapperResolver.class).build();
ServiceClientFactory serviceClientFactory = new ServiceClientFactory(baseUrl, resteasyClient);
tenantRestService = serviceClientFactory.createTenantRestServiceClient();
skillRestService = serviceClientFactory.createSkillRestServiceClient();
employeeRestService = serviceClientFactory.createEmployeeRestServiceClient();
spotRestService = serviceClientFactory.createSpotRestServiceClient();
shiftRestService = serviceClientFactory.createShiftRestServiceClient();
rosterRestService = serviceClientFactory.createRosterRestServiceClient();
}
public void fromSkillToRoster() {
createTenant();
Skill ambulatoryCare = newSkill("Ambulatory care");
Skill criticalCare = newSkill("Critical care");
Spot neurology = newSpot("Neurology", ambulatoryCare);
Spot emergency = newSpot("Emergency", criticalCare);
Employee francis = newEmployee("<NAME>", ambulatoryCare, criticalCare);
Employee ivy = newEmployee("<NAME>", ambulatoryCare);
employeeUnavailability(francis, ROSTER_START_DAY, 8, 16);
newShift(neurology, ROSTER_START_DAY, 10, 18);
newShift(emergency, ROSTER_START_DAY + 1, 8, 16);
rosterRestService.solveRoster(tenantId);
sleep(500);
rosterRestService.terminateRosterEarly(tenantId);
LocalDate startDate = LocalDate.of(ROSTER_YEAR, ROSTER_MONTH, ROSTER_START_DAY);
LocalDate endDate = startDate.plusDays(1);
ShiftRosterView shiftRosterView =
rosterRestService.getShiftRosterView(tenantId, 0, 10, startDate.toString(), endDate.toString());
Assertions.assertThat(shiftRosterView).isNotNull();
Assertions.assertThat(shiftRosterView.getEmployeeList()).containsExactlyInAnyOrder(francis, ivy);
Assertions.assertThat(shiftRosterView.getSpotList()).containsExactlyInAnyOrder(neurology, emergency);
Assertions.assertThat(shiftRosterView.getSpotIdToShiftViewListMap().get(neurology.getId()))
.isNotEmpty()
.extracting(ShiftView::getEmployeeId).containsOnly(ivy.getId());
}
private void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
LOGGER.warn("Interrupted sleep.", e);
}
}
private void createTenant() {
LocalDate firstDraft = LocalDate.of(ROSTER_YEAR, ROSTER_MONTH, ROSTER_START_DAY);
LocalDate historical = firstDraft.minusWeeks(1);
RosterState rosterState = new RosterState(null, 7, firstDraft, 7, 24, 0, 7, historical, ZoneOffset.UTC);
rosterState.setTenant(new Tenant("Test Tenant"));
Tenant tenant = tenantRestService.addTenant(rosterState);
if (tenant == null) {
throw new IllegalArgumentException("Cannot create tenant.");
}
tenantId = tenant.getId();
}
private void deleteTenant() {
if (tenantId != null) {
tenantRestService.removeTenant(tenantId);
}
}
private Skill newSkill(String skillName) {
return skillRestService.addSkill(tenantId, new Skill(tenantId, skillName));
}
private Spot newSpot(String spotName, Skill... requiredSkills) {
return spotRestService.addSpot(tenantId, new Spot(tenantId, spotName, newSkillSet(requiredSkills)));
}
private Employee newEmployee(String name, Skill... skills) {
Employee employee = new Employee(tenantId, name);
employee.setSkillProficiencySet(newSkillSet(skills));
return employeeRestService.addEmployee(tenantId, employee);
}
private Set<Skill> newSkillSet(Skill... skills) {
Set<Skill> skillSet = new HashSet<>();
for (Skill skill : skills) {
skillSet.add(skill);
}
return skillSet;
}
private ShiftView newShift(Spot spot, int day, int startHour, int endHour) {
ShiftView shiftView = new ShiftView(tenantId, spot, newDateTime(day, startHour), newDateTime(day, endHour));
return shiftRestService.addShift(tenantId, shiftView);
}
private EmployeeAvailabilityView employeeUnavailability(Employee employee, int day, int startHour, int endHour) {
EmployeeAvailabilityView employeeAvailability = new EmployeeAvailabilityView(
tenantId,
employee,
newDateTime(day, startHour),
newDateTime(day, endHour),
EmployeeAvailabilityState.UNAVAILABLE
);
return employeeRestService.addEmployeeAvailability(tenantId, employeeAvailability);
}
private LocalDateTime newDateTime(int dayOfMonth, int hour) {
return LocalDateTime.of(ROSTER_YEAR, ROSTER_MONTH, dayOfMonth, hour, 0);
}
/**
* For debugging purpose - replace the URL according to your deployment.
*/
public static void main(String[] args) throws MalformedURLException {
String url = "http://localhost:8080/";
URL appUrl = new URL(url);
OptawebEmployeeRosteringTestProvider testProvider = new OptawebEmployeeRosteringTestProvider(appUrl);
try {
testProvider.fromSkillToRoster();
} finally {
testProvider.deleteTenant();
}
}
}
|
cl9200/cockroach | multiraft/storage_test.go | <reponame>cl9200/cockroach
// Copyright 2014 Square, Inc
// Author: <NAME> (bdarnell@)
package multiraft
import (
"sync"
"github.com/cockroachdb/cockroach/roachpb"
"github.com/coreos/etcd/raft/raftpb"
)
// BlockableStorage is an implementation of Storage that can be blocked for testing
// to simulate slow storage devices.
type BlockableStorage struct {
storage Storage
mu sync.Mutex
}
// Assert implementation of the storage interface.
var _ Storage = &BlockableStorage{}
// wait until the storage is unblocked.
func (b *BlockableStorage) wait() {
b.mu.Lock()
defer b.mu.Unlock()
}
// Block causes all operations on this storage to block until Unblock is called.
func (b *BlockableStorage) Block() {
b.mu.Lock()
}
// Unblock undoes the effect of Block() and allows blocked operations to proceed.
func (b *BlockableStorage) Unblock() {
b.mu.Unlock()
}
func (b *BlockableStorage) GroupStorage(g roachpb.RangeID, r roachpb.ReplicaID) (WriteableGroupStorage, error) {
gs, err := b.storage.GroupStorage(g, r)
return &blockableGroupStorage{b, gs}, err
}
func (b *BlockableStorage) ReplicaDescriptor(groupID roachpb.RangeID, replicaID roachpb.ReplicaID) (roachpb.ReplicaDescriptor, error) {
return b.storage.ReplicaDescriptor(groupID, replicaID)
}
func (b *BlockableStorage) ReplicaIDForStore(groupID roachpb.RangeID, storeID roachpb.StoreID) (roachpb.ReplicaID, error) {
return b.storage.ReplicaIDForStore(groupID, storeID)
}
func (b *BlockableStorage) ReplicasFromSnapshot(snap raftpb.Snapshot) ([]roachpb.ReplicaDescriptor, error) {
return b.storage.ReplicasFromSnapshot(snap)
}
func (b *BlockableStorage) CanApplySnapshot(groupID roachpb.RangeID, snap raftpb.Snapshot) bool {
return b.storage.CanApplySnapshot(groupID, snap)
}
func (b *BlockableStorage) AppliedIndex(groupID roachpb.RangeID) (uint64, error) {
return b.storage.AppliedIndex(groupID)
}
func (b *BlockableStorage) RaftLocker() sync.Locker {
return b.storage.RaftLocker()
}
type blockableGroupStorage struct {
b *BlockableStorage
s WriteableGroupStorage
}
func (b *blockableGroupStorage) Append(entries []raftpb.Entry) error {
b.b.wait()
return b.s.Append(entries)
}
func (b *blockableGroupStorage) ApplySnapshot(snap raftpb.Snapshot) error {
b.b.wait()
return b.s.ApplySnapshot(snap)
}
func (b *blockableGroupStorage) SetHardState(st raftpb.HardState) error {
b.b.wait()
return b.s.SetHardState(st)
}
func (b *blockableGroupStorage) InitialState() (raftpb.HardState, raftpb.ConfState, error) {
b.b.wait()
return b.s.InitialState()
}
func (b *blockableGroupStorage) Entries(lo, hi, maxBytes uint64) ([]raftpb.Entry, error) {
b.b.wait()
return b.s.Entries(lo, hi, maxBytes)
}
func (b *blockableGroupStorage) Term(i uint64) (uint64, error) {
b.b.wait()
return b.s.Term(i)
}
func (b *blockableGroupStorage) LastIndex() (uint64, error) {
b.b.wait()
return b.s.LastIndex()
}
func (b *blockableGroupStorage) FirstIndex() (uint64, error) {
b.b.wait()
return b.s.FirstIndex()
}
func (b *blockableGroupStorage) Snapshot() (raftpb.Snapshot, error) {
b.b.wait()
return b.s.Snapshot()
}
|
polarisdev87/TravelFeed | pages/dashboard/newsletter.js | <reponame>polarisdev87/TravelFeed<filename>pages/dashboard/newsletter.js
import PropTypes from 'prop-types';
import React from 'react';
import DashboardPage from '../../components/Dashboard/DashboardPage';
import Newsletter from '../../components/Dashboard/Newsletter';
const NewsletterPage = props => {
const { open } = props;
return (
<DashboardPage open={open} label="newsletter" content={<Newsletter />} />
);
};
NewsletterPage.getInitialProps = props => {
const { open } = props.query;
return { open };
};
NewsletterPage.propTypes = {
open: PropTypes.string,
};
export default NewsletterPage;
|
jawaidm/ledger | ledgergw/apps.py | <filename>ledgergw/apps.py
from __future__ import unicode_literals
from django.apps import AppConfig
class MarinastayConfig(AppConfig):
name = 'ledgergw'
|
soulbird/apisix-seed | test/e2e/tools/regcenter/nacos.go | package regcenter
import (
"e2e/tools/common"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
type Nacos struct {
}
func NewNacos() *Nacos {
return &Nacos{}
}
type servicesResp struct {
Count int `json:"count"`
Doms []string `json:"doms"`
}
func (n *Nacos) Online(node *common.Node) error {
//curl -X POST 'http://127.0.0.1:8848/nacos/v1/ns/instance?serviceName=APISIX-NACOS&ip=127.0.0.1&port=10000'
url := common.NACOS_HOST + "/nacos/v1/ns/instance?healthy=true&" +
"serviceName=" + node.ServiceName + "&" +
"ip=" + common.DOCKER_GATEWAY + "&" +
"port=" + node.Port
req, err := http.NewRequest("POST", url, nil)
if err != nil {
return err
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.New("register instance failed: " + node.String())
}
fmt.Println("register instance to Nacos: ", node.String())
return nil
}
func (n *Nacos) Offline(node *common.Node) error {
url := common.NACOS_HOST + "/nacos/v1/ns/instance?" +
"serviceName=" + node.ServiceName + "&" +
"ip=" + common.DOCKER_GATEWAY + "&" +
"port=" + node.Port
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
return err
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.New("delete instance failed: " + node.String())
}
fmt.Println("offline instance to Nacos: ", node.String())
return nil
}
func (n *Nacos) getServices() ([]string, error) {
// curl -X GET '127.0.0.1:8848/nacos/v1/ns/service/list?pageNo=1&pageSize=2'
// we just get 10 services, it's enough
url := common.NACOS_HOST + "/nacos/v1/ns/service/list?pageNo=1&pageSize=10"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
client := &http.Client{}
resp, err := client.Do(req)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
servResp := &servicesResp{}
err = json.Unmarshal(body, servResp)
if err != nil {
return nil, err
}
if servResp.Count > len(servResp.Doms) {
}
return servResp.Doms, nil
}
func (n *Nacos) deleteService(service string) error {
// curl -X DELETE '127.0.0.1:8848/nacos/v1/ns/service?serviceName=APISIX-NACOS'
url := common.NACOS_HOST + "/nacos/v1/ns/service?serviceName=" + service
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
return err
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.New("delete service failed, serviceName=:" + service)
}
fmt.Println("delete service, serviceName=" + service)
return nil
}
func (n *Nacos) Clean() error {
fmt.Println("clean all service form nacos...")
services, err := n.getServices()
if err != nil {
panic(err)
}
for _, srv := range services {
err = n.deleteService(srv)
if err != nil {
return err
}
}
return nil
}
|
izenecloud/izenelib | include/am/trie/alphabet_cjk.hpp | /**
@file alphabet_cjk.hpp
@author <NAME>
@date 2009.11.25
*/
#ifndef ALPHABET_CJK_H
#define ALPHABET_CJK_H
#include <types.h>
NS_IZENELIB_AM_BEGIN
const unsigned int cjk_size = 41040;
extern unsigned short cjk[cjk_size];
NS_IZENELIB_AM_END
#endif
|
huangfeng19820712/hfast | core/js/utils/AlgorithmUtils.js | /**
* @author: * @date: 2018/1/2
*/
define(["core/js/Class"], function ( Class) {
var AlgorithmUtils = Class.extend({
/**
* 快速排序
* @param array
* @returns {*}
*/
quickSort:function(array){
function sort(prev, numsize){
var nonius = prev;
var j = numsize -1;
var flag = array[prev];
if ((numsize - prev) > 1) {
while(nonius < j){
for(; nonius < j; j--){
if (array[j] < flag) {
array[nonius++] = array[j]; //a[i] = a[j]; i += 1;
break;
};
}
for( ; nonius < j; nonius++){
if (array[nonius] > flag){
array[j--] = array[nonius];
break;
}
}
}
array[nonius] = flag;
sort(0, nonius);
sort(nonius + 1, numsize);
}
}
sort(0, array.length);
return array;
}
});
AlgorithmUtils.getInstance = function () {
return new ViewUtils();
}
return AlgorithmUtils.getInstance();
});
|
salathegroup/crowdbreaks | app/javascript/custom/forms.js | // JS snippets to be used across forms
// File input (Show filename on file select)
function onChooseFile() {
let inputs = Array.from(document.querySelectorAll('.input-file'));
inputs.forEach((input) => {
let uploadButton = input.parentNode.parentNode.previousSibling.previousSibling.querySelector('div')
let filename = ''
input.addEventListener('change', (e) => {
filename = e.target.value.split('\\').pop()
uploadButton.querySelector('span').innerHTML = filename
})
})
}
$(document).on('turbolinks:load', () => {
onChooseFile();
});
|
pellizzetti/pulumi-gcp | sdk/go/gcp/iap/appEngineVersionIamPolicy.go | <gh_stars>1-10
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package iap
import (
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/go/pulumi"
)
// > This content is derived from https://github.com/terraform-providers/terraform-provider-google/blob/master/website/docs/r/iap_app_engine_version_iam_policy.html.markdown.
type AppEngineVersionIamPolicy struct {
s *pulumi.ResourceState
}
// NewAppEngineVersionIamPolicy registers a new resource with the given unique name, arguments, and options.
func NewAppEngineVersionIamPolicy(ctx *pulumi.Context,
name string, args *AppEngineVersionIamPolicyArgs, opts ...pulumi.ResourceOpt) (*AppEngineVersionIamPolicy, error) {
if args == nil || args.AppId == nil {
return nil, errors.New("missing required argument 'AppId'")
}
if args == nil || args.PolicyData == nil {
return nil, errors.New("missing required argument 'PolicyData'")
}
if args == nil || args.Service == nil {
return nil, errors.New("missing required argument 'Service'")
}
if args == nil || args.VersionId == nil {
return nil, errors.New("missing required argument 'VersionId'")
}
inputs := make(map[string]interface{})
if args == nil {
inputs["appId"] = nil
inputs["policyData"] = nil
inputs["project"] = nil
inputs["service"] = nil
inputs["versionId"] = nil
} else {
inputs["appId"] = args.AppId
inputs["policyData"] = args.PolicyData
inputs["project"] = args.Project
inputs["service"] = args.Service
inputs["versionId"] = args.VersionId
}
inputs["etag"] = nil
s, err := ctx.RegisterResource("gcp:iap/appEngineVersionIamPolicy:AppEngineVersionIamPolicy", name, true, inputs, opts...)
if err != nil {
return nil, err
}
return &AppEngineVersionIamPolicy{s: s}, nil
}
// GetAppEngineVersionIamPolicy gets an existing AppEngineVersionIamPolicy resource's state with the given name, ID, and optional
// state properties that are used to uniquely qualify the lookup (nil if not required).
func GetAppEngineVersionIamPolicy(ctx *pulumi.Context,
name string, id pulumi.ID, state *AppEngineVersionIamPolicyState, opts ...pulumi.ResourceOpt) (*AppEngineVersionIamPolicy, error) {
inputs := make(map[string]interface{})
if state != nil {
inputs["appId"] = state.AppId
inputs["etag"] = state.Etag
inputs["policyData"] = state.PolicyData
inputs["project"] = state.Project
inputs["service"] = state.Service
inputs["versionId"] = state.VersionId
}
s, err := ctx.ReadResource("gcp:iap/appEngineVersionIamPolicy:AppEngineVersionIamPolicy", name, id, inputs, opts...)
if err != nil {
return nil, err
}
return &AppEngineVersionIamPolicy{s: s}, nil
}
// URN is this resource's unique name assigned by Pulumi.
func (r *AppEngineVersionIamPolicy) URN() pulumi.URNOutput {
return r.s.URN()
}
// ID is this resource's unique identifier assigned by its provider.
func (r *AppEngineVersionIamPolicy) ID() pulumi.IDOutput {
return r.s.ID()
}
// Id of the App Engine application. Used to find the parent resource to bind the IAM policy to
func (r *AppEngineVersionIamPolicy) AppId() pulumi.StringOutput {
return (pulumi.StringOutput)(r.s.State["appId"])
}
// (Computed) The etag of the IAM policy.
func (r *AppEngineVersionIamPolicy) Etag() pulumi.StringOutput {
return (pulumi.StringOutput)(r.s.State["etag"])
}
// The policy data generated by
// a `organizations.getIAMPolicy` data source.
func (r *AppEngineVersionIamPolicy) PolicyData() pulumi.StringOutput {
return (pulumi.StringOutput)(r.s.State["policyData"])
}
// The ID of the project in which the resource belongs.
// If it is not provided, the project will be parsed from the identifier of the parent resource. If no project is provided in the parent identifier and no project is specified, the provider project is used.
func (r *AppEngineVersionIamPolicy) Project() pulumi.StringOutput {
return (pulumi.StringOutput)(r.s.State["project"])
}
// Service id of the App Engine application Used to find the parent resource to bind the IAM policy to
func (r *AppEngineVersionIamPolicy) Service() pulumi.StringOutput {
return (pulumi.StringOutput)(r.s.State["service"])
}
// Version id of the App Engine application Used to find the parent resource to bind the IAM policy to
func (r *AppEngineVersionIamPolicy) VersionId() pulumi.StringOutput {
return (pulumi.StringOutput)(r.s.State["versionId"])
}
// Input properties used for looking up and filtering AppEngineVersionIamPolicy resources.
type AppEngineVersionIamPolicyState struct {
// Id of the App Engine application. Used to find the parent resource to bind the IAM policy to
AppId interface{}
// (Computed) The etag of the IAM policy.
Etag interface{}
// The policy data generated by
// a `organizations.getIAMPolicy` data source.
PolicyData interface{}
// The ID of the project in which the resource belongs.
// If it is not provided, the project will be parsed from the identifier of the parent resource. If no project is provided in the parent identifier and no project is specified, the provider project is used.
Project interface{}
// Service id of the App Engine application Used to find the parent resource to bind the IAM policy to
Service interface{}
// Version id of the App Engine application Used to find the parent resource to bind the IAM policy to
VersionId interface{}
}
// The set of arguments for constructing a AppEngineVersionIamPolicy resource.
type AppEngineVersionIamPolicyArgs struct {
// Id of the App Engine application. Used to find the parent resource to bind the IAM policy to
AppId interface{}
// The policy data generated by
// a `organizations.getIAMPolicy` data source.
PolicyData interface{}
// The ID of the project in which the resource belongs.
// If it is not provided, the project will be parsed from the identifier of the parent resource. If no project is provided in the parent identifier and no project is specified, the provider project is used.
Project interface{}
// Service id of the App Engine application Used to find the parent resource to bind the IAM policy to
Service interface{}
// Version id of the App Engine application Used to find the parent resource to bind the IAM policy to
VersionId interface{}
}
|
depromeet/toonzip-api | src/main/java/kr/co/antoon/webtoon/application/WebtoonSnapshotService.java | <filename>src/main/java/kr/co/antoon/webtoon/application/WebtoonSnapshotService.java
package kr.co.antoon.webtoon.application;
import kr.co.antoon.webtoon.domain.WebtoonSnapshot;
import kr.co.antoon.webtoon.infrastructure.WebtoonSnapshotRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class WebtoonSnapshotService {
private final WebtoonSnapshotRepository webtoonSnapshotRepository;
@Transactional
public void saveAll(List<WebtoonSnapshot> webtoonSnapshots) {
webtoonSnapshotRepository.saveAll(webtoonSnapshots);
}
@Transactional
public void save(Double score, Long webtoonId) {
var webtoonSnapshot = new WebtoonSnapshot(score, webtoonId);
webtoonSnapshotRepository.save(webtoonSnapshot);
}
@Transactional(readOnly = true)
public Optional<WebtoonSnapshot> findTop1ByWebtoonIdOrderBySnapshotTimeDesc(Long webtoonId) {
return webtoonSnapshotRepository.findTop1ByWebtoonIdOrderBySnapshotTimeDesc(webtoonId);
}
@Transactional(readOnly = true)
public long count() {
return webtoonSnapshotRepository.count();
}
} |
rjw57/tiw-computer | emulator/src/mame/video/decodmd3.h | <filename>emulator/src/mame/video/decodmd3.h
// license:BSD-3-Clause
// copyright-holders:<NAME>
/*
* Data East Pinball DMD Type 3 Display
*/
#ifndef MAME_VIDEO_DECODMD3_H
#define MAME_VIDEO_DECODMD3_H
#pragma once
#include "cpu/m68000/m68000.h"
#include "machine/ram.h"
#include "machine/timer.h"
#include "video/mc6845.h"
#define MCFG_DECODMD_TYPE3_ADD(_tag, _region) \
MCFG_DEVICE_ADD(_tag, DECODMD3, 0) \
downcast<decodmd_type3_device &>(*device).set_gfxregion(_region);
class decodmd_type3_device : public device_t
{
public:
decodmd_type3_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock);
DECLARE_WRITE8_MEMBER(data_w);
DECLARE_READ8_MEMBER(busy_r);
DECLARE_WRITE8_MEMBER(ctrl_w);
DECLARE_READ16_MEMBER(latch_r);
DECLARE_READ16_MEMBER(status_r);
DECLARE_WRITE16_MEMBER(status_w);
DECLARE_WRITE16_MEMBER(crtc_address_w);
DECLARE_WRITE16_MEMBER(crtc_register_w);
DECLARE_READ16_MEMBER(crtc_status_r);
void set_gfxregion(const char *tag) { m_gfxtag = tag; }
void decodmd3_map(address_map &map);
protected:
virtual void device_add_mconfig(machine_config &config) override;
virtual void device_start() override;
virtual void device_reset() override;
private:
required_device<cpu_device> m_cpu;
required_device<mc6845_device> m_mc6845;
required_device<ram_device> m_ram;
required_memory_bank m_rambank;
required_memory_bank m_rombank;
memory_region* m_rom;
uint8_t m_status;
uint8_t m_crtc_index;
uint8_t m_crtc_reg[0x100];
uint8_t m_latch;
uint8_t m_ctrl;
uint8_t m_busy;
uint8_t m_command;
const char* m_gfxtag;
TIMER_DEVICE_CALLBACK_MEMBER(dmd_irq);
MC6845_UPDATE_ROW(crtc_update_row);
};
DECLARE_DEVICE_TYPE(DECODMD3, decodmd_type3_device)
#endif // MAME_VIDEO_DECODMD3_H
|
FavyTeam/Elderscape_server | source/game/content/clanchat/ClanChatHandler.java | <gh_stars>1-10
package game.content.clanchat;
import core.Server;
import core.ServerConstants;
import game.content.interfaces.InterfaceAssistant;
import game.content.miscellaneous.DiceSystem;
import game.content.miscellaneous.PlayerRank;
import game.content.miscellaneous.Teleport;
import game.item.ItemAssistant;
import game.player.Area;
import game.player.Player;
import game.player.PlayerHandler;
import game.player.punishment.DuelArenaBan;
import game.player.punishment.Mute;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import tools.discord.DiscordConstants;
import tools.discord.api.DiscordBot;
import utility.FileUtility;
import utility.Misc;
/**
* @author Sanity
*/
public class ClanChatHandler {
public ClanChatHandler() {
}
public static Clan[] clans = new Clan[100];
public static void updateFriendsList(Player player, String newPlayer, boolean added) {
if (!hasPermission(player)) {
return;
}
if (!clans[player.getClanId()].ownerName.equals(player.getPlayerName())) {
return;
}
ArrayList<String> friends = new ArrayList<String>();
for (int index = 0; index < player.friends.length; index++) {
if (player.friends[index][0] == 0) {
continue;
}
friends.add(Misc.capitalize(Misc.nameForLong(player.friends[index][0]).replaceAll("_", " ")));
}
clans[player.getClanId()].friends = friends;
clans[player.getClanId()].updated = true;
if (!clans[player.getClanId()].publicChat) {
if (added) {
player.getPA().sendMessage(Misc.capitalize(newPlayer) + " is now allowed to join this clan chat.");
} else {
player.getPA().sendMessage(Misc.capitalize(newPlayer) + " can no longer join this clan chat.");
for (int index = 0; index < clans[player.getClanId()].members.length; index++) {
if (clans[player.getClanId()].members[index] <= 0) {
continue;
}
Player loop = PlayerHandler.players[clans[player.getClanId()].members[index]];
if (loop == null) {
continue;
}
if (loop.getPlayerName().toLowerCase().equals(newPlayer.toLowerCase())) {
loop.getPA().sendMessage("You are no longer a friend of " + Misc.capitalize(player.getPlayerName()) + ".");
Server.clanChat.leaveClan(loop.getPlayerId(), loop.getClanId(), true, false, true);
}
}
}
}
}
private static void unBan(Player player, int buttonId, int clanId) {
if (!hasPermission(player)) {
return;
}
int buttonIndex = buttonId - 76159;
if (buttonIndex > clans[clanId].banned.size() - 1) {
if (buttonIndex <= player.clanChatBannedList.size() - 1) {
player.getPA().sendMessage("Another moderator has edited the ban list, please try again.");
updateBannedText(player);
}
return;
}
if (!player.clanChatBannedList.get(buttonIndex).equals(clans[clanId].banned.get(buttonIndex))) {
player.getPA().sendMessage("Another moderator has edited the ban list, please try again.");
updateBannedText(player);
return;
}
if (ClanChatHandler.inDiceCc(player, false, false)) {
if (!player.isModeratorRank()) {
return;
}
DiscordBot.sendMessageDate(DiscordConstants.STAFF_COMMANDS_LOG_CHANNEL, player.getPlayerName() + " has undice banned '" + clans[clanId].banned.get(buttonIndex) + "'");
}
clans[clanId].banned.remove(buttonIndex);
clans[clanId].updated = true;
updateBannedText(player);
}
private static void unMod(Player player, int buttonId, int clanId) {
if (!hasPermission(player)) {
return;
}
int buttonIndex = buttonId - 76140;
if (buttonIndex > clans[clanId].moderators.size() - 1) {
if (buttonIndex <= player.clanChatModeratorList.size() - 1) {
player.getPA().sendMessage("Another moderator has edited the mod list, please try again.");
updateModeratorText(player);
}
return;
}
if (!player.clanChatModeratorList.get(buttonIndex).equals(clans[clanId].moderators.get(buttonIndex))) {
player.getPA().sendMessage("Another moderator has edited the mod list, please try again.");
updateModeratorText(player);
return;
}
if (ClanChatHandler.inDiceCc(player, false, false)) {
if (!player.isModeratorRank()) {
return;
}
}
clans[clanId].moderators.remove(buttonIndex);
clans[clanId].updated = true;
updateModeratorText(player);
}
private boolean isBanned(Player player, int clanId) {
for (int index = 0; index < clans[clanId].banned.size(); index++) {
if (player.getPlayerName().equals(clans[clanId].banned.get(index))) {
return true;
}
}
return false;
}
public static void serverRestart(boolean nullClanChats) {
for (int index = 0; index < clans.length; index++) {
if (clans[index] == null) {
continue;
}
if (clans[index].updated) {
if (clans[index].indexOfClanChatsSavedData == -1) {
ClanChatStartUp item = new ClanChatStartUp(clans[index].ownerName, clans[index].clanChatTitle, clans[index].publicChat, clans[index].banned,
clans[index].moderators, true, clans[index].friends);
ClanChatStartUp.clanChats.add(item);
} else {
ClanChatStartUp.clanChats.get(clans[index].indexOfClanChatsSavedData).banned = clans[index].banned;
ClanChatStartUp.clanChats.get(clans[index].indexOfClanChatsSavedData).moderators = clans[index].moderators;
ClanChatStartUp.clanChats.get(clans[index].indexOfClanChatsSavedData).clanChatTitle = clans[index].clanChatTitle;
ClanChatStartUp.clanChats.get(clans[index].indexOfClanChatsSavedData).publicChat = clans[index].publicChat;
ClanChatStartUp.clanChats.get(clans[index].indexOfClanChatsSavedData).updated = clans[index].updated;
ClanChatStartUp.clanChats.get(clans[index].indexOfClanChatsSavedData).friends = clans[index].friends;
}
}
if (nullClanChats) {
clans[index] = null;
}
}
for (ClanChatStartUp data : ClanChatStartUp.clanChats) {
if (!data.updated) {
continue;
}
if (FileUtility.fileExists("backup/logs/clan chat/" + data.ownerName + ".txt")) {
FileUtility.deleteAllLines("backup/logs/clan chat/" + data.ownerName + ".txt");
}
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("backup/logs/clan chat/" + data.ownerName + ".txt", true));
bw.write("Title:" + data.clanChatTitle);
bw.newLine();
bw.write("Public:" + (data.publicChat ? "on" : "off"));
bw.newLine();
for (int index = 0; index < data.moderators.size(); index++) {
bw.write("Mod:" + data.moderators.get(index));
bw.newLine();
}
for (int index = 0; index < data.banned.size(); index++) {
bw.write("Ban:" + data.banned.get(index));
bw.newLine();
}
if (data.friends != null) {
for (int index = 0; index < data.friends.size(); index++) {
bw.write("Friend:" + data.friends.get(index));
bw.newLine();
}
}
bw.flush();
bw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
private void grabDataFromSavedClanChats(Player player) {
int index = 0;
for (ClanChatStartUp data : ClanChatStartUp.clanChats) {
if (data.ownerName.equals(clans[player.getClanId()].ownerName)) {
clans[player.getClanId()].indexOfClanChatsSavedData = index;
clans[player.getClanId()].clanChatTitle = data.clanChatTitle;
clans[player.getClanId()].banned = data.banned;
clans[player.getClanId()].moderators = data.moderators;
clans[player.getClanId()].publicChat = data.publicChat;
clans[player.getClanId()].friends = data.friends;
break;
}
index++;
}
}
private static boolean hasPermission(Player player) {
if (player.getClanId() == -1) {
return false;
}
if (clans[player.getClanId()] == null) {
return false;
}
if (player.getPlayerName().equals(clans[player.getClanId()].ownerName)) {
return true;
}
if (clans[player.getClanId()].ownerName.equalsIgnoreCase("dice") && player.isModeratorRank()) {
return true;
}
for (int index = 0; index < clans[player.getClanId()].moderators.size(); index++) {
if (player.getPlayerName().equals(clans[player.getClanId()].moderators.get(index))) {
return true;
}
}
return false;
}
public static void receiveChangeTitlePacket(Player player, String title) {
if (!hasPermission(player)) {
return;
}
if (title.length() > 22) {
title = title.substring(0, 22);
}
clans[player.getClanId()].updated = true;
clans[player.getClanId()].clanChatTitle = title;
updateClanChatTitle(player);
for (int index = 0; index < clans[player.getClanId()].members.length; index++) {
if (clans[player.getClanId()].members[index] <= 0) {
continue;
}
Player loop = PlayerHandler.players[clans[player.getClanId()].members[index]];
if (loop == null) {
continue;
}
if (player.getClanId() == loop.getClanId()) {
loop.getPA().sendFrame126("Talking in: " + clans[loop.getClanId()].clanChatTitle, 18140);
}
}
}
public static void receiveBanPacket(Player player, String name) {
if (name.isEmpty()) {
return;
}
name = Misc.capitalize(name);
if (name.equals(player.getPlayerName())) {
player.getPA().sendMessage("One does not simply ban himself.");
return;
}
if (!hasPermission(player)) {
return;
}
for (int index = 0; index < clans[player.getClanId()].banned.size(); index++) {
if (name.equals(clans[player.getClanId()].banned.get(index))) {
player.getPA().sendMessage(Misc.capitalize(name) + " is already banned.");
return;
}
}
if (name.equalsIgnoreCase(clans[player.getClanId()].ownerName)) {
player.getPA().sendMessage("The owner cannot be banned.");
return;
}
if (ClanChatHandler.inDiceCc(player, false, false)) {
if (!player.isModeratorRank()) {
return;
}
DiscordBot.sendMessageDate(DiscordConstants.STAFF_COMMANDS_LOG_CHANNEL, player.getPlayerName() + " has dice cc banned '" + name + "'");
}
clans[player.getClanId()].updated = true;
clans[player.getClanId()].banned.add(name);
updateBannedText(player);
for (int index = 0; index < clans[player.getClanId()].members.length; index++) {
if (clans[player.getClanId()].members[index] <= 0) {
continue;
}
Player loop = PlayerHandler.players[clans[player.getClanId()].members[index]];
if (loop == null) {
continue;
}
if (player.getClanId() == loop.getClanId() && loop.getPlayerName().equals(name)) {
Server.clanChat.leaveClan(loop.getPlayerId(), loop.getClanId(), true, true, true);
break;
}
}
}
public static void receiveModeratorPacket(Player player, String name) {
if (name.isEmpty()) {
return;
}
name = Misc.capitalize(name);
if (!hasPermission(player)) {
return;
}
if (ClanChatHandler.clans[player.getClanId()].ownerName.equalsIgnoreCase("dice")) {
player.getPA().sendMessage("In-game moderators already have Dice cc powers.");
return;
}
for (int index = 0; index < clans[player.getClanId()].moderators.size(); index++) {
if (name.equals(clans[player.getClanId()].moderators.get(index))) {
player.getPA().sendMessage(Misc.capitalize(name) + " is already a moderator.");
return;
}
}
clans[player.getClanId()].updated = true;
clans[player.getClanId()].moderators.add(name);
updateModeratorText(player);
}
public static boolean isClanChatButton(Player player, int buttonId) {
if (buttonId >= 76159 && buttonId <= 76159 + 49) {
unBan(player, buttonId, player.getClanId());
return true;
}
if (buttonId >= 76140 && buttonId <= 76140 + 9) {
unMod(player, buttonId, player.getClanId());
return true;
}
switch (buttonId) {
// Public/friends.
case 76127:
publicFriendsToggle(player);
return true;
// Change title.
case 76209:
player.getPA().sendMessage(":cctitle:");
return true;
// Ban
case 76137:
player.getPA().sendMessage(":ccbanplayer:");
return true;
// Moderator
case 76134:
player.getPA().sendMessage(":ccmodplayer:");
return true;
// Join/Leave clanchat.
case 70209:
joinLeaveButton(player);
return true;
// Clan chat setup.
case 70212:
clanChatSetUp(player);
return true;
}
return false;
}
private static void publicFriendsToggle(Player player) {
if (!inClanChat(player)) {
player.getPA().sendMessage("You need to be in a clan chat to use this.");
return;
}
if (!hasPermission(player)) {
return;
}
if (ClanChatHandler.clans[player.getClanId()].ownerName.equalsIgnoreCase("dice")) {
return;
}
clans[player.getClanId()].publicChat = !clans[player.getClanId()].publicChat;
clans[player.getClanId()].updated = true;
updatePublicText(player);
if (!clans[player.getClanId()].publicChat) {
int clanId = player.getClanId();
for (int index = 0; index < clans.length; index++) {
if (clans[clanId] == null) {
continue;
}
if (clans[clanId].members[index] <= 0) {
continue;
}
Player loop = PlayerHandler.players[clans[clanId].members[index]];
if (loop == null) {
continue;
}
loop.getPA().sendMessage("This clan chat has been changed to friends only.");
boolean isAFriend = false;
if (loop.getPlayerName().equalsIgnoreCase(clans[clanId].ownerName)) {
isAFriend = true;
} else {
if (clans[clanId].friends == null) {
ArrayList<String> friends = new ArrayList<String>();
for (index = 0; index < player.friends.length; index++) {
if (player.friends[index][0] == 0) {
continue;
}
friends.add(Misc.capitalize(Misc.nameForLong(player.friends[index][0]).replaceAll("_", " ")));
}
clans[clanId].friends = friends;
}
for (int a = 0; a < clans[clanId].friends.size(); a++) {
if (loop.getPlayerName().equalsIgnoreCase(clans[clanId].friends.get(a))) {
isAFriend = true;
break;
}
}
}
if (!isAFriend) {
Server.clanChat.leaveClan(loop.getPlayerId(), clanId, true, false, true);
}
}
} else {
for (int index = 0; index < clans[player.getClanId()].members.length; index++) {
if (clans[player.getClanId()].members[index] <= 0) {
continue;
}
Player loop = PlayerHandler.players[clans[player.getClanId()].members[index]];
if (loop == null) {
continue;
}
loop.getPA().sendMessage("This clan chat has been change to public access.");
}
}
}
private static boolean inClanChat(Player player) {
if (player.getClanId() >= 0) {
return true;
}
return false;
}
private static void clanChatSetUp(Player player) {
if (!inClanChat(player)) {
player.getPA().sendMessage("You need to be in a clan chat to use this.");
return;
}
if (!hasPermission(player)) {
player.getPA().sendMessage("You do not have permissions in this clan chat to use this.");
return;
}
updatePublicText(player);
updateClanChatTitle(player);
updateModeratorText(player);
updateBannedText(player);
player.getPA().displayInterface(19580);
}
private static void updateClanChatTitle(Player player) {
player.getPA().sendFrame126(clans[player.getClanId()].clanChatTitle, 19668);
}
private static void updateModeratorText(Player player) {
int lastIdUsed = 19595;
player.clanChatModeratorList.clear();
for (int index = 0; index < clans[player.getClanId()].moderators.size(); index++) {
player.getPA().sendFrame126(Misc.capitalize(clans[player.getClanId()].moderators.get(index)), 19596 + index);
player.clanChatModeratorList.add(clans[player.getClanId()].moderators.get(index));
lastIdUsed++;
}
lastIdUsed++;
InterfaceAssistant.clearFrames(player, lastIdUsed, 19613);
}
private static void updateBannedText(Player player) {
player.clanChatBannedList.clear();
int lastIdUsed = 19614;
for (int index = 0; index < clans[player.getClanId()].banned.size(); index++) {
if (index >= 50) {
break;
}
player.getPA().sendFrame126(Misc.capitalize(clans[player.getClanId()].banned.get(index)), 19615 + index);
player.clanChatBannedList.add(clans[player.getClanId()].banned.get(index));
lastIdUsed++;
}
lastIdUsed++;
InterfaceAssistant.clearFrames(player, lastIdUsed, 19664);
}
private static void updatePublicText(Player player) {
if (clans[player.getClanId()].publicChat) {
player.getPA().sendFrame126("Public", 19586);
} else {
player.getPA().sendFrame126("Friends", 19586);
}
}
public static void joinLeaveButton(Player player) {
if (player.getClanId() != -1) {
Server.clanChat.leaveClan(player.getPlayerId(), player.getClanId(), true, false, false);
return;
} else {
player.getPA().sendMessage(":joincc:");
}
}
/**
* True if the player is allowed to talk in clan chat.
*
* @param player The associated player.
*/
public boolean canTalkInClanChat(Player player, String message) {
if (player.getClanId() < 0) {
if (player.getClanId() != -1) {
player.setClanId(-1);
}
player.playerAssistant.sendMessage("You are not in a clan chat.");
return false;
}
if (Mute.isMuted(player)) {
return false;
}
if (dawntainedClanChat(player) && player.isJailed()) {
player.playerAssistant.sendMessage("You cannot talk in " + ServerConstants.getServerName() + " cc while jailed.");
return false;
}
if (dawntainedClanChat(player) && Misc.checkForOffensive(message)) {
player.playerAssistant.sendMessage("Do not use offensive language in the " + ServerConstants.getServerName() + " clan chat.");
return false;
}
int left = 15 - (player.secondsBeenOnline / 60);
if (dawntainedClanChat(player) && (player.secondsBeenOnline / 60) < 15) {
player.playerAssistant.sendMessage("You have to be online for " + left + " more minutes to use " + ServerConstants.getServerName() + " clan chat.");
return false;
}
return true;
}
/**
* True, if the player is in the Dawntain clan chat.
*
* @param player The associated player.
* @return True, if player is in Dawntain clan chat.
*/
private boolean dawntainedClanChat(Player player) {
if (clans[player.getClanId()].ownerName == null) {
return false;
}
return clans[player.getClanId()].ownerName.equalsIgnoreCase("" + ServerConstants.getServerName() + "");
}
/**
* Player logs out.
*
* @param player The associated player.
*/
public void logOut(Player player) {
if (player.getClanId() >= 0) {
leaveClan(player.getPlayerId(), player.getClanId(), false, false, true);
}
}
/**
* Player joins a clan chat.
*
* @param player The associated player.
* @param clanChatName The clan chat name.
*/
public void joinClanChat(Player player, String clanChatName, boolean logIn) {
if (player.bot) {
return;
}
if (player.getClanId() != -1) {
player.playerAssistant.sendMessage("You are already in a clan.");
return;
}
for (int j = 0; j < clans.length; j++) {
if (clans[j] != null) {
if (clans[j].ownerName.equalsIgnoreCase(clanChatName)) {
if (clanChatName.equalsIgnoreCase("dice")) {
if (DuelArenaBan.isDuelBanned(player, false)) {
return;
}
}
addToClan(player.getPlayerId(), j, logIn);
return;
}
}
}
makeClan(player, clanChatName, logIn);
}
public void makeClan(Player player, String clanChatName, boolean logIn) {
if (openClan() >= 0) {
if (validName(clanChatName)) {
if (player.getClanId() != -1) {
return;
}
if (clanChatName.equalsIgnoreCase("dice")) {
if (DuelArenaBan.isDuelBanned(player, false)) {
return;
}
}
player.setClanId(openClan());
clans[player.getClanId()] = new Clan(clanChatName);
clans[player.getClanId()].clanChatTitle = Misc.capitalize(clans[player.getClanId()].ownerName);
grabDataFromSavedClanChats(player);
addToClan(player.getPlayerId(), player.getClanId(), logIn);
player.getPA().sendFrame126("Leave Chat", 18135);
} else {
player.playerAssistant.sendMessage("A clan with this name already exists.");
}
} else {
player.playerAssistant.sendMessage("Your clan chat request could not be completed.");
}
}
public void updateClanChat(int clanId) {
boolean hasAMember = false;
for (int j = 0; j < clans[clanId].members.length; j++) {
if (clans[clanId].members[j] <= 0) {
continue;
}
hasAMember = true;
Player player = PlayerHandler.players[clans[clanId].members[j]];
if (player != null) {
player.getPA().sendFrame126("Owner: " + Misc.capitalize(clans[clanId].ownerName), 18139);
player.getPA().sendFrame126("Talking in: " + clans[clanId].clanChatTitle, 18140);
int slotToFill = 24600;
boolean dawntainedCc = false;
if (clans[clanId].ownerName.equalsIgnoreCase("dawntained")) {
dawntainedCc = true;
}
int dawntainedCcAmount = 0;
for (int i = 0; i < clans[clanId].members.length; i++) {
if (clans[clanId].members[i] > 0) {
if (PlayerHandler.players[clans[clanId].members[i]] != null) {
if (dawntainedCc) {
dawntainedCcAmount++;
continue;
}
player.getPA().sendFrame126(getRankString(PlayerHandler.players[clans[clanId].members[i]]) + Misc.capitalize(
PlayerHandler.players[clans[clanId].members[i]].getPlayerName()), slotToFill);
slotToFill++;
}
}
}
if (dawntainedCc) {
player.getPA().sendFrame126(dawntainedCcAmount + " player" + Misc.getPluralS(dawntainedCcAmount) + " in the Dawntained cc.", slotToFill);
slotToFill++;
player.getPA().sendFrame126("Ask them any question.", slotToFill);
slotToFill++;
player.getPA().sendFrame126("Type in ::guide for tips.", slotToFill);
slotToFill++;
}
InterfaceAssistant.clearFrames(player, slotToFill, 24699);
}
}
if (!hasAMember) {
if (clans[clanId].updated) {
if (clans[clanId].indexOfClanChatsSavedData == -1) {
ClanChatStartUp data = new ClanChatStartUp(clans[clanId].ownerName, clans[clanId].clanChatTitle, clans[clanId].publicChat, clans[clanId].banned,
clans[clanId].moderators, clans[clanId].updated, clans[clanId].friends);
ClanChatStartUp.clanChats.add(data);
} else {
ClanChatStartUp.clanChats.get(clans[clanId].indexOfClanChatsSavedData).banned = clans[clanId].banned;
ClanChatStartUp.clanChats.get(clans[clanId].indexOfClanChatsSavedData).moderators = clans[clanId].moderators;
ClanChatStartUp.clanChats.get(clans[clanId].indexOfClanChatsSavedData).clanChatTitle = clans[clanId].clanChatTitle;
ClanChatStartUp.clanChats.get(clans[clanId].indexOfClanChatsSavedData).publicChat = clans[clanId].publicChat;
ClanChatStartUp.clanChats.get(clans[clanId].indexOfClanChatsSavedData).updated = clans[clanId].updated;
ClanChatStartUp.clanChats.get(clans[clanId].indexOfClanChatsSavedData).friends = clans[clanId].friends;
}
}
clans[clanId] = null;
}
}
private String getRankString(Player player) {
if (inDiceCc(player, false, false)) {
if (ItemAssistant.hasItemInInventory(player, 16004)) {
return "<img=14>";
}
}
if (player.getPlayerName().equals(clans[player.getClanId()].ownerName)) {
return "<img=15>";
}
for (int index = 0; index < clans[player.getClanId()].moderators.size(); index++) {
if (player.getPlayerName().equals(clans[player.getClanId()].moderators.get(index))) {
return "<img=14>";
}
}
if (clans[player.getClanId()].friends != null) {
for (int a = 0; a < clans[player.getClanId()].friends.size(); a++) {
if (player.getPlayerName().equals(clans[player.getClanId()].friends.get(a))) {
return "<img=16>";
}
}
}
return "";
}
public int openClan() {
for (int j = 0; j < clans.length; j++) {
if (clans[j] == null) {
return j;
}
}
return -1;
}
public boolean validName(String name) {
for (int j = 0; j < clans.length; j++) {
if (clans[j] != null) {
if (clans[j].ownerName.equalsIgnoreCase(name)) {
return false;
}
}
}
return true;
}
public void addToClan(int playerId, int clanId, boolean logIn) {
boolean added = false;
Player player = PlayerHandler.players[playerId];
if (clans[clanId] != null) {
if (isBanned(player, clanId)) {
player.getPA().sendMessage("You are banned from this clan chat.");
if (clans[clanId].ownerName.equals("Dice")) {
player.getPA().sendMessage("You will have to pay 10m Osrs fine to be able to dice once again.");
player.getPA().sendMessage("Buy it from ::goldwebsites and pay any Moderator on ::staff");
}
return;
}
if (!clans[clanId].publicChat) {
boolean isAFriend = false;
if (player.getPlayerName().equals(clans[clanId].ownerName)) {
isAFriend = true;
} else {
if (clans[clanId].friends != null) {
for (int a = 0; a < clans[clanId].friends.size(); a++) {
if (player.getPlayerName().equals(clans[clanId].friends.get(a))) {
isAFriend = true;
break;
}
}
}
}
if (!isAFriend) {
player.getPA().sendMessage("This clan chat is for friends only.");
player.getPA().sendFrame126("Join Chat", 18135);
player.lastClanChatJoined = "";
clearClanChat(player, true);
return;
}
}
for (int j = 0; j < clans[clanId].members.length; j++) {
if (clans[clanId].members[j] <= 0) {
if (player.bot) {
return;
}
clans[clanId].members[j] = playerId;
player.setClanId(clanId);
playerJoinedClanChatMessage(PlayerRank.getIconText(player.playerRights, false) + player.getCapitalizedName() + " has joined the channel.", clanId);
updateClanChat(clanId);
player.lastClanChatJoined = clans[player.getClanId()].ownerName;
player.getPA().sendFrame126("Leave Chat", 18135);
added = true;
if (!logIn) {
if (inDiceCc(player, false, true)) {
if (!Area.inDiceZone(player)) {
Teleport.spellTeleport(player, 1690 + Misc.random(3), 4250 + Misc.random(3), 0, false);
ClanChatHandler.displayDiceRulesInterface(player);
}
}
}
return;
}
}
if (!added) {
player.getPA().sendMessage("Clan is full.");
}
}
}
public void leaveClan(int playerId, int clanId, boolean manual, boolean banned, boolean noMessage) {
if (clanId < 0) {
Player c = PlayerHandler.players[playerId];
c.playerAssistant.sendMessage("You are not in a clan.");
return;
}
if (clans[clanId] != null) {
for (int j = 0; j < clans[clanId].members.length; j++) {
if (clans[clanId].members[j] == playerId) {
clans[clanId].members[j] = -1;
}
}
if (PlayerHandler.players[playerId] != null) {
Player player = PlayerHandler.players[playerId];
PlayerHandler.players[playerId].setClanId(-1);
if (banned) {
player.getPA().sendMessage("You have been banned from the clan chat.");
} else if (!noMessage) {
player.playerAssistant.sendMessage("You have left the clan.");
}
player.getPA().sendFrame126("Join Chat", 18135);
if (manual) {
player.lastClanChatJoined = "";
}
clearClanChat(player, true);
}
updateClanChat(clanId);
} else {
Player c = PlayerHandler.players[playerId];
PlayerHandler.players[playerId].setClanId(-1);
c.playerAssistant.sendMessage("You are not in a clan.");
}
}
public void playerJoinedClanChatMessage(String message, int clanId) {
if (clanId < 0)
return;
for (int j = 0; j < clans[clanId].members.length; j++) {
if (clans[clanId].members[j] < 0)
continue;
if (PlayerHandler.players[clans[clanId].members[j]] != null) {
Player c = PlayerHandler.players[clans[clanId].members[j]];
c.playerAssistant.sendFilterableMessage("" + message);
}
}
}
public void playerMessageToClan(int playerId, String message, int clanId) {
if (clanId < 0) {
return;
}
Player player1 = PlayerHandler.players[playerId];
player1.clanChatMessageTime = System.currentTimeMillis();
player1.rwtChat.add("[" + Misc.getDateAndTime() + "] CC '" + ClanChatHandler.clans[clanId].ownerName + "': " + message);
if (ClanChatHandler.clans[clanId].ownerName.equalsIgnoreCase("dice")) {
String string = Misc.getDateAndTime() + "[" + PlayerHandler.players[playerId].getCapitalizedName() + "] sent a message: " + message;
DiceSystem.diceZoneChatLog.add(string);
diceLog.add(string);
}
for (int j = 0; j < clans[clanId].members.length; j++) {
if (clans[clanId].members[j] <= 0)
continue;
if (PlayerHandler.players[clans[clanId].members[j]] != null) {
Player player = PlayerHandler.players[clans[clanId].members[j]];
player.getPA().sendClan(PlayerHandler.players[playerId].getCapitalizedName(), message, Misc.capitalize(clans[clanId].ownerName),
PlayerHandler.players[playerId].playerRights);
}
}
}
public void clearClanChat(Player player, boolean clearInterface) {
player.setClanId(-1);
if (clearInterface) {
player.getPA().sendFrame126("Owner: ", 18139);
player.getPA().sendFrame126("Talking in: ", 18140);
InterfaceAssistant.clearFrames(player, 24600, 24699);
}
}
/**
* Receive the clan chat message that the player typed in.
*
* @param player The associated player.
*/
public void receiveClanChatMessage(Player player, String message) {
message = message.substring(1);
if (Misc.containsPassword(player.playerPass, message)) {
return;
}
if (!canTalkInClanChat(player, message)) {
return;
}
/* Check for empty message. */
if (message.trim().length() == 0) {
return;
}
/* Convert message to lowercase and capitalize first letter. */
String convertMessage = message.substring(1);
convertMessage = convertMessage.toLowerCase();
message = message.substring(0, 1).toUpperCase() + convertMessage;
Server.clanChat.playerMessageToClan(player.getPlayerId(), message, player.getClanId());
}
public static ArrayList<String> diceLog = new ArrayList<String>();
public static void sendDiceClanMessage(String name, int diceChannelId, String message) {
String string = Misc.getDateAndTime() + " [Official] " + name + ": " + message;
DiceSystem.diceZoneChatLog.add(string);
diceLog.add(string);
for (int j = 0; j < ClanChatHandler.clans[diceChannelId].members.length; j++) {
if (ClanChatHandler.clans[diceChannelId].members[j] <= 0) {
continue;
}
if (PlayerHandler.players[ClanChatHandler.clans[diceChannelId].members[j]] != null) {
Player loop = PlayerHandler.players[ClanChatHandler.clans[diceChannelId].members[j]];
// 8 means to show img=8 rank on the client for quick chat icon.
loop.getPA().sendClan(name, message, Misc.capitalize(ClanChatHandler.clans[diceChannelId].ownerName), 8);
}
}
}
public static boolean inDiceCc(Player player, boolean message, boolean ignoreDiceZoneCheck) {
if (player == null) {
return false;
}
if (player.getClanId() < 0) {
if (message) {
player.getPA().sendMessage("You need to be in the 'Dice' channel to dice.");
}
return false;
}
if (ClanChatHandler.clans[player.getClanId()] == null) {
return false;
}
if (!ClanChatHandler.clans[player.getClanId()].ownerName.equalsIgnoreCase("dice")) {
if (message) {
player.getPA().sendMessage("You need to be in the 'Dice' channel to dice.");
}
return false;
}
if (!Area.inDiceZone(player) && !ignoreDiceZoneCheck) {
if (message) {
player.getPA().sendMessage("You need to be in the the ::dice zone to dice.");
}
return false;
}
return true;
}
private final static String[] diceRulesText =
{
"@red@Follow the rules below or you will be punished!",
"",
"@yel@Host deposit vault:",
"It is the amount of blood money a host has",
"added to their deposit vault. It is used to refund victims",
"of scams. The game will not allow a host to remove blood",
"money from their deposit vault for 48 hours after their",
"last trade was accepted.",
"Trading a host will show their deposit vault amount &",
"their inventory wealth amount.",
"",
"@yel@General rules:",
"- Everything gamble related must be done in Dice zone.",
"- Breaking rules will result in a punishment.",
"- You must never self hold.",
"- Hosts can only plant for themselves and their customer.",
"- Scammers will have their dice & seeds removed and",
"their deposit vault transferred to the victim.",
"- Before betting against a host, you MUST check if they",
"are able to pay you from their inventory and they have",
"enough in their deposit vault to cover a scam against",
"you!",
"- Hosts are not allowed to bet their deposit vault.",
"- Hosts cannot accept bets worth more than their vault.",
"",
"All text in this area is logged.",
"Hosts have a crown next to their name in cc.",
"Report scammers to ::staff",
"",
"@yel@Dicing rules:",
"- Host always rolls for the customer first.",
"- If tie, Host wins.",
"- 55x2, 55 is host win",
"",
"@yel@Flower rules:",
"- Host always plants for the customer first.",
"- If tie, replant",
"- Black/White = both parties replant",
};
public static void displayDiceRulesInterface(Player player) {
player.diceRulesForce = true;
int frameIndex = 0;
player.getPA().sendFrame126("GAMBLING RULES: MUST READ!", 28872);
for (int index = 0; index < diceRulesText.length; index++) {
player.getPA().sendFrame126(diceRulesText[index], 28878 + index);
frameIndex++;
}
InterfaceAssistant.setFixedScrollMax(player, 28877, frameIndex * 17);
player.getPA().displayInterface(28870);
}
}
|
drincast/EntrenoReact | 03ReactGuiaCompletaHooksContextMERN/sec09/weather/src/components/Header.js | <reponame>drincast/EntrenoReact
import React from 'react';
import PropTypes from 'prop-types';
const Header = ({title}) => {
return(
<nav>
<div className="nav-wrapper light-blue darken-2">
<a href='#!' className='brand-logo'>{title}</a>
</div>
</nav>
);
}
Header.protoTypes = {
title: PropTypes.string.isRequired
}
export default Header; |
giantswarm/gsclientgen | models/v4_modify_user_password_request.go | // Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
strfmt "github.com/go-openapi/strfmt"
"github.com/go-openapi/errors"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// V4ModifyUserPasswordRequest Request model for modifying a user's password
// swagger:model v4ModifyUserPasswordRequest
type V4ModifyUserPasswordRequest struct {
// Current password encoded in Base64. Not required for admins
CurrentPasswordBase64 string `json:"current_password_base64,omitempty"`
// New password encoded in Base64
// Required: true
NewPasswordBase64 *string `json:"new_password_base64"`
}
// Validate validates this v4 modify user password request
func (m *V4ModifyUserPasswordRequest) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateNewPasswordBase64(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *V4ModifyUserPasswordRequest) validateNewPasswordBase64(formats strfmt.Registry) error {
if err := validate.Required("new_password_base64", "body", m.NewPasswordBase64); err != nil {
return err
}
return nil
}
// MarshalBinary interface implementation
func (m *V4ModifyUserPasswordRequest) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *V4ModifyUserPasswordRequest) UnmarshalBinary(b []byte) error {
var res V4ModifyUserPasswordRequest
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}
|
huyu0415/FFmpeg | ffmpeg-3.2.5/libavformat/lrcenc.c | /*
* LRC lyrics file format decoder
* Copyright (c) 2014 StarBrilliant <<EMAIL>>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <inttypes.h>
#include <stdint.h>
#include <string.h>
#include "avformat.h"
#include "internal.h"
#include "lrc.h"
#include "metadata.h"
#include "subtitles.h"
#include "version.h"
#include "libavutil/bprint.h"
#include "libavutil/dict.h"
#include "libavutil/log.h"
#include "libavutil/macros.h"
static int lrc_write_header(AVFormatContext *s)
{
const AVDictionaryEntry *metadata_item;
if(s->nb_streams != 1 ||
s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE) {
av_log(s, AV_LOG_ERROR,
"LRC supports only a single subtitle stream.\n");
return AVERROR(EINVAL);
}
if(s->streams[0]->codecpar->codec_id != AV_CODEC_ID_SUBRIP &&
s->streams[0]->codecpar->codec_id != AV_CODEC_ID_TEXT) {
av_log(s, AV_LOG_ERROR, "Unsupported subtitle codec: %s\n",
avcodec_get_name(s->streams[0]->codecpar->codec_id));
return AVERROR(EINVAL);
}
avpriv_set_pts_info(s->streams[0], 64, 1, 100);
ff_standardize_creation_time(s);
ff_metadata_conv_ctx(s, ff_lrc_metadata_conv, NULL);
if(!(s->flags & AVFMT_FLAG_BITEXACT)) { // avoid breaking regression tests
/* LRC provides a metadata slot for specifying encoder version
* in addition to encoder name. We will store LIBAVFORMAT_VERSION
* to it.
*/
av_dict_set(&s->metadata, "ve", AV_STRINGIFY(LIBAVFORMAT_VERSION), 0);
} else {
av_dict_set(&s->metadata, "ve", NULL, 0);
}
for(metadata_item = NULL;
(metadata_item = av_dict_get(s->metadata, "", metadata_item,
AV_DICT_IGNORE_SUFFIX));) {
char *delim;
if(!metadata_item->value[0]) {
continue;
}
while((delim = strchr(metadata_item->value, '\n'))) {
*delim = ' ';
}
while((delim = strchr(metadata_item->value, '\r'))) {
*delim = ' ';
}
avio_printf(s->pb, "[%s:%s]\n",
metadata_item->key, metadata_item->value);
}
avio_printf(s->pb, "\n");
return 0;
}
static int lrc_write_packet(AVFormatContext *s, AVPacket *pkt)
{
if(pkt->pts != AV_NOPTS_VALUE) {
char *data = av_malloc(pkt->size + 1);
char *line;
char *delim;
if(!data) {
return AVERROR(ENOMEM);
}
memcpy(data, pkt->data, pkt->size);
data[pkt->size] = '\0';
for(delim = data + pkt->size - 1;
delim >= data && (delim[0] == '\n' || delim[0] == '\r'); delim--) {
delim[0] = '\0'; // Strip last empty lines
}
line = data;
while(line[0] == '\n' || line[0] == '\r') {
line++; // Skip first empty lines
}
while(line) {
delim = strchr(line, '\n');
if(delim) {
if(delim > line && delim[-1] == '\r') {
delim[-1] = '\0';
}
delim[0] = '\0';
delim++;
}
if(line[0] == '[') {
av_log(s, AV_LOG_WARNING,
"Subtitle starts with '[', may cause problems with LRC format.\n");
}
if(pkt->pts >= 0) {
avio_printf(s->pb, "[%02"PRId64":%02"PRId64".%02"PRId64"]",
(pkt->pts / 6000),
((pkt->pts / 100) % 60),
(pkt->pts % 100));
} else {
/* Offset feature of LRC can easily make pts negative,
* we just output it directly and let the player drop it. */
avio_printf(s->pb, "[-%02"PRId64":%02"PRId64".%02"PRId64"]",
(-pkt->pts) / 6000,
((-pkt->pts) / 100) % 60,
(-pkt->pts) % 100);
}
avio_printf(s->pb, "%s\n", line);
line = delim;
}
av_free(data);
}
return 0;
}
AVOutputFormat ff_lrc_muxer = {
.name = "lrc",
.long_name = NULL_IF_CONFIG_SMALL("LRC lyrics"),
.extensions = "lrc",
.priv_data_size = 0,
.write_header = lrc_write_header,
.write_packet = lrc_write_packet,
.flags = AVFMT_VARIABLE_FPS | AVFMT_GLOBALHEADER |
AVFMT_TS_NEGATIVE | AVFMT_TS_NONSTRICT,
.subtitle_codec = AV_CODEC_ID_SUBRIP
};
|
Tuscann/Java-Advanced---2017 | 06.EXERCISE ABSTRACTION/src/_03_Diagonal_Difference2.java | <filename>06.EXERCISE ABSTRACTION/src/_03_Diagonal_Difference2.java
import java.util.Scanner;
public class _03_Diagonal_Difference2 { // 100/100
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = Integer.parseInt(in.nextLine());
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
String[] currentRow = in.nextLine().split("\\s+");
for (int j = 0; j < n; j++) {
matrix[i][j] = Integer.parseInt(currentRow[j]);
}
}
int leftToRight = 0;
int rightToLeft = 0;
for (int i = 0; i < n; i++) {
leftToRight += matrix[i][i];
rightToLeft += matrix[i][n - i - 1];
}
System.out.println(Math.abs(leftToRight - rightToLeft));
}
}
|
88act/go-cms | server/plugin/txim/txFileDown.go | package plugin
import (
"go-cms/global"
"go-cms/model/business"
bizReq "go-cms/model/business/request"
bizSev "go-cms/service/business"
"go-cms/utils"
"path"
"strconv"
"strings"
"sync"
)
//文件下载器
type TxFileDown struct {
statusRun int
}
var once_TxFileDown sync.Once = sync.Once{}
var obj_TxFileDown *TxFileDown
var wg sync.WaitGroup
/**
*获取单例
*/
func GetTxFileDown() *TxFileDown {
once_TxFileDown.Do(func() {
obj_TxFileDown = new(TxFileDown)
})
return obj_TxFileDown
}
func (m *TxFileDown) StartDownload() {
if m.statusRun == 1 {
global.LOG.Info("文件下载器txFileDown已经在下载中....statusRun =1")
return
}
m.statusRun = 1
//获取未下载的文件
go m.doDownload()
}
func (m *TxFileDown) doDownload() {
global.LOG.Info("下载 。。。。。 doDownload")
var pageInfo bizReq.ImTxFileSearch
pageInfo.Page = 1
pageInfo.PageSize = 20
pageInfo.OrderKey = "id"
pageInfo.OrderDesc = false
pageInfo.Status = utils.IntPtr(0)
createdAtBetween := []string{}
wg = sync.WaitGroup{}
if list, _, err := bizSev.GetImTxFileSev().GetListAll(pageInfo, createdAtBetween, ""); err != nil {
global.LOG.Error("下载文件ImTxFile获取失败" + err.Error())
return
} else {
global.LOG.Info("等待下载文件 len = " + strconv.Itoa(len(list)))
if len(list) == 0 {
m.statusRun = 0
global.LOG.Info("下载完成.正常退出doDownload")
return
}
for _, v := range list {
wg.Add(1)
go downOne(v)
}
}
wg.Wait()
global.LOG.Info("下载完成 ...继续 doDownload ")
m.doDownload()
}
func downOne(v business.ImTxFile) {
filename := path.Base(v.Url)
if fullPath, err := utils.DownloadFile(v.Url, v.Local, filename); err == nil {
global.LOG.Info("downOne fullPath = " + fullPath)
//更新数据库
mp := make(map[string]interface{})
///字符串替换, -1表示全部替换, 0表示不替换, 1表示替换第一个, 2表示替换第二个...
local := strings.Replace(fullPath, global.CONFIG.Local.BasePath, "", -1)
mp["local"] = local
mp["status"] = 1
ext := path.Ext(local)
media_type := 2
if ext == ".mp4" {
media_type = 3
} else if ext == ".m4a" {
media_type = 4
}
mp["media_type"] = media_type
global.LOG.Info(" 成功下载fullPath = " + fullPath)
bizSev.GetImTxFileSev().UpdateByMap(v, mp)
} else {
global.LOG.Error("下载失败 v.Url =" + v.Url + err.Error())
}
wg.Done()
}
|
weng-lab/SCREEN | 2_import/30_cytobands.py | #!/usr/bin/env python2
# SPDX-License-Identifier: MIT
# Copyright (c) 2016-2020 <NAME>, <NAME>, <NAME>, <NAME>
from __future__ import print_function
import os
import sys
import gzip
import argparse
import json
sys.path.append(os.path.join(os.path.dirname(__file__), '../../metadata/utils'))
from utils import Utils, eprint, AddPath, printt
AddPath(__file__, '../common/')
from db_utils import getcursor
from dbconnect import db_connect
from constants import paths
from config import Config
class Cytoband:
def __init__(self, curs, assembly):
self.curs = curs
self.assembly = assembly
self.tableName = self.assembly + "_cytobands"
def run(self):
self._load()
self._import()
self.show()
def _load(self):
fnp = paths.cytobands[self.assembly]
self.bands = {}
with gzip.open(fnp, "r") as f:
for line in f:
p = line.strip().split("\t")
if p[0] not in self.bands:
self.bands[p[0]] = []
if "gpos" in p[4]:
self.bands[p[0]].append({"start": int(p[1]),
"end": int(p[2]),
"feature": p[4],
"color": float(p[4].replace("gpos", "")) / 100.0})
else:
self.bands[p[0]].append({"start": int(p[1]),
"end": int(p[2]),
"feature": p[4]})
def _import(self):
printt('***********', "drop and create", self.tableName)
self.curs.execute("""
DROP TABLE IF EXISTS {tableName};
CREATE TABLE {tableName}
(id serial PRIMARY KEY,
assembly text,
cytobands jsonb);""".format(tableName=self.tableName))
printt('***********', "import cytobands")
self.curs.execute("""
INSERT INTO {tableName}
(assembly, cytobands)
VALUES (%s, %s)
""".format(tableName=self.tableName),
(self.assembly,
json.dumps(self.bands)))
print("updated", self.tableName)
def show(self):
for chrom, bands in self.bands.iteritems():
print(chrom, len(bands), bands[0])
print()
print(json.dumps(self.bands, sort_keys=True, indent=4))
def run(args, DBCONN):
assemblies = Config.assemblies
if args.assembly:
assemblies = [args.assembly]
for assembly in assemblies:
printt('***********', assembly)
with getcursor(DBCONN, "30_cytobands") as curs:
c = Cytoband(curs, assembly)
c.run()
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--assembly", type=str, default="")
args = parser.parse_args()
return args
def main():
args = parse_args()
DBCONN = db_connect(os.path.realpath(__file__))
run(args, DBCONN)
return 0
if __name__ == "__main__":
sys.exit(main())
|
manxx5521/shabao-blog | shabao-blog-core/src/test/java/test/SpringBeanTest.java | package test;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.xiaoshabao.base.component.SpringContextHolder;
import com.xiaoshabao.base.service.SysConfigService;
import com.xiaoshabao.blog.BlogCoreApplication;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = BlogCoreApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@WebAppConfiguration
public class SpringBeanTest {
@Test
public void testAddProject() {
try {
SpringContextHolder.getBean("sysConfigServiceImpl", SysConfigService.class);
} catch (Exception e) {
e.printStackTrace();
fail("Not yet implemented");
}
}
}
|
WUSTL-CSPL/RT-TEE | linux/samples/bpf/task_fd_query_user.c | // SPDX-License-Identifier: GPL-2.0
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <stdbool.h>
#include <string.h>
#include <stdint.h>
#include <fcntl.h>
#include <linux/bpf.h>
#include <sys/ioctl.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "libbpf.h"
#include "bpf_load.h"
#include "bpf_util.h"
#include "perf-sys.h"
#include "trace_helpers.h"
#define CHECK_PERROR_RET(condition) ({ \
int __ret = !!(condition); \
if (__ret) { \
printf("FAIL: %s:\n", __func__); \
perror(" "); \
return -1; \
} \
})
#define CHECK_AND_RET(condition) ({ \
int __ret = !!(condition); \
if (__ret) \
return -1; \
})
static __u64 ptr_to_u64(void *ptr)
{
return (__u64) (unsigned long) ptr;
}
#define PMU_TYPE_FILE "/sys/bus/event_source/devices/%s/type"
static int bpf_find_probe_type(const char *event_type)
{
char buf[256];
int fd, ret;
ret = snprintf(buf, sizeof(buf), PMU_TYPE_FILE, event_type);
CHECK_PERROR_RET(ret < 0 || ret >= sizeof(buf));
fd = open(buf, O_RDONLY);
CHECK_PERROR_RET(fd < 0);
ret = read(fd, buf, sizeof(buf));
close(fd);
CHECK_PERROR_RET(ret < 0 || ret >= sizeof(buf));
errno = 0;
ret = (int)strtol(buf, NULL, 10);
CHECK_PERROR_RET(errno);
return ret;
}
#define PMU_RETPROBE_FILE "/sys/bus/event_source/devices/%s/format/retprobe"
static int bpf_get_retprobe_bit(const char *event_type)
{
char buf[256];
int fd, ret;
ret = snprintf(buf, sizeof(buf), PMU_RETPROBE_FILE, event_type);
CHECK_PERROR_RET(ret < 0 || ret >= sizeof(buf));
fd = open(buf, O_RDONLY);
CHECK_PERROR_RET(fd < 0);
ret = read(fd, buf, sizeof(buf));
close(fd);
CHECK_PERROR_RET(ret < 0 || ret >= sizeof(buf));
CHECK_PERROR_RET(strlen(buf) < strlen("config:"));
errno = 0;
ret = (int)strtol(buf + strlen("config:"), NULL, 10);
CHECK_PERROR_RET(errno);
return ret;
}
static int test_debug_fs_kprobe(int prog_fd_idx, const char *fn_name,
__u32 expected_fd_type)
{
__u64 probe_offset, probe_addr;
__u32 len, prog_id, fd_type;
char buf[256];
int err;
len = sizeof(buf);
err = bpf_task_fd_query(getpid(), event_fd[prog_fd_idx], 0, buf, &len,
&prog_id, &fd_type, &probe_offset,
&probe_addr);
if (err < 0) {
printf("FAIL: %s, for event_fd idx %d, fn_name %s\n",
__func__, prog_fd_idx, fn_name);
perror(" :");
return -1;
}
if (strcmp(buf, fn_name) != 0 ||
fd_type != expected_fd_type ||
probe_offset != 0x0 || probe_addr != 0x0) {
printf("FAIL: bpf_trace_event_query(event_fd[%d]):\n",
prog_fd_idx);
printf("buf: %s, fd_type: %u, probe_offset: 0x%llx,"
" probe_addr: 0x%llx\n",
buf, fd_type, probe_offset, probe_addr);
return -1;
}
return 0;
}
static int test_nondebug_fs_kuprobe_common(const char *event_type,
const char *name, __u64 offset, __u64 addr, bool is_return,
char *buf, __u32 *buf_len, __u32 *prog_id, __u32 *fd_type,
__u64 *probe_offset, __u64 *probe_addr)
{
int is_return_bit = bpf_get_retprobe_bit(event_type);
int type = bpf_find_probe_type(event_type);
struct perf_event_attr attr = {};
int fd;
if (type < 0 || is_return_bit < 0) {
printf("FAIL: %s incorrect type (%d) or is_return_bit (%d)\n",
__func__, type, is_return_bit);
return -1;
}
attr.sample_period = 1;
attr.wakeup_events = 1;
if (is_return)
attr.config |= 1 << is_return_bit;
if (name) {
attr.config1 = ptr_to_u64((void *)name);
attr.config2 = offset;
} else {
attr.config1 = 0;
attr.config2 = addr;
}
attr.size = sizeof(attr);
attr.type = type;
fd = sys_perf_event_open(&attr, -1, 0, -1, 0);
CHECK_PERROR_RET(fd < 0);
CHECK_PERROR_RET(ioctl(fd, PERF_EVENT_IOC_ENABLE, 0) < 0);
CHECK_PERROR_RET(ioctl(fd, PERF_EVENT_IOC_SET_BPF, prog_fd[0]) < 0);
CHECK_PERROR_RET(bpf_task_fd_query(getpid(), fd, 0, buf, buf_len,
prog_id, fd_type, probe_offset, probe_addr) < 0);
return 0;
}
static int test_nondebug_fs_probe(const char *event_type, const char *name,
__u64 offset, __u64 addr, bool is_return,
__u32 expected_fd_type,
__u32 expected_ret_fd_type,
char *buf, __u32 buf_len)
{
__u64 probe_offset, probe_addr;
__u32 prog_id, fd_type;
int err;
err = test_nondebug_fs_kuprobe_common(event_type, name,
offset, addr, is_return,
buf, &buf_len, &prog_id,
&fd_type, &probe_offset,
&probe_addr);
if (err < 0) {
printf("FAIL: %s, "
"for name %s, offset 0x%llx, addr 0x%llx, is_return %d\n",
__func__, name ? name : "", offset, addr, is_return);
perror(" :");
return -1;
}
if ((is_return && fd_type != expected_ret_fd_type) ||
(!is_return && fd_type != expected_fd_type)) {
printf("FAIL: %s, incorrect fd_type %u\n",
__func__, fd_type);
return -1;
}
if (name) {
if (strcmp(name, buf) != 0) {
printf("FAIL: %s, incorrect buf %s\n", __func__, buf);
return -1;
}
if (probe_offset != offset) {
printf("FAIL: %s, incorrect probe_offset 0x%llx\n",
__func__, probe_offset);
return -1;
}
} else {
if (buf_len != 0) {
printf("FAIL: %s, incorrect buf %p\n",
__func__, buf);
return -1;
}
if (probe_addr != addr) {
printf("FAIL: %s, incorrect probe_addr 0x%llx\n",
__func__, probe_addr);
return -1;
}
}
return 0;
}
static int test_debug_fs_uprobe(char *binary_path, long offset, bool is_return)
{
const char *event_type = "uprobe";
struct perf_event_attr attr = {};
char buf[256], event_alias[256];
__u64 probe_offset, probe_addr;
__u32 len, prog_id, fd_type;
int err, res, kfd, efd;
ssize_t bytes;
snprintf(buf, sizeof(buf), "/sys/kernel/debug/tracing/%s_events",
event_type);
kfd = open(buf, O_WRONLY | O_APPEND, 0);
CHECK_PERROR_RET(kfd < 0);
res = snprintf(event_alias, sizeof(event_alias), "test_%d", getpid());
CHECK_PERROR_RET(res < 0 || res >= sizeof(event_alias));
res = snprintf(buf, sizeof(buf), "%c:%ss/%s %s:0x%lx",
is_return ? 'r' : 'p', event_type, event_alias,
binary_path, offset);
CHECK_PERROR_RET(res < 0 || res >= sizeof(buf));
CHECK_PERROR_RET(write(kfd, buf, strlen(buf)) < 0);
close(kfd);
kfd = -1;
snprintf(buf, sizeof(buf), "/sys/kernel/debug/tracing/events/%ss/%s/id",
event_type, event_alias);
efd = open(buf, O_RDONLY, 0);
CHECK_PERROR_RET(efd < 0);
bytes = read(efd, buf, sizeof(buf));
CHECK_PERROR_RET(bytes <= 0 || bytes >= sizeof(buf));
close(efd);
buf[bytes] = '\0';
attr.config = strtol(buf, NULL, 0);
attr.type = PERF_TYPE_TRACEPOINT;
attr.sample_period = 1;
attr.wakeup_events = 1;
kfd = sys_perf_event_open(&attr, -1, 0, -1, PERF_FLAG_FD_CLOEXEC);
CHECK_PERROR_RET(kfd < 0);
CHECK_PERROR_RET(ioctl(kfd, PERF_EVENT_IOC_SET_BPF, prog_fd[0]) < 0);
CHECK_PERROR_RET(ioctl(kfd, PERF_EVENT_IOC_ENABLE, 0) < 0);
len = sizeof(buf);
err = bpf_task_fd_query(getpid(), kfd, 0, buf, &len,
&prog_id, &fd_type, &probe_offset,
&probe_addr);
if (err < 0) {
printf("FAIL: %s, binary_path %s\n", __func__, binary_path);
perror(" :");
return -1;
}
if ((is_return && fd_type != BPF_FD_TYPE_URETPROBE) ||
(!is_return && fd_type != BPF_FD_TYPE_UPROBE)) {
printf("FAIL: %s, incorrect fd_type %u\n", __func__,
fd_type);
return -1;
}
if (strcmp(binary_path, buf) != 0) {
printf("FAIL: %s, incorrect buf %s\n", __func__, buf);
return -1;
}
if (probe_offset != offset) {
printf("FAIL: %s, incorrect probe_offset 0x%llx\n", __func__,
probe_offset);
return -1;
}
close(kfd);
return 0;
}
int main(int argc, char **argv)
{
struct rlimit r = {1024*1024, RLIM_INFINITY};
extern char __executable_start;
char filename[256], buf[256];
__u64 uprobe_file_offset;
snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
if (setrlimit(RLIMIT_MEMLOCK, &r)) {
perror("setrlimit(RLIMIT_MEMLOCK)");
return 1;
}
if (load_kallsyms()) {
printf("failed to process /proc/kallsyms\n");
return 1;
}
if (load_bpf_file(filename)) {
printf("%s", bpf_log_buf);
return 1;
}
/* test two functions in the corresponding *_kern.c file */
CHECK_AND_RET(test_debug_fs_kprobe(0, "blk_start_request",
BPF_FD_TYPE_KPROBE));
CHECK_AND_RET(test_debug_fs_kprobe(1, "blk_account_io_completion",
BPF_FD_TYPE_KRETPROBE));
/* test nondebug fs kprobe */
CHECK_AND_RET(test_nondebug_fs_probe("kprobe", "bpf_check", 0x0, 0x0,
false, BPF_FD_TYPE_KPROBE,
BPF_FD_TYPE_KRETPROBE,
buf, sizeof(buf)));
#ifdef __x86_64__
/* set a kprobe on "bpf_check + 0x5", which is x64 specific */
CHECK_AND_RET(test_nondebug_fs_probe("kprobe", "bpf_check", 0x5, 0x0,
false, BPF_FD_TYPE_KPROBE,
BPF_FD_TYPE_KRETPROBE,
buf, sizeof(buf)));
#endif
CHECK_AND_RET(test_nondebug_fs_probe("kprobe", "bpf_check", 0x0, 0x0,
true, BPF_FD_TYPE_KPROBE,
BPF_FD_TYPE_KRETPROBE,
buf, sizeof(buf)));
CHECK_AND_RET(test_nondebug_fs_probe("kprobe", NULL, 0x0,
ksym_get_addr("bpf_check"), false,
BPF_FD_TYPE_KPROBE,
BPF_FD_TYPE_KRETPROBE,
buf, sizeof(buf)));
CHECK_AND_RET(test_nondebug_fs_probe("kprobe", NULL, 0x0,
ksym_get_addr("bpf_check"), false,
BPF_FD_TYPE_KPROBE,
BPF_FD_TYPE_KRETPROBE,
NULL, 0));
CHECK_AND_RET(test_nondebug_fs_probe("kprobe", NULL, 0x0,
ksym_get_addr("bpf_check"), true,
BPF_FD_TYPE_KPROBE,
BPF_FD_TYPE_KRETPROBE,
buf, sizeof(buf)));
CHECK_AND_RET(test_nondebug_fs_probe("kprobe", NULL, 0x0,
ksym_get_addr("bpf_check"), true,
BPF_FD_TYPE_KPROBE,
BPF_FD_TYPE_KRETPROBE,
0, 0));
/* test nondebug fs uprobe */
/* the calculation of uprobe file offset is based on gcc 7.3.1 on x64
* and the default linker script, which defines __executable_start as
* the start of the .text section. The calculation could be different
* on different systems with different compilers. The right way is
* to parse the ELF file. We took a shortcut here.
*/
uprobe_file_offset = (__u64)main - (__u64)&__executable_start;
CHECK_AND_RET(test_nondebug_fs_probe("uprobe", (char *)argv[0],
uprobe_file_offset, 0x0, false,
BPF_FD_TYPE_UPROBE,
BPF_FD_TYPE_URETPROBE,
buf, sizeof(buf)));
CHECK_AND_RET(test_nondebug_fs_probe("uprobe", (char *)argv[0],
uprobe_file_offset, 0x0, true,
BPF_FD_TYPE_UPROBE,
BPF_FD_TYPE_URETPROBE,
buf, sizeof(buf)));
/* test debug fs uprobe */
CHECK_AND_RET(test_debug_fs_uprobe((char *)argv[0], uprobe_file_offset,
false));
CHECK_AND_RET(test_debug_fs_uprobe((char *)argv[0], uprobe_file_offset,
true));
return 0;
}
|
dassmeta/weixin | dassmeta-weixin-web-home/src/main/java/com/dassmeta/weixin/web/home/util/WeixinAbstractHandler.java | <reponame>dassmeta/weixin
package com.dassmeta.weixin.web.home.util;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jdom2.JDOMException;
import com.dassmeta.weixin.web.home.vo.recv.WxRecvEventMsg;
import com.dassmeta.weixin.web.home.vo.recv.WxRecvGeoMsg;
import com.dassmeta.weixin.web.home.vo.recv.WxRecvLinkMsg;
import com.dassmeta.weixin.web.home.vo.recv.WxRecvMsg;
import com.dassmeta.weixin.web.home.vo.recv.WxRecvPicMsg;
import com.dassmeta.weixin.web.home.vo.recv.WxRecvTextMsg;
import com.dassmeta.weixin.web.home.vo.recv.WxRecvVideoMsg;
import com.dassmeta.weixin.web.home.vo.recv.WxRecvVoiceMsg;
import com.dassmeta.weixin.web.home.vo.send.WxSendMsg;
import com.dassmeta.weixin.web.home.vo.send.WxSendMusicMsg;
import com.dassmeta.weixin.web.home.vo.send.WxSendNewsMsg;
import com.dassmeta.weixin.web.home.vo.send.WxSendTextMsg;
/**
* 非线程安全 (应该每个请求创建一个) Created by 0x0001 on 14-9-28.
*/
public abstract class WeixinAbstractHandler {
private final HttpServletRequest req;
private final HttpServletResponse res;
private final String TOKEN;
private WxRecvMsg recvMsg;
public WeixinAbstractHandler(HttpServletRequest req, HttpServletResponse res, String token) {
this.req = req;
this.res = res;
this.TOKEN = token;
}
public void handler() {
if (!isFromWeiXin()) {
onNotFromWeixin();
return;
}
if (isWeixinVerifyURL()) {
renderText(getPara("echostr"));
return;
}
try {
WxRecvMsg msg = WeiXin.recv(req.getInputStream());
handler(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
// ------------------------------------------------------------------- protected Methods
protected void sendText(String content) {
WxSendMsg send = WeiXin.builderSendByRecv(this.recvMsg);
send(new WxSendTextMsg(send, content));
}
protected void sendNewsMsg(WxSendNewsMsg wxSendNewsMsg) {
send(wxSendNewsMsg);
}
protected void sendMusicMsg(String title, String desc, String music, String hqMusic) {
WxSendMsg send = WeiXin.builderSendByRecv(this.recvMsg);
send(new WxSendMusicMsg(send, title, desc, music, hqMusic));
}
protected WxSendNewsMsg buildNewsMsg() {
return new WxSendNewsMsg(WeiXin.builderSendByRecv(this.recvMsg));
}
protected void send(WxSendMsg send) {
try {
WeiXin.send(send, res.getOutputStream());
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected boolean isFromWeiXin() {
if (verifySignature()) {
return isWeixinVerifyURL() || isPost();
}
return false;
}
// ------------------------------------------------------------------- Abstract Methods
/**
* 收到图片消息
*
* @param msg
*/
protected abstract void onPic(WxRecvPicMsg msg);
/**
* 收到链接消息
*
* @param msg
*/
protected abstract void onLink(WxRecvLinkMsg msg);
/**
* 收到地址消息
*
* @param msg
*/
protected abstract void onGeo(WxRecvGeoMsg msg);
/**
* 收到文本消息
*
* @param msg
*/
protected abstract void onText(WxRecvTextMsg msg);
/**
* 收到事件消息
*
* @param msg
*/
protected abstract void onEvent(WxRecvEventMsg msg);
/**
* 语音消息
*
* @param msg
*/
protected abstract void onVoice(WxRecvVoiceMsg msg);
/**
* 视频消息
*
* @param msg
*/
protected abstract void onVideo(WxRecvVideoMsg msg);
/**
* 请求可能不是来自微信
*/
protected abstract void onNotFromWeixin();
// -------------------------------------------------------- Get Set
public HttpServletRequest getRequest() {
return req;
}
public HttpServletResponse getResponse() {
return res;
}
// -------------------------------------------------------- Private Methods
private boolean isPost() {
return "POST".equalsIgnoreCase(req.getMethod());
}
private boolean isWeixinVerifyURL() {
return getPara("echostr") != null;
}
private boolean verifySignature() {
String signature = getPara("signature");
String timestamp = getPara("timestamp");
String nonce = getPara("nonce");
if (null != timestamp && null != nonce && null != signature) {
return WeiXin.access(TOKEN, signature, timestamp, nonce);
}
return false;
}
private void handler(WxRecvMsg msg) {
this.recvMsg = msg;
if (msg instanceof WxRecvTextMsg) {
onText((WxRecvTextMsg) msg);
} else if (msg instanceof WxRecvEventMsg) {
onEvent((WxRecvEventMsg) msg);
} else if (msg instanceof WxRecvGeoMsg) {
onGeo((WxRecvGeoMsg) msg);
} else if (msg instanceof WxRecvLinkMsg) {
onLink((WxRecvLinkMsg) msg);
} else if (msg instanceof WxRecvPicMsg) {
onPic((WxRecvPicMsg) msg);
} else if (msg instanceof WxRecvVoiceMsg) {
onVoice((WxRecvVoiceMsg) msg);
} else if (msg instanceof WxRecvVideoMsg) {
onVideo((WxRecvVideoMsg) msg);
}
}
private String getPara(String key) {
return req.getParameter(key);
}
private void renderText(String text) {
try {
PrintWriter pw = res.getWriter();
pw.write(text);
pw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
byepolr/ErgoDox-EZ-Reactor | lib/firmware/keyboard/quark/backlight.h |
void backlight_init_ports(void);
|
wlhcode/lscct | src/L/L1401.cpp | #include<cstdio>
int main(){
long long x,y;
scanf("%lld %lld",&x,&y);
printf("%lld\n",(x*y)%10);
return 0;
}
|
ProvoK/concourse | skymarshal/token/tokenfakes/fake_middleware.go | <reponame>ProvoK/concourse<gh_stars>1-10
// Code generated by counterfeiter. DO NOT EDIT.
package tokenfakes
import (
"net/http"
"sync"
"time"
"github.com/concourse/concourse/skymarshal/token"
)
type FakeMiddleware struct {
GetTokenStub func(*http.Request) string
getTokenMutex sync.RWMutex
getTokenArgsForCall []struct {
arg1 *http.Request
}
getTokenReturns struct {
result1 string
}
getTokenReturnsOnCall map[int]struct {
result1 string
}
SetTokenStub func(http.ResponseWriter, string, time.Time) error
setTokenMutex sync.RWMutex
setTokenArgsForCall []struct {
arg1 http.ResponseWriter
arg2 string
arg3 time.Time
}
setTokenReturns struct {
result1 error
}
setTokenReturnsOnCall map[int]struct {
result1 error
}
UnsetTokenStub func(http.ResponseWriter)
unsetTokenMutex sync.RWMutex
unsetTokenArgsForCall []struct {
arg1 http.ResponseWriter
}
invocations map[string][][]interface{}
invocationsMutex sync.RWMutex
}
func (fake *FakeMiddleware) GetToken(arg1 *http.Request) string {
fake.getTokenMutex.Lock()
ret, specificReturn := fake.getTokenReturnsOnCall[len(fake.getTokenArgsForCall)]
fake.getTokenArgsForCall = append(fake.getTokenArgsForCall, struct {
arg1 *http.Request
}{arg1})
fake.recordInvocation("GetToken", []interface{}{arg1})
fake.getTokenMutex.Unlock()
if fake.GetTokenStub != nil {
return fake.GetTokenStub(arg1)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.getTokenReturns
return fakeReturns.result1
}
func (fake *FakeMiddleware) GetTokenCallCount() int {
fake.getTokenMutex.RLock()
defer fake.getTokenMutex.RUnlock()
return len(fake.getTokenArgsForCall)
}
func (fake *FakeMiddleware) GetTokenCalls(stub func(*http.Request) string) {
fake.getTokenMutex.Lock()
defer fake.getTokenMutex.Unlock()
fake.GetTokenStub = stub
}
func (fake *FakeMiddleware) GetTokenArgsForCall(i int) *http.Request {
fake.getTokenMutex.RLock()
defer fake.getTokenMutex.RUnlock()
argsForCall := fake.getTokenArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeMiddleware) GetTokenReturns(result1 string) {
fake.getTokenMutex.Lock()
defer fake.getTokenMutex.Unlock()
fake.GetTokenStub = nil
fake.getTokenReturns = struct {
result1 string
}{result1}
}
func (fake *FakeMiddleware) GetTokenReturnsOnCall(i int, result1 string) {
fake.getTokenMutex.Lock()
defer fake.getTokenMutex.Unlock()
fake.GetTokenStub = nil
if fake.getTokenReturnsOnCall == nil {
fake.getTokenReturnsOnCall = make(map[int]struct {
result1 string
})
}
fake.getTokenReturnsOnCall[i] = struct {
result1 string
}{result1}
}
func (fake *FakeMiddleware) SetToken(arg1 http.ResponseWriter, arg2 string, arg3 time.Time) error {
fake.setTokenMutex.Lock()
ret, specificReturn := fake.setTokenReturnsOnCall[len(fake.setTokenArgsForCall)]
fake.setTokenArgsForCall = append(fake.setTokenArgsForCall, struct {
arg1 http.ResponseWriter
arg2 string
arg3 time.Time
}{arg1, arg2, arg3})
fake.recordInvocation("SetToken", []interface{}{arg1, arg2, arg3})
fake.setTokenMutex.Unlock()
if fake.SetTokenStub != nil {
return fake.SetTokenStub(arg1, arg2, arg3)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.setTokenReturns
return fakeReturns.result1
}
func (fake *FakeMiddleware) SetTokenCallCount() int {
fake.setTokenMutex.RLock()
defer fake.setTokenMutex.RUnlock()
return len(fake.setTokenArgsForCall)
}
func (fake *FakeMiddleware) SetTokenCalls(stub func(http.ResponseWriter, string, time.Time) error) {
fake.setTokenMutex.Lock()
defer fake.setTokenMutex.Unlock()
fake.SetTokenStub = stub
}
func (fake *FakeMiddleware) SetTokenArgsForCall(i int) (http.ResponseWriter, string, time.Time) {
fake.setTokenMutex.RLock()
defer fake.setTokenMutex.RUnlock()
argsForCall := fake.setTokenArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}
func (fake *FakeMiddleware) SetTokenReturns(result1 error) {
fake.setTokenMutex.Lock()
defer fake.setTokenMutex.Unlock()
fake.SetTokenStub = nil
fake.setTokenReturns = struct {
result1 error
}{result1}
}
func (fake *FakeMiddleware) SetTokenReturnsOnCall(i int, result1 error) {
fake.setTokenMutex.Lock()
defer fake.setTokenMutex.Unlock()
fake.SetTokenStub = nil
if fake.setTokenReturnsOnCall == nil {
fake.setTokenReturnsOnCall = make(map[int]struct {
result1 error
})
}
fake.setTokenReturnsOnCall[i] = struct {
result1 error
}{result1}
}
func (fake *FakeMiddleware) UnsetToken(arg1 http.ResponseWriter) {
fake.unsetTokenMutex.Lock()
fake.unsetTokenArgsForCall = append(fake.unsetTokenArgsForCall, struct {
arg1 http.ResponseWriter
}{arg1})
fake.recordInvocation("UnsetToken", []interface{}{arg1})
fake.unsetTokenMutex.Unlock()
if fake.UnsetTokenStub != nil {
fake.UnsetTokenStub(arg1)
}
}
func (fake *FakeMiddleware) UnsetTokenCallCount() int {
fake.unsetTokenMutex.RLock()
defer fake.unsetTokenMutex.RUnlock()
return len(fake.unsetTokenArgsForCall)
}
func (fake *FakeMiddleware) UnsetTokenCalls(stub func(http.ResponseWriter)) {
fake.unsetTokenMutex.Lock()
defer fake.unsetTokenMutex.Unlock()
fake.UnsetTokenStub = stub
}
func (fake *FakeMiddleware) UnsetTokenArgsForCall(i int) http.ResponseWriter {
fake.unsetTokenMutex.RLock()
defer fake.unsetTokenMutex.RUnlock()
argsForCall := fake.unsetTokenArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeMiddleware) Invocations() map[string][][]interface{} {
fake.invocationsMutex.RLock()
defer fake.invocationsMutex.RUnlock()
fake.getTokenMutex.RLock()
defer fake.getTokenMutex.RUnlock()
fake.setTokenMutex.RLock()
defer fake.setTokenMutex.RUnlock()
fake.unsetTokenMutex.RLock()
defer fake.unsetTokenMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
for key, value := range fake.invocations {
copiedInvocations[key] = value
}
return copiedInvocations
}
func (fake *FakeMiddleware) recordInvocation(key string, args []interface{}) {
fake.invocationsMutex.Lock()
defer fake.invocationsMutex.Unlock()
if fake.invocations == nil {
fake.invocations = map[string][][]interface{}{}
}
if fake.invocations[key] == nil {
fake.invocations[key] = [][]interface{}{}
}
fake.invocations[key] = append(fake.invocations[key], args)
}
var _ token.Middleware = new(FakeMiddleware)
|
ck76/awesome-cs | Algorithm/coding_interviews/Python/sword-for-offer/31_valid_stack_seq.py | <filename>Algorithm/coding_interviews/Python/sword-for-offer/31_valid_stack_seq.py
#! /usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2019/3/9 10:58 PM
# @Author : xiaoliji
# @Email : <EMAIL>
"""
根据入栈和出栈顺序,判断是否能够清空该栈。
>>> pushed = [1, 2, 3, 4, 5]
>>> popped = [4, 5, 3, 2, 1]
>>> validateStackSequences(pushed, popped)
True
>>> validateStackSequences(pushed, [4, 3, 5, 1, 2])
False
"""
def validateStackSequences(pushed: 'List[int]', popped: 'List[int]') -> 'bool':
stack = []
j = 0
for num in pushed:
stack.append(num)
while stack and stack[-1] == popped[j]:
stack.pop()
j += 1
return j == len(popped) |
typa1/spring-boot | spring-boot-note5/src/main/java/me/loveshare/note5/data/util/ResourceUtils.java | package me.loveshare.note5.data.util;
import me.loveshare.note5.data.constant.SymbolConstants;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Tony on 2017/8/5.
* 资源辅助工具类
*/
public class ResourceUtils {
/**
* 文件类型:1.视频 2.音频 3.图片 4.压缩文件 5:办公文件
*/
public static final Map<Byte, String> TYPE = new HashMap<Byte, String>(10);
/**
* 文件平台来源:1.家庭 2.学校 3.公司 4.户外
*/
public static final Map<Byte, String> SOURCE = new HashMap<Byte, String>(10);
public static final String DISK_PREFIX = "resources";
//私有默认打开时长
public static final int OWNED_URL_MINUTES = 5;
/**
* 1.视频
*/
public static final byte VIDEO = 1;
/**
* 2.音频
*/
public static final byte VOICE = 2;
/**
* 3.图片
*/
public static final byte IMAGE = 3;
/**
* 4.压缩文件
*/
public static final byte ZIP = 4;
/**
* 5:办公文件
*/
public static final byte OFFICE = 5;
/**
* 5:默认
*/
public static final byte DEFAULTT = 6;
/**
* 1.家庭
*/
public static final byte FAMILY = 1;
/**
* 2.学校
*/
public static final byte SCHOOL = 2;
/**
* 3.公司
*/
public static final byte COMPANY = 3;
/**
* 4.户外
*/
public static final byte OUTDOORS = 4;
/**
* 5.默认
*/
public static final byte DEFAULTS = 4;
static {
TYPE.put(VIDEO, "wmv,wm,asf,asx,rm,rmvb,ra,ram,mpg,mpeg,mpe,vob,dat,mov,3gp,mp4,mp4v,m4v,mkv,avi,flv,f4v");
TYPE.put(VOICE, "wav,aif,au,mp3,ram,wma,mmf,amr,aac,flac");
TYPE.put(IMAGE, "bmp,jpg,dib,jpeg,png,jfif,jpe,tif,tiff,gif,tgp");
TYPE.put(ZIP, "rar,zip,7z,gz,arj,z,xz,iso,exe,dmg");
TYPE.put(OFFICE, "ppt,pptx,doc,docx,xls,xlsx,pdf,txt");
TYPE.put(OFFICE, "ppt,pptx,doc,docx,xls,xlsx,pdf,txt");
TYPE.put(DEFAULTT, "defaultt");
SOURCE.put(FAMILY, "family");
SOURCE.put(SCHOOL, "school");
SOURCE.put(COMPANY, "company");
SOURCE.put(OUTDOORS, "outdoors");
SOURCE.put(DEFAULTS, "defaults");
}
/**
* 获取文件夹路径: resources/family/jpeg/20170519/
*/
public static final String disk(Byte source, String suffix) {
StringBuilder su = new StringBuilder(39);
su.append(DISK_PREFIX).append(SymbolConstants.SPRIT);
su.append(platform(source)).append(SymbolConstants.SPRIT);
su.append(suffix).append(SymbolConstants.SPRIT);
su.append(date()).append(SymbolConstants.SPRIT);
return su.toString();
}
/**
* UUID随机生产文件名: 21792dd7bcae443d846a1ec19a115054.jpeg
*/
public static final String file(String uuid, String suffix) {
return new StringBuilder(37).append(uuid).append(SymbolConstants.DOT).append(suffix).toString();
}
/**
* 获取文件名:kaka.jpeg -> kaka
*/
public static final String name(String fileName) {
if (StringUtils.isEmpty(fileName) || fileName.indexOf(SymbolConstants.DOT) < 0) return SymbolConstants.EMPTY;
return fileName.substring(0, fileName.lastIndexOf(SymbolConstants.DOT)).toLowerCase();
}
/**
* 获取文件的扩展名:kaka.jpeg -> jpeg
*/
public static final String suffix(String name) {
if (StringUtils.isEmpty(name) || name.indexOf(SymbolConstants.DOT) < 0) return SymbolConstants.EMPTY;
return name.substring(name.lastIndexOf(SymbolConstants.DOT) + 1).toLowerCase();
}
/**
* 资源云OSS存储地址url:
*/
public static String url(String ossUrl, String diskName, String fileName) {
return new StringBuilder(128).append(ossUrl).append(diskName).append(fileName).toString();
}
/**
* 获取来源平台: family
*/
public static final String platform(Byte source) {
return SOURCE.get(source);
}
/**
* 获取当天的日期: 20170519
*/
public static final String date() {
return LocalDate.now().toString().replace(SymbolConstants.HLINE, "");
}
/**
* 获取当天的日期+时间(毫秒): 20170522161106540
*/
public static final String time() {
String time = new StringBuilder(22).append(LocalDate.now()).append(LocalTime.now()).toString();
time = time.replace(SymbolConstants.HLINE, "").replace(SymbolConstants.COLON, "").replace(SymbolConstants.DOT, "");
return time;
}
/**
* UUID随机数: 21792dd7bcae443d846a1ec19a115054
*/
public static final String uuid() {
return UUIDUtils.uuid();
}
/**
* 判断文件扩展名是否合法
*/
public static final boolean next(Byte type, String suffix) {
if (type == null) {
return TYPE.containsValue(suffix);
} else {
if (TYPE.get(type) == null) {
return false;
} else {
return TYPE.get(type).contains(suffix);
}
}
}
/**
* 通过文件的名获取type
*/
public static final byte type(String name) {
if (StringUtils.isEmpty(name) || name.indexOf(SymbolConstants.DOT) < 0) return 0;
String suffix = name.substring(name.lastIndexOf(SymbolConstants.DOT) + 1).toLowerCase();
for (Map.Entry<Byte, String> entry : TYPE.entrySet()) {
if (entry.getValue().contains(suffix)) {
return entry.getKey();
}
}
return 0;
}
}
|
AleksandrSidorov/react-fb-chat | app/containers/MessageInput/constants.js | <filename>app/containers/MessageInput/constants.js<gh_stars>0
/*
*
* MessageInput constants
*
*/
export const CHANGE_MESSAGE = 'app/MessageInput/CHANGE_MESSAGE'
export const CLEAR_MESSAGE_INPUT = 'app/MessageInput/CLEAR_MESSAGE_INPUT'
|
zihadboss/UVA-Solutions | 12250 Language Detection.cpp | <reponame>zihadboss/UVA-Solutions<gh_stars>10-100
#include <cstdio>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string current;
int t = 1;
cin >> current;
while (current != "#")
{
printf("Case %d: ", t);
if (current == "HELLO")
printf("ENGLISH\n");
else if (current == "HOLA")
printf("SPANISH\n");
else if (current == "HALLO")
printf("GERMAN\n");
else if (current == "BONJOUR")
printf("FRENCH\n");
else if (current == "CIAO")
printf("ITALIAN\n");
else if (current == "ZDRAVSTVUJTE")
printf("RUSSIAN\n");
else
printf("UNKNOWN\n");
++t;
cin >> current;
}
} |
1065672644894730302/Chromium | chrome/browser/policy/device_policy_cache.cc | <filename>chrome/browser/policy/device_policy_cache.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/policy/device_policy_cache.h"
#include <limits>
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/values.h"
#include "chrome/browser/chromeos/cros_settings.h"
#include "chrome/browser/chromeos/login/authenticator.h"
#include "chrome/browser/chromeos/login/ownership_service.h"
#include "chrome/browser/chromeos/login/signed_settings_helper.h"
#include "chrome/browser/policy/app_pack_updater.h"
#include "chrome/browser/policy/cloud_policy_data_store.h"
#include "chrome/browser/policy/enterprise_install_attributes.h"
#include "chrome/browser/policy/enterprise_metrics.h"
#include "chrome/browser/policy/policy_map.h"
#include "chrome/browser/policy/proto/device_management_backend.pb.h"
#include "chrome/browser/policy/proto/device_management_local.pb.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/update_engine_client.h"
#include "policy/policy_constants.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
using google::protobuf::RepeatedField;
using google::protobuf::RepeatedPtrField;
namespace em = enterprise_management;
namespace {
// Stores policy, updates the owner key if required and reports the status
// through a callback.
class StorePolicyOperation : public chromeos::OwnerManager::KeyUpdateDelegate {
public:
typedef base::Callback<void(chromeos::SignedSettings::ReturnCode)> Callback;
StorePolicyOperation(chromeos::SignedSettingsHelper* signed_settings_helper,
const em::PolicyFetchResponse& policy,
const Callback& callback)
: signed_settings_helper_(signed_settings_helper),
policy_(policy),
callback_(callback),
weak_ptr_factory_(this) {
signed_settings_helper_->StartStorePolicyOp(
policy,
base::Bind(&StorePolicyOperation::OnStorePolicyCompleted,
weak_ptr_factory_.GetWeakPtr()));
}
virtual ~StorePolicyOperation() {
}
void OnStorePolicyCompleted(chromeos::SignedSettings::ReturnCode code) {
if (code != chromeos::SignedSettings::SUCCESS) {
callback_.Run(code);
delete this;
return;
}
if (policy_.has_new_public_key()) {
// The session manager has successfully done a key rotation. Replace the
// owner key also in chrome.
const std::string& new_key = policy_.new_public_key();
const std::vector<uint8> new_key_data(new_key.c_str(),
new_key.c_str() + new_key.size());
chromeos::OwnershipService::GetSharedInstance()->StartUpdateOwnerKey(
new_key_data, this);
return;
} else {
chromeos::CrosSettings::Get()->ReloadProviders();
callback_.Run(chromeos::SignedSettings::SUCCESS);
delete this;
return;
}
}
// OwnerManager::KeyUpdateDelegate implementation:
virtual void OnKeyUpdated() OVERRIDE {
chromeos::CrosSettings::Get()->ReloadProviders();
callback_.Run(chromeos::SignedSettings::SUCCESS);
delete this;
}
private:
chromeos::SignedSettingsHelper* signed_settings_helper_;
em::PolicyFetchResponse policy_;
Callback callback_;
base::WeakPtrFactory<StorePolicyOperation> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(StorePolicyOperation);
};
// Decodes a protobuf integer to an IntegerValue. The caller assumes ownership
// of the return Value*. Returns NULL in case the input value is out of bounds.
Value* DecodeIntegerValue(google::protobuf::int64 value) {
if (value < std::numeric_limits<int>::min() ||
value > std::numeric_limits<int>::max()) {
LOG(WARNING) << "Integer value " << value
<< " out of numeric limits, ignoring.";
return NULL;
}
return Value::CreateIntegerValue(static_cast<int>(value));
}
Value* DecodeConnectionType(int value) {
static const char* const kConnectionTypes[] = {
flimflam::kTypeEthernet,
flimflam::kTypeWifi,
flimflam::kTypeWimax,
flimflam::kTypeBluetooth,
flimflam::kTypeCellular,
};
if (value < 0 || value >= static_cast<int>(arraysize(kConnectionTypes)))
return NULL;
return Value::CreateStringValue(kConnectionTypes[value]);
}
} // namespace
namespace policy {
DevicePolicyCache::DevicePolicyCache(
CloudPolicyDataStore* data_store,
EnterpriseInstallAttributes* install_attributes)
: data_store_(data_store),
install_attributes_(install_attributes),
signed_settings_helper_(chromeos::SignedSettingsHelper::Get()),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)),
policy_fetch_pending_(false) {
}
DevicePolicyCache::DevicePolicyCache(
CloudPolicyDataStore* data_store,
EnterpriseInstallAttributes* install_attributes,
chromeos::SignedSettingsHelper* signed_settings_helper)
: data_store_(data_store),
install_attributes_(install_attributes),
signed_settings_helper_(signed_settings_helper),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)),
policy_fetch_pending_(false) {
}
DevicePolicyCache::~DevicePolicyCache() {
}
void DevicePolicyCache::Load() {
signed_settings_helper_->StartRetrievePolicyOp(
base::Bind(&DevicePolicyCache::OnRetrievePolicyCompleted,
weak_ptr_factory_.GetWeakPtr()));
}
bool DevicePolicyCache::SetPolicy(const em::PolicyFetchResponse& policy) {
DCHECK(IsReady());
// Make sure we have an enterprise device.
std::string registration_user(install_attributes_->GetRegistrationUser());
if (registration_user.empty()) {
LOG(WARNING) << "Refusing to accept policy on non-enterprise device.";
UMA_HISTOGRAM_ENUMERATION(kMetricPolicy,
kMetricPolicyFetchNonEnterpriseDevice,
kMetricPolicySize);
InformNotifier(CloudPolicySubsystem::LOCAL_ERROR,
CloudPolicySubsystem::POLICY_LOCAL_ERROR);
return false;
}
// Check the user this policy is for against the device-locked name.
em::PolicyData policy_data;
if (!policy_data.ParseFromString(policy.policy_data())) {
LOG(WARNING) << "Invalid policy protobuf";
UMA_HISTOGRAM_ENUMERATION(kMetricPolicy, kMetricPolicyFetchInvalidPolicy,
kMetricPolicySize);
InformNotifier(CloudPolicySubsystem::LOCAL_ERROR,
CloudPolicySubsystem::POLICY_LOCAL_ERROR);
return false;
}
// Existing installations may not have a canonicalized version of the
// registration user name in install attributes, so re-canonicalize here.
if (chromeos::Authenticator::Canonicalize(registration_user) !=
chromeos::Authenticator::Canonicalize(policy_data.username())) {
LOG(WARNING) << "Refusing policy blob for " << policy_data.username()
<< " which doesn't match " << registration_user;
UMA_HISTOGRAM_ENUMERATION(kMetricPolicy, kMetricPolicyFetchUserMismatch,
kMetricPolicySize);
InformNotifier(CloudPolicySubsystem::LOCAL_ERROR,
CloudPolicySubsystem::POLICY_LOCAL_ERROR);
return false;
}
set_last_policy_refresh_time(base::Time::NowFromSystemTime());
// Start a store operation.
StorePolicyOperation::Callback callback =
base::Bind(&DevicePolicyCache::PolicyStoreOpCompleted,
weak_ptr_factory_.GetWeakPtr());
new StorePolicyOperation(signed_settings_helper_, policy, callback);
policy_fetch_pending_ = true;
return true;
}
void DevicePolicyCache::SetUnmanaged() {
LOG(WARNING) << "Tried to set DevicePolicyCache to 'unmanaged'!";
// This is not supported for DevicePolicyCache.
}
void DevicePolicyCache::SetFetchingDone() {
// Don't send the notification just yet if there is a pending policy
// store/reload cycle.
if (!policy_fetch_pending_)
CloudPolicyCacheBase::SetFetchingDone();
}
void DevicePolicyCache::OnRetrievePolicyCompleted(
chromeos::SignedSettings::ReturnCode code,
const em::PolicyFetchResponse& policy) {
DCHECK(CalledOnValidThread());
if (!IsReady()) {
std::string device_token;
InstallInitialPolicy(code, policy, &device_token);
SetTokenAndFlagReady(device_token);
} else { // In other words, IsReady() == true
if (code != chromeos::SignedSettings::SUCCESS) {
if (code == chromeos::SignedSettings::BAD_SIGNATURE) {
UMA_HISTOGRAM_ENUMERATION(kMetricPolicy, kMetricPolicyFetchBadSignature,
kMetricPolicySize);
InformNotifier(CloudPolicySubsystem::LOCAL_ERROR,
CloudPolicySubsystem::SIGNATURE_MISMATCH);
} else {
UMA_HISTOGRAM_ENUMERATION(kMetricPolicy, kMetricPolicyFetchOtherFailed,
kMetricPolicySize);
InformNotifier(CloudPolicySubsystem::LOCAL_ERROR,
CloudPolicySubsystem::POLICY_LOCAL_ERROR);
}
} else {
bool ok = SetPolicyInternal(policy, NULL, false);
if (ok) {
UMA_HISTOGRAM_ENUMERATION(kMetricPolicy, kMetricPolicyFetchOK,
kMetricPolicySize);
}
}
}
CheckFetchingDone();
}
bool DevicePolicyCache::DecodePolicyData(const em::PolicyData& policy_data,
PolicyMap* policies) {
em::ChromeDeviceSettingsProto policy;
if (!policy.ParseFromString(policy_data.policy_value())) {
LOG(WARNING) << "Failed to parse ChromeDeviceSettingsProto.";
return false;
}
DecodeDevicePolicy(policy, policies);
return true;
}
void DevicePolicyCache::PolicyStoreOpCompleted(
chromeos::SignedSettings::ReturnCode code) {
DCHECK(CalledOnValidThread());
if (code != chromeos::SignedSettings::SUCCESS) {
UMA_HISTOGRAM_ENUMERATION(kMetricPolicy, kMetricPolicyStoreFailed,
kMetricPolicySize);
if (code == chromeos::SignedSettings::BAD_SIGNATURE) {
UMA_HISTOGRAM_ENUMERATION(kMetricPolicy, kMetricPolicyFetchBadSignature,
kMetricPolicySize);
InformNotifier(CloudPolicySubsystem::LOCAL_ERROR,
CloudPolicySubsystem::SIGNATURE_MISMATCH);
} else {
UMA_HISTOGRAM_ENUMERATION(kMetricPolicy, kMetricPolicyFetchOtherFailed,
kMetricPolicySize);
InformNotifier(CloudPolicySubsystem::LOCAL_ERROR,
CloudPolicySubsystem::POLICY_LOCAL_ERROR);
}
CheckFetchingDone();
return;
}
UMA_HISTOGRAM_ENUMERATION(kMetricPolicy, kMetricPolicyStoreSucceeded,
kMetricPolicySize);
signed_settings_helper_->StartRetrievePolicyOp(
base::Bind(&DevicePolicyCache::OnRetrievePolicyCompleted,
weak_ptr_factory_.GetWeakPtr()));
}
void DevicePolicyCache::InstallInitialPolicy(
chromeos::SignedSettings::ReturnCode code,
const em::PolicyFetchResponse& policy,
std::string* device_token) {
if (code == chromeos::SignedSettings::NOT_FOUND ||
code == chromeos::SignedSettings::KEY_UNAVAILABLE ||
!policy.has_policy_data()) {
InformNotifier(CloudPolicySubsystem::UNENROLLED,
CloudPolicySubsystem::NO_DETAILS);
return;
}
em::PolicyData policy_data;
if (!policy_data.ParseFromString(policy.policy_data())) {
LOG(WARNING) << "Failed to parse PolicyData protobuf.";
UMA_HISTOGRAM_ENUMERATION(kMetricPolicy, kMetricPolicyLoadFailed,
kMetricPolicySize);
InformNotifier(CloudPolicySubsystem::LOCAL_ERROR,
CloudPolicySubsystem::POLICY_LOCAL_ERROR);
return;
}
if (!policy_data.has_request_token() ||
policy_data.request_token().empty()) {
SetUnmanagedInternal(base::Time::NowFromSystemTime());
InformNotifier(CloudPolicySubsystem::UNMANAGED,
CloudPolicySubsystem::NO_DETAILS);
// TODO(jkummerow): Reminder: When we want to feed device-wide settings
// made by a local owner into this cache, we need to call
// SetPolicyInternal() here.
return;
}
if (!policy_data.has_username() || !policy_data.has_device_id()) {
UMA_HISTOGRAM_ENUMERATION(kMetricPolicy, kMetricPolicyLoadFailed,
kMetricPolicySize);
InformNotifier(CloudPolicySubsystem::LOCAL_ERROR,
CloudPolicySubsystem::POLICY_LOCAL_ERROR);
return;
}
UMA_HISTOGRAM_ENUMERATION(kMetricPolicy, kMetricPolicyLoadSucceeded,
kMetricPolicySize);
data_store_->set_user_name(policy_data.username());
data_store_->set_device_id(policy_data.device_id());
*device_token = policy_data.request_token();
base::Time timestamp;
if (SetPolicyInternal(policy, ×tamp, true))
set_last_policy_refresh_time(timestamp);
}
void DevicePolicyCache::SetTokenAndFlagReady(const std::string& device_token) {
// Wait for device settings to become available.
if (chromeos::CrosSettingsProvider::TRUSTED !=
chromeos::CrosSettings::Get()->PrepareTrustedValues(
base::Bind(&DevicePolicyCache::SetTokenAndFlagReady,
weak_ptr_factory_.GetWeakPtr(),
device_token))) {
return;
}
// We need to call SetDeviceToken unconditionally to indicate the cache has
// finished loading.
data_store_->SetDeviceToken(device_token, true);
SetReady();
}
void DevicePolicyCache::CheckFetchingDone() {
if (policy_fetch_pending_) {
CloudPolicyCacheBase::SetFetchingDone();
policy_fetch_pending_ = false;
}
}
void DevicePolicyCache::DecodeDevicePolicy(
const em::ChromeDeviceSettingsProto& policy,
PolicyMap* policies) {
// Decode the various groups of policies.
DecodeLoginPolicies(policy, policies);
DecodeKioskPolicies(policy, policies, install_attributes_);
DecodeNetworkPolicies(policy, policies, install_attributes_);
DecodeReportingPolicies(policy, policies);
DecodeAutoUpdatePolicies(policy, policies);
DecodeGenericPolicies(policy, policies);
}
// static
void DevicePolicyCache::DecodeLoginPolicies(
const em::ChromeDeviceSettingsProto& policy,
PolicyMap* policies) {
if (policy.has_guest_mode_enabled()) {
const em::GuestModeEnabledProto& container(policy.guest_mode_enabled());
if (container.has_guest_mode_enabled()) {
policies->Set(key::kDeviceGuestModeEnabled,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateBooleanValue(container.guest_mode_enabled()));
}
}
if (policy.has_show_user_names()) {
const em::ShowUserNamesOnSigninProto& container(policy.show_user_names());
if (container.has_show_user_names()) {
policies->Set(key::kDeviceShowUserNamesOnSignin,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateBooleanValue(container.show_user_names()));
}
}
if (policy.has_allow_new_users()) {
const em::AllowNewUsersProto& container(policy.allow_new_users());
if (container.has_allow_new_users()) {
policies->Set(key::kDeviceAllowNewUsers,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateBooleanValue(container.allow_new_users()));
}
}
if (policy.has_user_whitelist()) {
const em::UserWhitelistProto& container(policy.user_whitelist());
if (container.user_whitelist_size()) {
ListValue* whitelist = new ListValue();
RepeatedPtrField<std::string>::const_iterator entry;
for (entry = container.user_whitelist().begin();
entry != container.user_whitelist().end();
++entry) {
whitelist->Append(Value::CreateStringValue(*entry));
}
policies->Set(key::kDeviceUserWhitelist,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
whitelist);
}
}
if (policy.has_ephemeral_users_enabled()) {
const em::EphemeralUsersEnabledProto& container(
policy.ephemeral_users_enabled());
if (container.has_ephemeral_users_enabled()) {
policies->Set(key::kDeviceEphemeralUsersEnabled,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateBooleanValue(
container.ephemeral_users_enabled()));
}
}
}
// static
void DevicePolicyCache::DecodeKioskPolicies(
const em::ChromeDeviceSettingsProto& policy,
PolicyMap* policies,
EnterpriseInstallAttributes* install_attributes) {
// No policies if this is not KIOSK.
if (install_attributes->GetMode() != DEVICE_MODE_KIOSK)
return;
if (policy.has_forced_logout_timeouts()) {
const em::ForcedLogoutTimeoutsProto& container(
policy.forced_logout_timeouts());
if (container.has_idle_logout_timeout()) {
policies->Set(key::kDeviceIdleLogoutTimeout,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
DecodeIntegerValue(container.idle_logout_timeout()));
}
if (container.has_idle_logout_warning_duration()) {
policies->Set(key::kDeviceIdleLogoutWarningDuration,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
DecodeIntegerValue(
container.idle_logout_warning_duration()));
}
}
if (policy.has_login_screen_saver()) {
const em::ScreenSaverProto& container(
policy.login_screen_saver());
if (container.has_screen_saver_extension_id()) {
policies->Set(key::kDeviceLoginScreenSaverId,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateStringValue(
container.screen_saver_extension_id()));
}
if (container.has_screen_saver_timeout()) {
policies->Set(key::kDeviceLoginScreenSaverTimeout,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
DecodeIntegerValue(container.screen_saver_timeout()));
}
}
if (policy.has_app_pack()) {
const em::AppPackProto& container(policy.app_pack());
base::ListValue* app_pack_list = new base::ListValue();
for (int i = 0; i < container.app_pack_size(); ++i) {
const em::AppPackEntryProto& entry(container.app_pack(i));
if (entry.has_extension_id() && entry.has_update_url()) {
base::DictionaryValue* dict = new base::DictionaryValue();
dict->SetString(AppPackUpdater::kExtensionId, entry.extension_id());
dict->SetString(AppPackUpdater::kUpdateUrl, entry.update_url());
app_pack_list->Append(dict);
}
}
policies->Set(key::kDeviceAppPack,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
app_pack_list);
}
if (policy.has_pinned_apps()) {
const em::PinnedAppsProto& container(policy.pinned_apps());
base::ListValue* pinned_apps_list = new base::ListValue();
for (int i = 0; i < container.app_id_size(); ++i)
pinned_apps_list->Append(Value::CreateStringValue(container.app_id(i)));
policies->Set(key::kPinnedLauncherApps,
POLICY_LEVEL_RECOMMENDED,
POLICY_SCOPE_MACHINE,
pinned_apps_list);
}
}
// static
void DevicePolicyCache::DecodeNetworkPolicies(
const em::ChromeDeviceSettingsProto& policy,
PolicyMap* policies,
EnterpriseInstallAttributes* install_attributes) {
if (policy.has_device_proxy_settings()) {
const em::DeviceProxySettingsProto& container(
policy.device_proxy_settings());
scoped_ptr<DictionaryValue> proxy_settings(new DictionaryValue);
if (container.has_proxy_mode())
proxy_settings->SetString(key::kProxyMode, container.proxy_mode());
if (container.has_proxy_server())
proxy_settings->SetString(key::kProxyServer, container.proxy_server());
if (container.has_proxy_pac_url())
proxy_settings->SetString(key::kProxyPacUrl, container.proxy_pac_url());
if (container.has_proxy_bypass_list()) {
proxy_settings->SetString(key::kProxyBypassList,
container.proxy_bypass_list());
}
// Figure out the level. Proxy policy is mandatory in kiosk mode.
PolicyLevel level = POLICY_LEVEL_RECOMMENDED;
if (install_attributes->GetMode() == DEVICE_MODE_KIOSK)
level = POLICY_LEVEL_MANDATORY;
if (!proxy_settings->empty()) {
policies->Set(key::kProxySettings,
level,
POLICY_SCOPE_MACHINE,
proxy_settings.release());
}
}
if (policy.has_data_roaming_enabled()) {
const em::DataRoamingEnabledProto& container(policy.data_roaming_enabled());
if (container.has_data_roaming_enabled()) {
policies->Set(key::kDeviceDataRoamingEnabled,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateBooleanValue(
container.data_roaming_enabled()));
}
}
if (policy.has_open_network_configuration() &&
policy.open_network_configuration().has_open_network_configuration()) {
std::string config(
policy.open_network_configuration().open_network_configuration());
policies->Set(key::kDeviceOpenNetworkConfiguration,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateStringValue(config));
}
}
// static
void DevicePolicyCache::DecodeReportingPolicies(
const em::ChromeDeviceSettingsProto& policy,
PolicyMap* policies) {
if (policy.has_device_reporting()) {
const em::DeviceReportingProto& container(policy.device_reporting());
if (container.has_report_version_info()) {
policies->Set(key::kReportDeviceVersionInfo,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateBooleanValue(container.report_version_info()));
}
if (container.has_report_activity_times()) {
policies->Set(key::kReportDeviceActivityTimes,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateBooleanValue(
container.report_activity_times()));
}
if (container.has_report_boot_mode()) {
policies->Set(key::kReportDeviceBootMode,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateBooleanValue(container.report_boot_mode()));
}
if (container.has_report_location()) {
policies->Set(key::kReportDeviceLocation,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateBooleanValue(container.report_location()));
}
}
}
// static
void DevicePolicyCache::DecodeAutoUpdatePolicies(
const em::ChromeDeviceSettingsProto& policy,
PolicyMap* policies) {
if (policy.has_release_channel()) {
const em::ReleaseChannelProto& container(policy.release_channel());
if (container.has_release_channel()) {
std::string channel(container.release_channel());
policies->Set(key::kChromeOsReleaseChannel,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateStringValue(channel));
// TODO(dubroy): Once http://crosbug.com/17015 is implemented, we won't
// have to pass the channel in here, only ping the update engine to tell
// it to fetch the channel from the policy.
chromeos::DBusThreadManager::Get()->GetUpdateEngineClient()->
SetReleaseTrack(channel);
}
if (container.has_release_channel_delegated()) {
policies->Set(key::kChromeOsReleaseChannelDelegated,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateBooleanValue(
container.release_channel_delegated()));
}
}
if (policy.has_auto_update_settings()) {
const em::AutoUpdateSettingsProto& container(policy.auto_update_settings());
if (container.has_update_disabled()) {
policies->Set(key::kDeviceAutoUpdateDisabled,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateBooleanValue(container.update_disabled()));
}
if (container.has_target_version_prefix()) {
policies->Set(key::kDeviceTargetVersionPrefix,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateStringValue(
container.target_version_prefix()));
}
// target_version_display_name is not actually a policy, but a display
// string for target_version_prefix, so we ignore it.
if (container.has_scatter_factor_in_seconds()) {
policies->Set(key::kDeviceUpdateScatterFactor,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateIntegerValue(
container.scatter_factor_in_seconds()));
}
if (container.allowed_connection_types_size()) {
ListValue* allowed_connection_types = new ListValue();
RepeatedField<int>::const_iterator entry;
for (entry = container.allowed_connection_types().begin();
entry != container.allowed_connection_types().end();
++entry) {
base::Value* value = DecodeConnectionType(*entry);
if (value)
allowed_connection_types->Append(value);
}
policies->Set(key::kDeviceUpdateAllowedConnectionTypes,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
allowed_connection_types);
}
}
}
// static
void DevicePolicyCache::DecodeGenericPolicies(
const em::ChromeDeviceSettingsProto& policy,
PolicyMap* policies) {
if (policy.has_device_policy_refresh_rate()) {
const em::DevicePolicyRefreshRateProto& container(
policy.device_policy_refresh_rate());
if (container.has_device_policy_refresh_rate()) {
policies->Set(key::kDevicePolicyRefreshRate,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
DecodeIntegerValue(container.device_policy_refresh_rate()));
}
}
if (policy.has_metrics_enabled()) {
const em::MetricsEnabledProto& container(policy.metrics_enabled());
if (container.has_metrics_enabled()) {
policies->Set(key::kDeviceMetricsReportingEnabled,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
Value::CreateBooleanValue(container.metrics_enabled()));
}
}
if (policy.has_start_up_urls()) {
const em::StartUpUrlsProto& container(policy.start_up_urls());
if (container.start_up_urls_size()) {
ListValue* urls = new ListValue();
RepeatedPtrField<std::string>::const_iterator entry;
for (entry = container.start_up_urls().begin();
entry != container.start_up_urls().end();
++entry) {
urls->Append(Value::CreateStringValue(*entry));
}
policies->Set(key::kDeviceStartUpUrls,
POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_MACHINE,
urls);
}
}
}
} // namespace policy
|
czack810150/Markus | app/controllers/api/grade_entry_forms_controller.rb | module Api
class GradeEntryFormsController < MainApiController
# Sends the contents of the specified grade entry form
# Requires: id
def show
grade_entry_form = GradeEntryForm.find(params[:id])
send_data grade_entry_form.export_as_csv,
type: 'text/csv',
filename: "#{grade_entry_form.short_identifier}_grades_report.csv",
disposition: 'inline'
rescue ActiveRecord::RecordNotFound => e
# could not find grade entry form
render 'shared/http_status', locals: { code: '404', message: e }, status: 404
end
end
end
|
mibutec/jnet | src/test/java/org/jnet/core/GameClientTest.java | package org.jnet.core;
import static org.mockito.Matchers.any;
import junit.framework.Assert;
import org.jnet.core.connection.Connection;
import org.jnet.core.connection.messages.NewStateMessage;
import org.jnet.core.synchronizer.ObjectId;
import org.jnet.core.testdata.FigureState;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
public class GameClientTest {
private int serverTime = 0;
private GameClient client;
@Before
public void setup() {
serverTime = 0;
client = new GameClient() {
@Override
public int serverTime() {
return serverTime;
}
};
client.connect(Mockito.mock(Connection.class));
}
@Test
public void testNewState() throws Exception {
// the entity on that we want to test
FigureState state = client.createProxy(new FigureState());
ObjectId id = client.getIdForProxy(state);
// server sends a new state
FigureState newState = new FigureState();
newState.setTargetX(500);
client.handleNewState(id, 0, new NewStateMessage(id, 0, client.getMetaDataManager().get(FigureState.class), newState).getStateAsMap());
// client reacts on that new state
serverTime = 1000;
Assert.assertEquals(50f, state.getX());
}
@Test
public void testNewStateCanBeOverwritten() throws Exception {
// the entity on that we want to test
FigureState state = client.createProxy(new FigureState());
ObjectId id = client.getIdForProxy(state);
// create a new event in eventqueue
serverTime = 1000;
state.gotoX(1000);
serverTime = 2000;
Assert.assertEquals(50f, state.getX());
// let the "server" send a state in timeline before the last client event
// that will be overwritten by the clients request in the future
FigureState newState = new FigureState();
newState.setTargetX(10);
client.handleNewState(id, 0, new NewStateMessage(id, 0, client.getMetaDataManager().get(FigureState.class), newState).getStateAsMap());
Assert.assertEquals(60f, state.getX());
}
@Test
public void testCallsToServer() throws Exception {
Connection serverConnection = Mockito.mock(Connection.class);
GameClient client = new GameClient();
client.connect(serverConnection);
FigureState state = client.createProxy(new FigureState());
Assert.assertEquals(0.0f, state.getX());
Mockito.verify(serverConnection, Mockito.never()).send(any());
state.update(42);
Mockito.verify(serverConnection, Mockito.never()).send(any());
state.gotoX(42);
Mockito.verify(serverConnection, Mockito.times(1)).send(any());
client.close();
}
}
|
tylerslaton/api | vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/surroundingobject.go | <filename>vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/surroundingobject.go<gh_stars>1000+
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package defaulting
import (
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// AccessorFunc returns a node x in obj on a fixed (implicitly encoded) JSON path
// if that path exists in obj (found==true). If it does not exist, found is false.
// If on the path the type of a field is wrong, an error is returned.
type AccessorFunc func(obj map[string]interface{}) (x interface{}, found bool, err error)
// SurroundingObjectFunc is a surrounding object builder with a given x at a leaf.
// Which leave is determined by the series of Index() and Child(k) calls.
// It also returns the inverse of the builder, namely the accessor that extracts x
// from the test object.
//
// With obj, acc, _ := someSurroundingObjectFunc(x) we get:
//
// acc(obj) == x
// reflect.DeepEqual(acc(DeepCopy(obj), x) == x
//
// where x is the original instance for slices and maps.
//
// If after computation of acc the node holding x in obj is mutated (e.g. pruned),
// the accessor will return that mutated node value (e.g. the pruned x).
//
// Example (ignoring the last two return values):
//
// NewRootObjectFunc()(x) == x
// NewRootObjectFunc().Index()(x) == [x]
// NewRootObjectFunc().Index().Child("foo") == [{"foo": x}]
// NewRootObjectFunc().Index().Child("foo").Child("bar") == [{"foo": {"bar":x}}]
// NewRootObjectFunc().Index().Child("foo").Child("bar").Index() == [{"foo": {"bar":[x]}}]
//
// and:
//
// NewRootObjectFunc(), then acc(x) == x
// NewRootObjectFunc().Index(), then acc([x]) == x
// NewRootObjectFunc().Index().Child("foo"), then acc([{"foo": x}]) == x
// NewRootObjectFunc().Index().Child("foo").Child("bar"), then acc([{"foo": {"bar":x}}]) == x
// NewRootObjectFunc().Index().Child("foo").Child("bar").Index(), then acc([{"foo": {"bar":[x]}}]) == x
type SurroundingObjectFunc func(focus interface{}) (map[string]interface{}, AccessorFunc, error)
// NewRootObjectFunc returns the identity function. The passed focus value
// must be an object.
func NewRootObjectFunc() SurroundingObjectFunc {
return func(x interface{}) (map[string]interface{}, AccessorFunc, error) {
obj, ok := x.(map[string]interface{})
if !ok {
return nil, nil, fmt.Errorf("object root default value must be of object type")
}
return obj, func(root map[string]interface{}) (interface{}, bool, error) {
return root, true, nil
}, nil
}
}
// WithTypeMeta returns a closure with the TypeMeta fields set if they are defined.
// This mutates f(x).
func (f SurroundingObjectFunc) WithTypeMeta(meta metav1.TypeMeta) SurroundingObjectFunc {
return func(x interface{}) (map[string]interface{}, AccessorFunc, error) {
obj, acc, err := f(x)
if err != nil {
return nil, nil, err
}
if obj == nil {
obj = map[string]interface{}{}
}
if _, found := obj["kind"]; !found {
obj["kind"] = meta.Kind
}
if _, found := obj["apiVersion"]; !found {
obj["apiVersion"] = meta.APIVersion
}
return obj, acc, err
}
}
// Child returns a function x => f({k: x}) and the corresponding accessor.
func (f SurroundingObjectFunc) Child(k string) SurroundingObjectFunc {
return func(x interface{}) (map[string]interface{}, AccessorFunc, error) {
obj, acc, err := f(map[string]interface{}{k: x})
if err != nil {
return nil, nil, err
}
return obj, func(obj map[string]interface{}) (interface{}, bool, error) {
x, found, err := acc(obj)
if err != nil {
return nil, false, fmt.Errorf(".%s%v", k, err)
}
if !found {
return nil, false, nil
}
if x, ok := x.(map[string]interface{}); !ok {
return nil, false, fmt.Errorf(".%s must be of object type", k)
} else if v, found := x[k]; !found {
return nil, false, nil
} else {
return v, true, nil
}
}, err
}
}
// Index returns a function x => f([x]) and the corresponding accessor.
func (f SurroundingObjectFunc) Index() SurroundingObjectFunc {
return func(focus interface{}) (map[string]interface{}, AccessorFunc, error) {
obj, acc, err := f([]interface{}{focus})
if err != nil {
return nil, nil, err
}
return obj, func(obj map[string]interface{}) (interface{}, bool, error) {
x, found, err := acc(obj)
if err != nil {
return nil, false, fmt.Errorf("[]%v", err)
}
if !found {
return nil, false, nil
}
if x, ok := x.([]interface{}); !ok {
return nil, false, fmt.Errorf("[] must be of array type")
} else if len(x) == 0 {
return nil, false, nil
} else {
return x[0], true, nil
}
}, err
}
}
|
adriansr/cryptopals-challenge | cmd/s4c25/main.go | package main
import (
"os"
"fmt"
"io/ioutil"
"github.com/adriansr/cryptopals-challenge/util"
"crypto/aes"
"github.com/adriansr/cryptopals-challenge/crypto"
"bytes"
"encoding/binary"
"crypto/cipher"
)
// Make it more challenging
const MaxEdit = 15
var key = util.RandomBytes(aes.BlockSize)
var nonce = binary.BigEndian.Uint64(util.RandomBytes(8))
var bc cipher.Block
func init() {
var err error
bc, err = aes.NewCipher(key)
if err != nil {
panic(err)
}
}
func loadCyphertext(filename string) []byte {
fHandle, err := os.Open(os.Args[1])
if err != nil {
panic(err)
}
defer fHandle.Close()
plaintext, err := ioutil.ReadAll(fHandle)
if err != nil {
panic(err)
}
ciphertext, err := ioutil.ReadAll(crypto.NewCTRStream(bytes.NewReader(plaintext), nonce, bc))
if len(ciphertext) != len(plaintext) {
panic(len(ciphertext) - len(plaintext))
}
return ciphertext
}
func edit(ciphertext []byte, pos uint64, newData []byte) {
if uint64(len(newData)) + pos > uint64(len(ciphertext)) {
panic(555)
}
if len(newData) > MaxEdit {
panic(444)
}
nc, err := ioutil.ReadAll(crypto.NewCTRStreamAtPos(pos, bytes.NewReader(newData), nonce, bc))
if err != nil {
panic(err)
}
copy(ciphertext[pos:], nc)
}
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s <file>\n", os.Args[0])
os.Exit(1)
}
ciphertext := loadCyphertext(os.Args[1])
n := len(ciphertext)
buf := make([]byte, n)
copy(buf, ciphertext)
for i := 0; i < n; i++ {
rem := n - i
if rem > MaxEdit {
rem = MaxEdit
}
// It is even simpler: Editing with the ciphertext is equivalent to
// decrypt. No need to worry about the keystream.
edit(buf, uint64(i), buf[i:i+rem])
}
fmt.Print(string(buf))
}
|
TheBricktop/BoofCV | main/boofcv-ip/src/main/java/boofcv/abst/filter/derivative/AnyImageDerivative.java | /*
* Copyright (c) 2021, <NAME>. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.abst.filter.derivative;
import boofcv.BoofDefaults;
import boofcv.abst.filter.convolve.ConvolveInterface;
import boofcv.alg.filter.kernel.GKernelMath;
import boofcv.core.image.GeneralizedImageOps;
import boofcv.factory.filter.convolve.FactoryConvolve;
import boofcv.struct.border.BorderType;
import boofcv.struct.convolve.Kernel1D;
import boofcv.struct.convolve.Kernel2D;
import boofcv.struct.image.ImageGray;
import boofcv.struct.image.ImageType;
/**
* <p>
* A helpful class which allows a derivative of any order to be computed from an input image using a simple to use
* interface. Higher order derivatives are computed from lower order derivatives. Derivatives are computed
* using convolution kernels and thus might not be as efficient as when using functions from
* {@link boofcv.factory.filter.derivative.FactoryDerivative}.
* </p>
*
* @author <NAME>
*/
@SuppressWarnings({"NullAway.Init"})
public class AnyImageDerivative<I extends ImageGray<I>, D extends ImageGray<D>> {
// filters for computing image derivatives
private final ConvolveInterface<I, D> derivX;
private final ConvolveInterface<I, D> derivY;
// gaussian blur the derivative image
private final ConvolveInterface<D, D> derivDerivX;
private final ConvolveInterface<D, D> derivDerivY;
// how the borders are handled
private final BorderType borderDeriv = BoofDefaults.DERIV_BORDER_TYPE;
private I inputImage;
// stores computed derivative images
private D[][] derivatives;
// if true then
private boolean[][] stale;
private final Class<D> derivType;
/**
* Constructor for 1D kernels.
*
* @param deriv 1D convolution kernel for computing derivative along x and y axises.
* @param inputType The type of input image.
* @param derivType Derivative image type
*/
public AnyImageDerivative( Kernel1D deriv, Class<I> inputType, Class<D> derivType ) {
this.derivType = derivType;
ImageType<I> _inputType = ImageType.single(inputType);
ImageType<D> _derivType = ImageType.single(derivType);
derivX = FactoryConvolve.convolve(deriv, _inputType, _derivType, borderDeriv, true);
derivY = FactoryConvolve.convolve(deriv, _inputType, _derivType, borderDeriv, false);
derivDerivX = FactoryConvolve.convolve(deriv, _derivType, _derivType, borderDeriv, true);
derivDerivY = FactoryConvolve.convolve(deriv, _derivType, _derivType, borderDeriv, false);
}
/**
* Constructor for 2D kernels.
*
* @param derivX 2D convolution kernel for computing derivative along x axis
* @param inputType The type of input image.
* @param derivType Derivative image type
*/
public AnyImageDerivative( Kernel2D derivX, Class<I> inputType, Class<D> derivType ) {
this.derivType = derivType;
Kernel2D derivY = GKernelMath.transpose(derivX);
this.derivX = FactoryConvolve.convolve(derivX, inputType, derivType, borderDeriv);
this.derivY = FactoryConvolve.convolve(derivY, inputType, derivType, borderDeriv);
derivDerivX = FactoryConvolve.convolve(derivX, derivType, derivType, borderDeriv);
derivDerivY = FactoryConvolve.convolve(derivY, derivType, derivType, borderDeriv);
}
/**
* Constructor for when all derivative filters are specified
*
* @param derivX Filter for computing derivative along x axis from input image.
* @param derivY Filter for computing derivative along y axis from input image.
* @param derivXX Filter for computing derivative along x axis from input image.
* @param derivYY Filter for computing derivative along y axis from input image.
* @param inputType The type of input image.
*/
public AnyImageDerivative( ConvolveInterface<I, D> derivX, ConvolveInterface<I, D> derivY,
ConvolveInterface<D, D> derivXX, ConvolveInterface<D, D> derivYY,
Class<I> inputType, Class<D> derivType ) {
this.derivType = derivType;
this.derivX = derivX;
this.derivY = derivY;
this.derivDerivX = derivXX;
this.derivDerivY = derivYY;
}
/**
* Sets the new input image from which the image derivatives are computed from.
*
* @param input Input image.
*/
public void setInput( I input ) {
this.inputImage = input;
// reset the state flag so that everything need sto be computed
if (stale != null) {
for (int i = 0; i < stale.length; i++) {
boolean a[] = stale[i];
for (int j = 0; j < a.length; j++) {
a[j] = true;
}
}
}
}
/**
* Computes derivative images using previously computed lower level derivatives. Only
* computes/declares images as needed.
*/
public D getDerivative( boolean... isX ) {
if (derivatives == null) {
declareTree(isX.length);
} else if (isX.length > stale.length) {
growTree(isX.length);
}
int index = 0;
int prevIndex = 0;
for (int level = 0; level < isX.length; level++) {
index |= isX[level] ? 0 : 1 << level;
if (stale[level][index]) {
stale[level][index] = false;
derivatives[level][index].reshape(inputImage.getWidth(), inputImage.getHeight());
if (level == 0) {
if (isX[level]) {
derivX.process(inputImage, derivatives[level][index]);
} else {
derivY.process(inputImage, derivatives[level][index]);
}
} else {
D prev = derivatives[level - 1][prevIndex];
if (isX[level]) {
derivDerivX.process(prev, derivatives[level][index]);
} else {
derivDerivY.process(prev, derivatives[level][index]);
}
}
}
prevIndex = index;
}
return derivatives[isX.length - 1][index];
}
private void declareTree( int maxDerivativeOrder ) {
derivatives = (D[][])new ImageGray[maxDerivativeOrder][];
stale = new boolean[maxDerivativeOrder][];
for (int i = 0; i < maxDerivativeOrder; i++) {
int N = (int)Math.pow(2, i + 1);
derivatives[i] = (D[])new ImageGray[N];
stale[i] = new boolean[N];
for (int j = 0; j < N; j++) {
stale[i][j] = true;
derivatives[i][j] = GeneralizedImageOps.createSingleBand(derivType, 1, 1);
}
}
}
private void growTree( int maxDerivativeOrder ) {
D[][] oldDerives = derivatives;
boolean[][] oldStale = stale;
declareTree(maxDerivativeOrder);
int N = oldStale.length;
for (int i = 0; i < N; i++) {
int M = oldStale[i].length;
for (int j = 0; j < M; j++) {
derivatives[i][j] = oldDerives[i][j];
stale[i][j] = oldStale[i][j];
}
}
}
}
|
k4netmt/Ogaga | oGAGA/app/src/main/java/com/ogaga/flash/acitivies/TimeLineActivity.java | package com.ogaga.flash.acitivies;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Display;
import android.view.View;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.firebase.client.Query;
import com.ogaga.flash.R;
import com.ogaga.flash.adapters.ProductRecyclerViewAdapter;
import com.ogaga.flash.clients.FirebaseClient;
import com.ogaga.flash.extra.Constant;
import com.ogaga.flash.models.Catalogies;
import com.ogaga.flash.models.User;
import org.parceler.Parcels;
import butterknife.Bind;
import butterknife.ButterKnife;
public class TimeLineActivity extends AppCompatActivity {
private Firebase fbProduct;
@Bind(R.id.toolbarHeader)
Toolbar mToolbar;
@Bind(R.id.rvProductList)
RecyclerView rvProductList;
@Bind(R.id.fab)
FloatingActionButton fab;
Catalogies mCatalogies;
private ProductRecyclerViewAdapter mProductRecyclerViewAdapter;
private User mUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time_line);
ButterKnife.bind(this);
mCatalogies= Parcels.unwrap(getIntent().getParcelableExtra("catalogies"));
mUser= Parcels.unwrap(getIntent().getParcelableExtra("user"));
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(mCatalogies.getName());
populateProductListView();
/* onClickSellFAB();*/
}
@Override
public Context createDisplayContext(Display display) {
return super.createDisplayContext(display);
}
public void populateProductListView() {
Firebase firebaseProduct = FirebaseClient.getProduct();
Query query=firebaseProduct.orderByChild("id_productType").equalTo(mCatalogies.getId());
mProductRecyclerViewAdapter = new ProductRecyclerViewAdapter(query, this,mUser);
rvProductList.setHasFixedSize(true);
rvProductList.setLayoutManager(new LinearLayoutManager(this));
rvProductList.setAdapter(mProductRecyclerViewAdapter);
}
public void onClickSellFAB() {
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(TimeLineActivity.this, SellActivity.class);
intent.putExtra("user", Parcels.wrap(mUser));
startActivityForResult(intent, Constant.SELLPRODUCT_SUCCESS_CODE);
}
});
}
// on Product post result
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Constant.SELLPRODUCT_SUCCESS_CODE) {
Toast.makeText(this, getString(R.string.product_created_successful), Toast.LENGTH_SHORT).show();
}
}
}
|
NotCamelCase/Grad-Project-Arcade-Sim | src/Screen/MainMenuScreen.cpp | <reponame>NotCamelCase/Grad-Project-Arcade-Sim
/*
The MIT License (MIT)
Copyright (c) 2015 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "Screen\MainMenuScreen.h"
#include <MyGUI.h>
#include <MyGUI_OgrePlatform.h>
#include <fmod.hpp>
#include "Screen\ScreenManager.h"
#include "Player\PlayerManager.h"
#include "Audio\AudioManager.h"
#include "Audio\SoundEffect.h"
#include "Player\Player.h"
#include "Audio\Music.h"
#include "Utils.h"
#include "Game.h"
using namespace Ogre;
using namespace MyGUI;
#define SKIP_TO_GAMEPLAY // Skip directly to GameplayScreen pressing SPACE when developing
//#undefine
MainMenuScreen::MainMenuScreen(ScreenManager* sm, ScreenTag tag)
: Screen(sm, tag), m_singlePlayerButton(NULL), m_multiplayerButton(NULL),
m_exitButton(NULL), m_creditsButton(NULL), m_bgImage(NULL),
m_clickSound(NULL), m_bgMusic(NULL), m_hoverSound(NULL)
{
m_uiFileName = "main_menu.layout";
}
MainMenuScreen::~MainMenuScreen()
{
}
void MainMenuScreen::enter()
{
m_ogrePlatform->getRenderManagerPtr()->setSceneManager(m_sceneMgr);
static const String resourceName = "Essential";
if (!ResourceGroupManager::getSingleton().isResourceGroupInitialised(resourceName))
ResourceGroupManager::getSingleton().initialiseResourceGroup(resourceName);
if (!ResourceGroupManager::getSingleton().isResourceGroupLoaded(resourceName))
ResourceGroupManager::getSingleton().loadResourceGroup(resourceName);
buildUI();
}
void MainMenuScreen::buildUI()
{
m_guiLayout = LayoutManager::getInstance().loadLayout(m_uiFileName);
assert(!m_guiLayout.empty() && "Main Menu UI failed to load!");
m_bgImage = Gui::getInstance().findWidget<ImageBox>("background");
m_bgImage->setSize(RenderManager::getInstance().getViewSize());
m_bgImage->setImageTexture("race_back.png");
m_singlePlayerButton = Gui::getInstance().findWidget<Button>("singleplayerButton");
m_multiplayerButton = Gui::getInstance().findWidget<Button>("multiplayerButton");
m_exitButton = Gui::getInstance().findWidget<Button>("exitButton");
m_creditsButton = Gui::getInstance().findWidget<Button>("creditsButton");
m_singlePlayerButton->setNeedMouseFocus(true);
m_singlePlayerButton->eventMouseSetFocus += newDelegate(this, &MainMenuScreen::buttonHovered);
m_singlePlayerButton->eventMouseButtonClick += newDelegate(this, &MainMenuScreen::buttonClicked);
m_multiplayerButton->setNeedMouseFocus(true);
m_multiplayerButton->eventMouseSetFocus += newDelegate(this, &MainMenuScreen::buttonHovered);
m_multiplayerButton->eventMouseButtonClick += newDelegate(this, &MainMenuScreen::buttonClicked);
m_exitButton->setNeedMouseFocus(true);
m_exitButton->eventMouseSetFocus += newDelegate(this, &MainMenuScreen::buttonHovered);
m_exitButton->eventMouseButtonClick += newDelegate(this, &MainMenuScreen::buttonClicked);
m_creditsButton->setNeedMouseFocus(true);
m_creditsButton->eventMouseSetFocus += newDelegate(this, &MainMenuScreen::buttonHovered);
m_creditsButton->eventMouseButtonClick += newDelegate(this, &MainMenuScreen::buttonClicked);
m_clickSound = AudioManager::getSingleton().createSoundEffect("click.ogg");
m_hoverSound = AudioManager::getSingleton().createSoundEffect("clickalt.ogg");
m_bgMusic = AudioManager::getSingleton().createMusic("menu.ogg", AudioType::SOUND_2D_LOOPING);
m_bgMusic->play();
m_bgMusic->setVolume(0.5);
}
void MainMenuScreen::update(Real delta)
{
}
void MainMenuScreen::pause()
{
Screen::pause();
m_bgMusic->stop();
}
void MainMenuScreen::resume()
{
Screen::resume();
if (!m_bgMusic)
{
m_bgMusic = AudioManager::getSingleton().createMusic("menu.ogg", AudioType::SOUND_2D_LOOPING);
}
m_bgMusic->play();
m_bgMusic->setVolume(0.5);
}
void MainMenuScreen::leave()
{
m_logger->logMessage("MainMenuScreen::leave()");
if (m_guiLayout.size() > 0)
{
LayoutManager::getInstance().unloadLayout(m_guiLayout);
m_guiLayout.clear();
}
//AudioManager::getSingleton().release(m_clickSound);
//AudioManager::getSingleton().release(m_hoverSound);
//AudioManager::getSingleton().release(m_bgMusic);
}
void MainMenuScreen::buttonClicked(WidgetPtr sender)
{
if (sender == m_singlePlayerButton)
enterPracticeMode();
else if (sender == m_multiplayerButton)
enterMultiplayer();
else if (sender == m_creditsButton)
showCredits();
else if (sender == m_exitButton)
exitGame();
}
void MainMenuScreen::buttonHovered(WidgetPtr sender, WidgetPtr old)
{
m_hoverSound->play();
}
void MainMenuScreen::enterPracticeMode()
{
m_logger->logMessage("MainMenuScreen::enterPracticeMode()");
m_clickSound->play();
Game::setGameMode(GameMode::PRACTICE);
if (!PlayerManager::getSingleton().getLocalPlayer() || !PlayerManager::getSingleton().getLocalPlayer()->isLoggedIn())
{
m_screenManager->changeScreen(ScreenTag::USER_LOGIN, false);
}
else
{
m_screenManager->changeScreen(ScreenTag::TRACK_SELECT, false);
}
}
void MainMenuScreen::enterMultiplayer()
{
m_logger->logMessage("MainMenuScreen::enterOnlineMode()");
m_clickSound->play();
Game::setGameMode(GameMode::MULTI_PLAYER);
if (!PlayerManager::getSingleton().getLocalPlayer() || !PlayerManager::getSingleton().getLocalPlayer()->isLoggedIn())
{
m_screenManager->changeScreen(ScreenTag::USER_LOGIN, false);
}
else
{
m_screenManager->changeScreen(ScreenTag::GAME_LOBBY, false);
}
}
void MainMenuScreen::showCredits()
{
m_logger->logMessage("MainMenuScreen::showCredits()");
m_clickSound->play();
m_screenManager->changeScreen(ScreenTag::CREDITS, true);
}
void MainMenuScreen::exitGame()
{
m_logger->logMessage("MainMenuScreen::exitGame()");
m_clickSound->play();
m_screenManager->setShutDown(true);
}
bool MainMenuScreen::keyPressed(const OIS::KeyEvent& e)
{
InputManager::getInstance().injectKeyPress(KeyCode::Enum(e.key), e.text);
switch (e.key)
{
case OIS::KC_ESCAPE:
m_screenManager->setShutDown(true);
break;
}
return true;
}
bool MainMenuScreen::keyReleased(const OIS::KeyEvent& e)
{
InputManager::getInstance().injectKeyRelease(KeyCode::Enum(e.key));
#if defined (SKIP_TO_GAMEPLAY)
switch (e.key)
{
// DEBUG ONLY !!!
case OIS::KC_SPACE:
AudioManager::getSingleton().release(m_clickSound);
AudioManager::getSingleton().release(m_hoverSound);
AudioManager::getSingleton().release(m_bgMusic);
m_screenManager->changeScreen(ScreenTag::GAME_PLAY, false);
break;
default:
break;
}
#endif
return true;
}
bool MainMenuScreen::mousePressed(const OIS::MouseEvent& e, OIS::MouseButtonID id)
{
InputManager::getInstance().injectMousePress(e.state.X.abs, e.state.Y.abs, MouseButton::Enum(id));
return true;
}
bool MainMenuScreen::mouseMoved(const OIS::MouseEvent& e)
{
InputManager::getInstance().injectMouseMove(e.state.X.abs, e.state.Y.abs, e.state.Z.abs);
return true;
}
bool MainMenuScreen::mouseReleased(const OIS::MouseEvent& e, OIS::MouseButtonID id)
{
InputManager::getInstance().injectMouseRelease(e.state.X.abs, e.state.Y.abs, MouseButton::Enum(id));
return true;
} |
mahshidhelali/RL-Assisted-Performance-Testing | RELOAD v0.2/LoadTester.java | <gh_stars>1-10
package org.deeplearning4j.rl4j.examples.advanced.QLearning;
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.reporters.Summariser;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.threads.ThreadGroup;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
import org.apache.jorphan.collections.SearchByClass;
import java.io.File;
import java.util.Collection;
public class LoadTester{
private StandardJMeterEngine jmeter;
private Summariser summer;
private ResultCollector logger;
private String JMETER_HOME_PATH = "/Users/IEUser/Desktop/apache-jmeter-5.1";
private String JMETER_PROPERTY_PATH = "/Users/IEUser/Desktop/apache-jmeter-5.1/bin/jmeter.properties";
private String JMETER_LOG_FILE_PATH = "/Users/IEUser/Desktop/apache-jmeter-5.1/bin/transactions_rubis/all_transactions_local_server.jtl";
private String JMX_FILES_PATH = "/Users/IEUser/Desktop/apache-jmeter-5.1/bin/transactions_rubis/";
// private String JMETER_HOME_PATH = "/Users/erisa/OneDrive/Desktop/apache-jmeter-5.4.1/apache-jmeter-5.4.1";
// private String JMETER_PROPERTY_PATH = "/Users/erisa/OneDrive/Desktop/apache-jmeter-5.4.1/apache-jmeter-5.4.1/bin/jmeter.properties";
// private String JMETER_LOG_FILE_PATH = "/Users/erisa/OneDrive/Desktop/jmx_logs/Test_Plan.jtl";
// private String JMX_FILES_PATH = "/Users/erisa/OneDrive/Desktop/jmx_files/";
// private String JMX_FILES_PATH = "/Users/erisa/OneDrive/Desktop/JMeter_examples/jmx_files/";
public LoadTester(){
Initialize();
}
private void Initialize(){
// JMeter Engine
jmeter = new StandardJMeterEngine();
// Initialize Properties, logging, locale, etc.
JMeterUtils.loadJMeterProperties(JMETER_PROPERTY_PATH);
JMeterUtils.setJMeterHome(JMETER_HOME_PATH);
// JMeterUtils.initLogging();// you can comment this line out to see extra log messages of i.e. DEBUG level
JMeterUtils.initLocale();
// Initialize JMeter SaveService
try{
SaveService.loadProperties();
}catch(Exception e){
e.printStackTrace();
}
}
//for seperate transactions
/*
public boolean ExecuteTransaction(Transaction t,int rampUpTime,int numOfLoops){
HashTree testPlanTree;
boolean testPassed = false;
try{
testPlanTree = SaveService.loadTree(new File (JMX_FILES_PATH+t.name+".jmx"));
// testPlanTree.add(testPlanTree.getArray()[0], logger);
// System.out.println(testPlanTree.toString());
SearchByClass<ThreadGroup> threadGroups = new SearchByClass<>(ThreadGroup.class);
testPlanTree.traverse(threadGroups);
Collection<ThreadGroup> threadGroupsRes = threadGroups.getSearchResults();
for (ThreadGroup threadGroup : threadGroupsRes) {
threadGroup.setNumThreads(t.workLoad);
threadGroup.setRampUp(rampUpTime);
((LoopController)threadGroup.getSamplerController()).setLoops(numOfLoops);
System.out.println("Transaction: "+ t.name +", Workload (num of threads): "+threadGroup.getProperty("ThreadGroup.num_threads").toString());
System.out.println("Ramp Up:"+threadGroup.getRampUp());
System.out.println("Loop: "+ ((LoopController)threadGroup.getSamplerController()).getProperty("LoopController.loops"));
}
MyResultCollector myResultCollector = new MyResultCollector(summer);
testPlanTree.add(testPlanTree.getArray()[0], myResultCollector);
// Run JMeter Test
jmeter.configure(testPlanTree);
try{
jmeter.run();
testPassed = myResultCollector.allTestSamplesPassed();
if(testPassed)
myResultCollector.calculateAverageQualityMeasures(t);
}catch(Exception e){
System.out.println("jmeter run");
e.printStackTrace();
}
}catch(Exception e){
System.out.println("testPlanTree");
e.printStackTrace();
}
return testPassed;
}*/
public boolean ExecuteAllTransactions(Transaction[] transactions, int rampUpTime, int numOfLoops, QualityMeasures qualityMeasures){
summer = null;
String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
if (summariserName.length() > 0) {
summer = new Summariser(summariserName);
}
String logFile = JMETER_LOG_FILE_PATH;
logger = new ResultCollector(summer);
logger.setFilename(logFile);
HashTree testPlanTree;
boolean testPassed = false;
String transactionName = "all_transactions";
try{
testPlanTree = SaveService.loadTree(new File (JMX_FILES_PATH+"all_transactions_local_server.jmx"));
// testPlanTree.add(testPlanTree.getArray()[0], logger);
// System.out.println(testPlanTree.toString());
SearchByClass<ThreadGroup> threadGroups = new SearchByClass<>(ThreadGroup.class);
testPlanTree.traverse(threadGroups);
Collection<ThreadGroup> threadGroupsRes = threadGroups.getSearchResults();
for (ThreadGroup threadGroup : threadGroupsRes) {
for (Transaction t : transactions) {
if((t.name+"_thread_group").equals(threadGroup.getName())) {
threadGroup.setNumThreads(t.workLoad);
threadGroup.setRampUp(rampUpTime);
((LoopController) threadGroup.getSamplerController()).setLoops(numOfLoops);
//System.out.println("thread group: " + threadGroup.getName());
//System.out.println("Transaction: " + t.name + ", Workload (num of threads): " + threadGroup.getProperty("ThreadGroup.num_threads").toString());
//System.out.println("Ramp Up:" + threadGroup.getRampUp());
//System.out.println("Loop: " + ((LoopController) threadGroup.getSamplerController()).getProperty("LoopController.loops"));
break;
}
}
}
System.out.println("Ramp Up:" + rampUpTime);
MyResultCollector myResultCollector = new MyResultCollector(summer);
testPlanTree.add(testPlanTree.getArray()[0], myResultCollector);
// Run JMeter Test
jmeter.configure(testPlanTree);
try{
jmeter.run();
testPassed = myResultCollector.allTestSamplesPassed();
if(testPassed)
myResultCollector.calculateAverageQualityMeasures(qualityMeasures);
}catch(Exception e){
System.out.println("jmeter run");
e.printStackTrace();
}
}catch(Exception e){
System.out.println("testPlanTree");
e.printStackTrace();
}
return testPassed;
}
}
|
teddywest32/intellij-community | plugins/InspectionGadgets/test/com/siyeh/igtest/visibility/ambiguous/AmbiguousMethodCall.java | <gh_stars>0
package com.siyeh.igtest.visibility.ambiguous;
public class AmbiguousMethodCall {
class X {
void m() {}
class Inner extends Y {
{
<warning descr="Call to method 'm()' from superclass 'Y' looks like call to method from class 'X'">m</warning>(); // ambiguous
}
}
}
class Y {
void m() {}
}
class Z {
void n() {}
class Inner extends Object {
{
n(); // not ambiguous
}
void n() {}
}
}
}
|
timxor/leetcode-journal | solutions/LeetCode/Java/128.java | <reponame>timxor/leetcode-journal
__________________________________________________________________________________________________
sample 2 ms submission
import java.util.Arrays;
/*
* @lc app=leetcode id=128 lang=java
*
* [128] Longest Consecutive Sequence
*/
class Solution {
public int longestConsecutive(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int curr = 1;
int res = 1;
Arrays.sort(nums);
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[i - 1]){
if (nums[i] == nums[i - 1] + 1) {
curr++;
} else {
res = Math.max(curr, res);
curr = 1;
}
}
}
return res = Math.max(curr, res);
}
}
__________________________________________________________________________________________________
sample 34232 kb submission
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num: nums) {
set.add(num);
}
int res = 0;
for (int i = 0; i < nums.length; i++) {
int temp = 0;
int tempres = 0;
if (!set.contains(nums[i] - 1)) {
temp = nums[i];
tempres = 1;
while (set.contains(++temp)) {
tempres++;
}
}
res = Math.max(res, tempres);
}
return res;
}
}
__________________________________________________________________________________________________
|
tan9/spring-security | core/src/test/java/org/springframework/security/jackson2/RememberMeAuthenticationTokenMixinTests.java | /*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.jackson2;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.json.JSONException;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.io.IOException;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author <NAME>
* @since 4.2
*/
public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests {
private static final String REMEMBERME_KEY = "rememberMe";
// @formatter:off
private static final String REMEMBERME_AUTH_JSON = "{"
+ "\"@class\": \"org.springframework.security.authentication.RememberMeAuthenticationToken\", "
+ "\"keyHash\": " + REMEMBERME_KEY.hashCode() + ", "
+ "\"authenticated\": true, \"details\": null" + ", "
+ "\"principal\": " + UserDeserializerTests.USER_JSON + ", "
+ "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON
+ "}";
// @formatter:on
// @formatter:off
private static final String REMEMBERME_AUTH_STRINGPRINCIPAL_JSON = "{"
+ "\"@class\": \"org.springframework.security.authentication.RememberMeAuthenticationToken\","
+ "\"keyHash\": " + REMEMBERME_KEY.hashCode() + ", "
+ "\"authenticated\": true, "
+ "\"details\": null,"
+ "\"principal\": \"admin\", "
+ "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON
+ "}";
// @formatter:on
@Test(expected = IllegalArgumentException.class)
public void testWithNullPrincipal() {
new RememberMeAuthenticationToken("key", null, Collections.<GrantedAuthority>emptyList());
}
@Test(expected = IllegalArgumentException.class)
public void testWithNullKey() {
new RememberMeAuthenticationToken(null, "principal", Collections.<GrantedAuthority>emptyList());
}
@Test
public void serializeRememberMeAuthenticationToken() throws JsonProcessingException, JSONException {
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(REMEMBERME_KEY, "admin", Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")));
String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(REMEMBERME_AUTH_STRINGPRINCIPAL_JSON, actualJson, true);
}
@Test
public void serializeRememberMeAuthenticationWithUserToken() throws JsonProcessingException, JSONException {
User user = createDefaultUser();
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(REMEMBERME_KEY, user, user.getAuthorities());
String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(String.format(REMEMBERME_AUTH_JSON, "\"password\""), actualJson, true);
}
@Test
public void serializeRememberMeAuthenticationWithUserTokenAfterEraseCredential() throws JsonProcessingException, JSONException {
User user = createDefaultUser();
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(REMEMBERME_KEY, user, user.getAuthorities());
token.eraseCredentials();
String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(REMEMBERME_AUTH_JSON.replace(UserDeserializerTests.USER_PASSWORD, "null"), actualJson, true);
}
@Test
public void deserializeRememberMeAuthenticationToken() throws IOException {
RememberMeAuthenticationToken token = mapper.readValue(REMEMBERME_AUTH_STRINGPRINCIPAL_JSON, RememberMeAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.getPrincipal()).isNotNull().isEqualTo("admin").isEqualTo(token.getName());
assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
}
@Test
public void deserializeRememberMeAuthenticationTokenWithUserTest() throws IOException {
RememberMeAuthenticationToken token = mapper
.readValue(String.format(REMEMBERME_AUTH_JSON, "\"password\""), RememberMeAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class);
assertThat(((User) token.getPrincipal()).getUsername()).isEqualTo("admin");
assertThat(((User) token.getPrincipal()).getPassword()).isEqualTo("<PASSWORD>");
assertThat(((User) token.getPrincipal()).getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
assertThat(((User) token.getPrincipal()).isEnabled()).isEqualTo(true);
}
}
|
slafayIGN/validator | validator-core/src/main/java/fr/ign/validator/validation/database/AttributeReferenceValidator.java | package fr.ign.validator.validation.database;
import java.io.IOException;
import java.sql.SQLException;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import org.locationtech.jts.geom.Envelope;
import fr.ign.validator.Context;
import fr.ign.validator.database.Database;
import fr.ign.validator.database.RowIterator;
import fr.ign.validator.error.CoreErrorCodes;
import fr.ign.validator.error.ErrorScope;
import fr.ign.validator.model.AttributeType;
import fr.ign.validator.model.FeatureType;
import fr.ign.validator.model.TableModel;
import fr.ign.validator.tools.EnvelopeUtils;
import fr.ign.validator.tools.ModelHelper;
import fr.ign.validator.validation.Validator;
/**
* Validate "reference" constraints using validation database.
*
* @author MBorne
*
*/
public class AttributeReferenceValidator implements Validator<Database> {
public static final Logger log = LogManager.getRootLogger();
public static final Marker MARKER = MarkerManager.getMarker("RelationValidator");
/**
* hardcoded limit to avoid huge report on massively invalid table
*/
private static final int LIMIT_PER_ATTRIBUTE = 10;
/**
* Validate "reference" constraints for each attribute.
*/
public void validate(Context context, Database database) {
try {
doValidate(context, database);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @param context
* @param database
* @throws SQLException
* @throws IOException
*/
private void doValidate(Context context, Database database) throws SQLException, IOException {
log.info(MARKER, "Looking for attributes with reference constraints...");
/*
* Validate each attribute marked as unique
*/
for (TableModel tableModel : ModelHelper.getTableModels(context.getDocumentModel())) {
context.beginModel(tableModel);
FeatureType featureType = tableModel.getFeatureType();
for (AttributeType<?> attribute : featureType.getAttributes()) {
String reference = attribute.getConstraints().getReference();
if (StringUtils.isEmpty(reference)) {
continue;
}
context.beginModel(attribute);
String sourceTableName = tableModel.getName();
String sourceColumnName = attribute.getName();
String targetTableName = attribute.getTableReference();
String targetColumnName = attribute.getAttributeReference();
/*
* Retrieve rows
*/
log.info(
MARKER, "Ensure that {}.{} references to {}.{} are valid...",
sourceTableName,
sourceColumnName,
targetTableName,
targetColumnName
);
String sql = getSqlFindInvalidRows(
sourceTableName, sourceColumnName, targetTableName, targetColumnName
);
RowIterator it = database.query(sql);
/*
* Prepare reporting
*/
int count = 0;
int indexValue = it.getColumn(sourceColumnName);
AttributeType<?> attributeFeatureId = featureType.getIdentifier();
int indexFeatureId = attributeFeatureId != null ? it.getColumn(attributeFeatureId.getName()) : -1;
// TODO add support for different column name (kept for validator-plugin-dgpr)
int indexGeom = it.getColumn("WKT");
while (it.hasNext()) {
count++;
String[] row = it.next();
/*
* retrieve the id of the feature (kept for validator-plugin-dgpr)
*/
String featureId = "";
if (indexFeatureId >= 0) {
featureId = row[indexFeatureId];
}
/*
* retrieve the bounding box of the feature (kept for validator-plugin-dgpr)
*/
Envelope featureBoundingBox = null;
if (indexGeom >= 0 && !StringUtils.isEmpty(row[indexGeom])) {
featureBoundingBox = EnvelopeUtils.getEnvelope(row[indexGeom], context.getProjection());
}
context.report(
/*
* Note that scope DIRECTORY is mainly forced to ease integration in current
* client.
*/
context.createError(CoreErrorCodes.ATTRIBUTE_REFERENCE_NOT_FOUND)
.setScope(ErrorScope.DIRECTORY)
.setFileModel(tableModel.getName())
.setAttribute(attribute.getName())
.setFeatureId(featureId)
.setFeatureBbox(featureBoundingBox)
.setMessageParam("REF_VALUE", row[indexValue])
.setMessageParam("SOURCE_TABLE", sourceTableName)
.setMessageParam("SOURCE_COLUMN", sourceColumnName)
.setMessageParam("TARGET_TABLE", targetTableName)
.setMessageParam("TARGET_COLUMN", targetColumnName)
);
}
/*
* Report the number of errors for duplicated values
*/
log.info(
MARKER,
"Found {} invalid reference(s) from {}.{} to {}.{} (max : 10)",
count,
sourceTableName,
sourceColumnName,
targetTableName,
targetColumnName
);
it.close();
context.endModel(attribute);
}
context.endModel(tableModel);
}
}
/**
* Get SQL statement to retrieve rows with invalid reference.
*
* @param sourceTableName
* @param sourceColumnName
* @param targetTableName
* @param targetColumnName
* @return
*/
private String getSqlFindInvalidRows(
String sourceTableName,
String sourceColumnName,
String targetTableName,
String targetColumnName) {
String sql = "SELECT s.* FROM " + sourceTableName + " s";
sql += " WHERE NOT s." + sourceColumnName + " IN (SELECT " + targetColumnName + " FROM " + targetTableName
+ " t WHERE s." + sourceColumnName + " = t." + targetColumnName + ")";
sql += " AND NOT s." + sourceColumnName + " IS NULL";
sql += " LIMIT " + LIMIT_PER_ATTRIBUTE;
return sql;
}
}
|
nathanmullenax83/rhizome | include/parse/star_closure.cpp | #include "star_closure.hpp"
#include "log.hpp"
namespace rhizome {
namespace parse {
StarClosure::StarClosure( Gramex *inner ): inner(inner) {
}
StarClosure::~StarClosure() {
delete inner;
}
bool
StarClosure::accepts( GrammarFn lookup ) const {
(void)lookup;
return true;
}
void
StarClosure::match( ILexer *lexer, GrammarFn lookup, stringstream &captured ) {
//static rhizome::log::Log log("cfg_STAR");
//log.info("Match called.");
Gramex *copy = inner->clone_gramex(false);
//log.info("Copied gramex.");
while( copy->can_match(lexer,lookup)) {
//log.info("Match available.");
copy->match(lexer,lookup,captured);
//log.info("Match complete.");
append_all(copy->clone_matched_tokens());
//log.info("Match extracted.");
copy->clear();
//log.info("Copy of gramex cleared.");
}
//log.info("Match complete. Deleting copy of gramex.");
delete copy;
}
bool
StarClosure::can_match( ILexer *lexer, GrammarFn lookup ) const {
Gramex *copy = inner->clone_gramex(false);
bool cm = (!lexer->has_next_thing()) || copy->can_match(lexer,lookup);
delete copy;
return cm;
}
Gramex *
StarClosure::clone_gramex(bool withmatches) const {
StarClosure *s = new StarClosure(inner->clone_gramex(withmatches));
if(withmatches) {
s->append_all(clone_matched_tokens());
}
return s;
}
void
StarClosure::serialize_to( size_t level, ostream &out ) const {
out << "(";
inner->serialize_to(level,out);
out << ")*";
}
string
StarClosure::rhizome_type() const {
return "gramex::StarClosure";
}
bool
StarClosure::has_interface( string const &name ) {
return name==rhizome_type()||name=="gramex"||name=="Thing";
}
Thing *
StarClosure::invoke( Thing *context, string const &method, Thing *arg ) {
(void)method; (void)arg; (void)context;
throw runtime_error("Invoke failed.");
}
}
} |
patelsan/fetchpipe | node_modules/isobject/index-compiled.js | <reponame>patelsan/fetchpipe
/*!
* isobject <https://github.com/jonschlinkert/isobject>
*
* Copyright (c) 2014-2015, <NAME>.
* Licensed under the MIT License.
*/
'use strict';
module.exports = function isObject(val) {
return val != null && typeof val === 'object' && !Array.isArray(val);
};
//# sourceMappingURL=index-compiled.js.map |
grmkris/XChange | xchange-btcturk/src/main/java/org/knowm/xchange/btcturk/service/BTCTurkDigest.java | <gh_stars>1000+
package org.knowm.xchange.btcturk.service;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.knowm.xchange.service.BaseParamsDigest;
import si.mazi.rescu.RestInvocation;
/** @author mertguner */
public class BTCTurkDigest extends BaseParamsDigest {
private byte[] SecretKey;
private BTCTurkDigest(String secretKey) {
super(secretKey, HMAC_SHA_256);
SecretKey = Base64.getDecoder().decode(secretKey);
}
public static BTCTurkDigest createInstance(String secretKey, String apiKey) {
return secretKey == null ? null : new BTCTurkDigest(secretKey);
}
@Override
public String digestParams(RestInvocation restInvocation) {
String ApiKey = restInvocation.getHttpHeadersFromParams().get("X-PCK");
String timestamp = restInvocation.getHttpHeadersFromParams().get("X-Stamp");
return generateHash(ApiKey, timestamp);
}
private String generateHash(String ApiKey, String timestamp) {
Mac sha256_HMAC = null;
String message = ApiKey + timestamp;
try {
sha256_HMAC = Mac.getInstance(HMAC_SHA_256);
SecretKeySpec keySpec = new SecretKeySpec(SecretKey, HMAC_SHA_256);
sha256_HMAC.init(keySpec);
return Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(message.getBytes()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return "";
}
}
|
gaybro8777/xfopencv | examples_sdaccel/magnitude/xf_magnitude_accel.cpp | <reponame>gaybro8777/xfopencv<filename>examples_sdaccel/magnitude/xf_magnitude_accel.cpp
/***************************************************************************
Copyright (c) 2019, Xilinx, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
#include "xf_magnitude_config.h"
extern "C" {
void magnitude_accel(ap_uint<INPUT_PTR_WIDTH> *img_inp1, ap_uint<INPUT_PTR_WIDTH> *img_inp2,ap_uint<OUTPUT_PTR_WIDTH> *img_out,int rows, int cols)
{
#pragma HLS INTERFACE m_axi port=img_inp1 offset=slave bundle=gmem1
#pragma HLS INTERFACE m_axi port=img_inp2 offset=slave bundle=gmem2
#pragma HLS INTERFACE m_axi port=img_out offset=slave bundle=gmem3
#pragma HLS INTERFACE s_axilite port=img_inp1 bundle=control
#pragma HLS INTERFACE s_axilite port=img_inp2 bundle=control
#pragma HLS INTERFACE s_axilite port=img_out bundle=control
#pragma HLS INTERFACE s_axilite port=rows bundle=control
#pragma HLS INTERFACE s_axilite port=cols bundle=control
#pragma HLS INTERFACE s_axilite port=return bundle=control
const int pROWS = HEIGHT;
const int pCOLS = WIDTH;
const int pNPC1 = NPC1;
xf::Mat<XF_16SC1, HEIGHT, WIDTH, NPC1> _src1;
#pragma HLS stream variable=_src1.data depth=pCOLS/pNPC1
_src1.rows = rows;
_src1.cols = cols;
xf::Mat<XF_16SC1, HEIGHT, WIDTH, NPC1> _src2;
#pragma HLS stream variable=_src2.data depth=pCOLS/pNPC1
_src2.rows = rows;
_src2.cols = cols;
xf::Mat<XF_16SC1, HEIGHT, WIDTH, NPC1> _dst;
#pragma HLS stream variable=_dst.data depth=pCOLS/pNPC1
_dst.rows = rows;
_dst.cols = cols;
#pragma HLS DATAFLOW
xf::Array2xfMat<INPUT_PTR_WIDTH,XF_16SC1,HEIGHT,WIDTH,NPC1>(img_inp1,_src1);
xf::Array2xfMat<INPUT_PTR_WIDTH,XF_16SC1,HEIGHT,WIDTH,NPC1>(img_inp2,_src2);
xf::magnitude<NORM_TYPE,XF_16SC1,XF_16SC1,HEIGHT, WIDTH,NPC1>(_src1, _src2,_dst);
xf::xfMat2Array<OUTPUT_PTR_WIDTH,XF_16SC1,HEIGHT,WIDTH,NPC1>(_dst,img_out);
}
} |
jnthn/intellij-community | java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advFixture/PackageNameAsClassFQName.java | <reponame>jnthn/intellij-community
package a;
import foo.Bar.*;
class MyTest {
private void foo(Inner inner) {}
} |
plixcoindev/Acryl | node/src/main/scala/com/acrylplatform/consensus/GeneratingBalanceProvider.scala | <reponame>plixcoindev/Acryl
package com.acrylplatform.consensus
import com.acrylplatform.account.Address
import com.acrylplatform.block.Block
import com.acrylplatform.block.Block.BlockId
import com.acrylplatform.common.state.ByteStr
import com.acrylplatform.features.BlockchainFeatures
import com.acrylplatform.state.Blockchain
object GeneratingBalanceProvider {
private val MinimalEffectiveBalanceForGenerator1: Long = 1000000000000L
private val MinimalEffectiveBalanceForGenerator2: Long = 100000000000L
private val MinimalEffectiveBalanceForGenerator3: Long = 10000000000L
private val FirstDepth = 50
private val SecondDepth = 1000
def isMiningAllowed(blockchain: Blockchain, height: Int, effectiveBalance: Long): Boolean = {
val activatedOf1000 = blockchain.activatedFeatures.get(BlockchainFeatures.SmallerMinimalGeneratingBalance.id).exists(height >= _)
val activatedOf100 = blockchain.activatedFeatures.get(BlockchainFeatures.MinimumGeneratingBalanceOf100.id).exists(height >= _)
(!activatedOf100 && !activatedOf1000 && effectiveBalance >= MinimalEffectiveBalanceForGenerator1) ||
(!activatedOf100 && activatedOf1000 && effectiveBalance >= MinimalEffectiveBalanceForGenerator2) ||
(activatedOf100 && effectiveBalance >= MinimalEffectiveBalanceForGenerator3)
}
//noinspection ScalaStyle
def isEffectiveBalanceValid(blockchain: Blockchain, height: Int, block: Block, effectiveBalance: Long): Boolean = {
val activatedOf1000 = blockchain.activatedFeatures.get(BlockchainFeatures.SmallerMinimalGeneratingBalance.id).exists(height >= _)
val activatedOf100 = blockchain.activatedFeatures.get(BlockchainFeatures.MinimumGeneratingBalanceOf100.id).exists(height >= _)
block.timestamp < blockchain.settings.functionalitySettings.minimalGeneratingBalanceAfter || (block.timestamp >= blockchain.settings.functionalitySettings.minimalGeneratingBalanceAfter && effectiveBalance >= MinimalEffectiveBalanceForGenerator1) ||
(activatedOf1000 && effectiveBalance >= MinimalEffectiveBalanceForGenerator2) ||
(activatedOf100 && effectiveBalance >= MinimalEffectiveBalanceForGenerator3)
}
def balance(blockchain: Blockchain, account: Address, blockId: BlockId = ByteStr.empty): Long = {
val height =
if (blockId.isEmpty) blockchain.height
else blockchain.heightOf(blockId).getOrElse(throw new IllegalArgumentException(s"Invalid block ref: $blockId"))
val depth = if (height >= blockchain.settings.functionalitySettings.generationBalanceDepthFrom50To1000AfterHeight) SecondDepth else FirstDepth
blockchain.effectiveBalance(account, depth, blockId)
}
}
|
heisedebaise/photon | photon-pdf/src/main/java/org/lpw/photon/pdf/PdfConverter.java | <gh_stars>0
package org.lpw.photon.pdf;
import java.io.OutputStream;
public interface PdfConverter {
/**
* HTML转化为PDF。
*
* @param html HTML文本。
* @param outputStream PDF输出流。
* @return 如果转化成功则返回true;否则返回false。
*/
boolean html2pdf(String html, OutputStream outputStream);
/**
* HTML转化为PDF。
*
* @param html HTML文本。
* @param file PDF输出文件路径。
* @return 如果转化成功则返回true;否则返回false。
*/
boolean html2pdf(String html, String file);
}
|
IoanBasnic/Le-BoomberMan | MainProject/src/main/java/frontend/UI/QuitListener.java | package frontend.UI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class QuitListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
} |
bobheadlabs/sourcegraph | enterprise/internal/authz/bitbucketserver/integration_test.go | package bitbucketserver
import (
"testing"
)
func TestIntegration(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
cli, save := newClient(t, "BitbucketServer")
defer save()
f := newFixtures()
f.load(t, cli)
for _, tc := range []struct {
name string
test func(*testing.T)
}{
{"Provider/FetchAccount", testProviderFetchAccount(f, cli)},
{"Provider/FetchUserPerms", testProviderFetchUserPerms(f, cli)},
{"Provider/FetchRepoPerms", testProviderFetchRepoPerms(f, cli)},
} {
t.Run(tc.name, tc.test)
}
}
|
feieryouyiji/learningpy | 2020-04-19/test_enum.py | <reponame>feieryouyiji/learningpy<gh_stars>0
from enum import Enum, unique
@unique
class Weekday(Enum):
Sun = 0 # Sun的value被设定为0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
print(Weekday.Sun)
print(Weekday.Sun.value)
print(type(Weekday)) |
MarioMatschgi/Minecraft-Plugins | _Eclipse/_SpigotDecompiled/work/decompile-cf6b1333/net/minecraft/server/Slot.java | <filename>_Eclipse/_SpigotDecompiled/work/decompile-cf6b1333/net/minecraft/server/Slot.java
package net.minecraft.server;
public class Slot {
public final int index;
public final IInventory inventory;
public int rawSlotIndex;
public int f;
public int g;
public Slot(IInventory iinventory, int i, int j, int k) {
this.inventory = iinventory;
this.index = i;
this.f = j;
this.g = k;
}
public void a(ItemStack itemstack, ItemStack itemstack1) {
int i = itemstack1.getCount() - itemstack.getCount();
if (i > 0) {
this.a(itemstack1, i);
}
}
protected void a(ItemStack itemstack, int i) {}
protected void b(int i) {}
protected void c(ItemStack itemstack) {}
public ItemStack a(EntityHuman entityhuman, ItemStack itemstack) {
this.f();
return itemstack;
}
public boolean isAllowed(ItemStack itemstack) {
return true;
}
public ItemStack getItem() {
return this.inventory.getItem(this.index);
}
public boolean hasItem() {
return !this.getItem().isEmpty();
}
public void set(ItemStack itemstack) {
this.inventory.setItem(this.index, itemstack);
this.f();
}
public void f() {
this.inventory.update();
}
public int getMaxStackSize() {
return this.inventory.getMaxStackSize();
}
public int getMaxStackSize(ItemStack itemstack) {
return this.getMaxStackSize();
}
public ItemStack a(int i) {
return this.inventory.splitStack(this.index, i);
}
public boolean a(IInventory iinventory, int i) {
return iinventory == this.inventory && i == this.index;
}
public boolean isAllowed(EntityHuman entityhuman) {
return true;
}
}
|
icco/fog | tests/fogdocker/requests/compute/image_create_tests.rb | <reponame>icco/fog
Shindo.tests("Fog::Compute[:fogdocker] | image_create request", 'fogdocker') do
compute = Fog::Compute[:fogdocker]
tests("Create image") do
response = compute.image_create({'fromImage' => 'mattdm/fedora', 'repo'=>'test', 'tag'=>'create_image'})
test("should be a kind of Hash") { response.kind_of? Hash}
test("should have an id") { !response['id'].nil? && !response['id'].empty? }
end
tests("Fail Creating image") do
begin
response = compute.image_create('fromImage' => 'not/exists')
test("should be a kind of Hash") { response.kind_of? Hash} #mock never raise exceptions
rescue => e
#should raise missing command in the create attributes.
test("error should be a kind of Docker::Error") { e.kind_of? Docker::Error::ServerError}
end
end
end
|
Rod1Andrade/lendbooks | lendbook-backend/src/main/java/com/github/rod1andrade/lendbookbackend/features/mail/infra/events/IDispatchMailEvent.java | <filename>lendbook-backend/src/main/java/com/github/rod1andrade/lendbookbackend/features/mail/infra/events/IDispatchMailEvent.java
package com.github.rod1andrade.lendbookbackend.features.mail.infra.events;
import com.github.rod1andrade.lendbookbackend.features.mail.core.entities.Mail;
/**
* @author <NAME>
*/
public interface IDispatchMailEvent {
void send(Mail mail);
}
|
nateshao/design-demo | 5-00-singleton/src/main/java/nateshao/design/demo/singleton/Singleton_03_hungry_man.java | <reponame>nateshao/design-demo<gh_stars>1-10
package nateshao.design.demo.singleton;
/**
* @date Created by 邵桐杰 on 2020/12/10 11:20
* @微信公众号 <PASSWORD>
* @个人网站 www.nateshao.cn
* @博客 https://nateshao.gitee.io
* @GitHub https://github.com/nateshao
* @Gitee https://gitee.com/nateshao
* Description: 饿汉模式(线程安全)
* <p>
* 此种⽅式与我们开头的第⼀个实例化 Map 基本⼀致,在程序启动的时候直接运⾏加载,后续有外
* 部需要使⽤的时候获取即可。 Inner class
* 但此种⽅式并不是懒加载,也就是说⽆论你程序中是否⽤到这样的类都会在程序启动之初进⾏创建。
* 那么这种⽅式导致的问题就像你下载个游戏软件,可能你游戏地图还没有打开呢,但是程序已经将
* 这些地图全部实例化。到你⼿机上最明显体验就⼀开游戏内存满了,⼿机卡了,需要换了。
*/
public class Singleton_03_hungry_man {
private static Singleton_03_hungry_man instance = new Singleton_03_hungry_man();
private Singleton_03_hungry_man() {
}
public static Singleton_03_hungry_man getInstance() {
return instance;
}
}
|
snpmyn/Widget | library/src/main/java/com/zsp/library/sidebar/AcronymSorting.java | <gh_stars>0
package com.zsp.library.sidebar;
import com.zsp.library.contact.bean.ContactBean;
import java.util.Comparator;
/**
* @decs: 首字母排序
* @author: 郑少鹏
* @date: 2019/9/12 16:48
*/
public class AcronymSorting implements Comparator<ContactBean> {
@Override
public int compare(ContactBean contactBean, ContactBean contactBean1) {
if (contactBean == null || contactBean1 == null) {
return 0;
}
String lhsSortLetters = contactBean.getIndex().substring(0, 1).toUpperCase();
String rhsSortLetters = contactBean1.getIndex().substring(0, 1).toUpperCase();
return lhsSortLetters.compareTo(rhsSortLetters);
}
}
|
93million/certcache | src/extensions/certbot/getBundle.js | const path = require('path')
const fs = require('fs')
const util = require('util')
const readFile = util.promisify(fs.readFile)
module.exports = async (cert) => {
const dirname = path.dirname(cert.certPath)
return {
cert: await readFile(`${dirname}/cert.pem`),
chain: await readFile(`${dirname}/chain.pem`),
privkey: await readFile(`${dirname}/privkey.pem`)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.