repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
CCAFS/AMKN
|
wp-content/themes/amkn_theme/js/jquery.reveal.js
|
4851
|
/*
* jQuery Reveal Plugin 1.0
* www.ZURB.com
* Copyright 2010, ZURB
* Free to use under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
/*---------------------------
Defaults for Reveal
----------------------------*/
/*---------------------------
Listener for data-reveal-id attributes
----------------------------*/
$('a[data-reveal-id]').live('click', function(e) {
e.preventDefault();
var modalLocation = $(this).attr('data-reveal-id');
$('#'+modalLocation).reveal($(this).data());
});
/*---------------------------
Extend and Execute
----------------------------*/
$.fn.reveal = function(options) {
var defaults = {
animation: 'fadeAndPop', //fade, fadeAndPop, none
animationspeed: 300, //how fast animtions are
closeonbackgroundclick: true, //if you click background will modal close?
dismissmodalclass: 'close-reveal-modal' //the class of a button or element that will close an open modal
};
//Extend dem' options
var options = $.extend({}, defaults, options);
return this.each(function() {
/*---------------------------
Global Variables
----------------------------*/
var modal = $(this),
topMeasure = parseInt(modal.css('top')),
topOffset = modal.height() + topMeasure,
locked = false,
modalBG = $('.reveal-modal-bg');
/*---------------------------
Create Modal BG
----------------------------*/
if(modalBG.length == 0) {
modalBG = $('<div class="reveal-modal-bg" />').insertAfter(modal);
}
/*---------------------------
Open & Close Animations
----------------------------*/
//Entrance Animations
modal.bind('reveal:open', function () {
modalBG.unbind('click.modalEvent');
$('.' + options.dismissmodalclass).unbind('click.modalEvent');
if(!locked) {
lockModal();
if(options.animation == "fadeAndPop") {
modal.css({'top': $(document).scrollTop()-topOffset, 'opacity' : 0, 'visibility' : 'visible'});
modalBG.fadeIn(options.animationspeed/2);
modal.delay(options.animationspeed/2).animate({
"top": $(document).scrollTop()+topMeasure + 'px',
"opacity" : 1
}, options.animationspeed,unlockModal());
}
if(options.animation == "fade") {
modal.css({'opacity' : 0, 'visibility' : 'visible', 'top': $(document).scrollTop()+topMeasure});
modalBG.fadeIn(options.animationspeed/2);
modal.delay(options.animationspeed/2).animate({
"opacity" : 1
}, options.animationspeed,unlockModal());
}
if(options.animation == "none") {
modal.css({'visibility' : 'visible', 'top':$(document).scrollTop()+topMeasure});
modalBG.css({"display":"block"});
unlockModal()
}
}
modal.unbind('reveal:open');
});
//Closing Animation
modal.bind('reveal:close', function () {
if(!locked) {
lockModal();
if(options.animation == "fadeAndPop") {
modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
modal.animate({
"top": $(document).scrollTop()-topOffset + 'px',
"opacity" : 0
}, options.animationspeed/2, function() {
modal.css({'top':topMeasure, 'opacity' : 1, 'visibility' : 'hidden'});
unlockModal();
});
}
if(options.animation == "fade") {
modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
modal.animate({
"opacity" : 0
}, options.animationspeed, function() {
modal.css({'opacity' : 1, 'visibility' : 'hidden', 'top' : topMeasure});
unlockModal();
});
}
if(options.animation == "none") {
modal.css({'visibility' : 'hidden', 'top' : topMeasure});
modalBG.css({'display' : 'none'});
}
}
modal.unbind('reveal:close');
});
/*---------------------------
Open and add Closing Listeners
----------------------------*/
//Open Modal Immediately
modal.trigger('reveal:open')
//Close Modal Listeners
var closeButton = $('.' + options.dismissmodalclass).bind('click.modalEvent', function () {
modal.trigger('reveal:close')
});
if(options.closeonbackgroundclick) {
modalBG.css({"cursor":"pointer"})
modalBG.bind('click.modalEvent', function () {
modal.trigger('reveal:close')
});
}
$('body').keyup(function(e) {
if(e.which===27){ modal.trigger('reveal:close'); } // 27 is the keycode for the Escape key
});
/*---------------------------
Animations Locks
----------------------------*/
function unlockModal() {
locked = false;
}
function lockModal() {
locked = true;
}
});//each call
}//orbit plugin call
})(jQuery);
|
gpl-3.0
|
will-bainbridge/OpenFOAM-dev
|
src/parallel/decompose/decompositionMethods/structuredDecomp/structuredDecomp.C
|
5261
|
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2011-2018 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM 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 General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "structuredDecomp.H"
#include "addToRunTimeSelectionTable.H"
#include "FaceCellWave.H"
#include "topoDistanceData.H"
#include "fvMeshSubset.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
defineTypeNameAndDebug(structuredDecomp, 0);
addToRunTimeSelectionTable
(
decompositionMethod,
structuredDecomp,
dictionary
);
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::structuredDecomp::structuredDecomp(const dictionary& decompositionDict)
:
decompositionMethod(decompositionDict),
methodDict_(decompositionDict_.optionalSubDict(typeName + "Coeffs")),
patches_(methodDict_.lookup("patches"))
{
methodDict_.set("numberOfSubdomains", nDomains());
method_ = decompositionMethod::New(methodDict_);
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
bool Foam::structuredDecomp::parallelAware() const
{
return method_().parallelAware();
}
Foam::labelList Foam::structuredDecomp::decompose
(
const polyMesh& mesh,
const pointField& cc,
const scalarField& cWeights
)
{
const polyBoundaryMesh& pbm = mesh.boundaryMesh();
const labelHashSet patchIDs(pbm.patchSet(patches_));
label nFaces = 0;
forAllConstIter(labelHashSet, patchIDs, iter)
{
nFaces += pbm[iter.key()].size();
}
// Extract a submesh.
labelHashSet patchCells(2*nFaces);
forAllConstIter(labelHashSet, patchIDs, iter)
{
const labelUList& fc = pbm[iter.key()].faceCells();
forAll(fc, i)
{
patchCells.insert(fc[i]);
}
}
// Subset the layer of cells next to the patch
fvMeshSubset subsetter(dynamic_cast<const fvMesh&>(mesh));
subsetter.setLargeCellSubset(patchCells);
const fvMesh& subMesh = subsetter.subMesh();
pointField subCc(cc, subsetter.cellMap());
scalarField subWeights(cWeights, subsetter.cellMap());
// Decompose the layer of cells
labelList subDecomp(method_().decompose(subMesh, subCc, subWeights));
// Transfer to final decomposition
labelList finalDecomp(cc.size(), -1);
forAll(subDecomp, i)
{
finalDecomp[subsetter.cellMap()[i]] = subDecomp[i];
}
// Field on cells and faces.
List<topoDistanceData> cellData(mesh.nCells());
List<topoDistanceData> faceData(mesh.nFaces());
// Start of changes
labelList patchFaces(nFaces);
List<topoDistanceData> patchData(nFaces);
nFaces = 0;
forAllConstIter(labelHashSet, patchIDs, iter)
{
const polyPatch& pp = pbm[iter.key()];
const labelUList& fc = pp.faceCells();
forAll(fc, i)
{
patchFaces[nFaces] = pp.start()+i;
patchData[nFaces] = topoDistanceData(finalDecomp[fc[i]], 0);
nFaces++;
}
}
// Propagate information inwards
FaceCellWave<topoDistanceData> deltaCalc
(
mesh,
patchFaces,
patchData,
faceData,
cellData,
mesh.globalData().nTotalCells()+1
);
// And extract
bool haveWarned = false;
forAll(finalDecomp, celli)
{
if (!cellData[celli].valid(deltaCalc.data()))
{
if (!haveWarned)
{
WarningInFunction
<< "Did not visit some cells, e.g. cell " << celli
<< " at " << mesh.cellCentres()[celli] << endl
<< "Assigning these cells to domain 0." << endl;
haveWarned = true;
}
finalDecomp[celli] = 0;
}
else
{
finalDecomp[celli] = cellData[celli].data();
}
}
return finalDecomp;
}
Foam::labelList Foam::structuredDecomp::decompose
(
const labelListList& globalPointPoints,
const pointField& points,
const scalarField& pointWeights
)
{
NotImplemented;
return labelList::null();
}
// ************************************************************************* //
|
gpl-3.0
|
SpyderTL/OZone
|
OZone/Programs/Compilers/Subleq/SubleqCompiler16.cs
|
1559
|
using System.IO;
using System.Linq;
using System.Diagnostics;
using OZone.Programs;
using System;
namespace OZone.Programs.Compilers.Subleq
{
public class SubleqCompiler16 : ProgramCompiler
{
public override uint Compile(Program program, MemoryAddress baseAddress)
{
var length = 0U;
// Assign memory addresses
MemoryAddress position = new MemoryAddress { Segment = baseAddress.Segment, Offset = baseAddress.Offset };
foreach(ProgramSegment segment in program.Segments)
{
if (segment.Address == null)
segment.Address = new MemoryAddress
{
Offset = position.Offset,
Segment = position.Segment
};
var length2 = GetLength(segment);
length += length2;
position.Offset += length2;
}
return length;
}
public override void Write(Program program, BinaryWriter writer)
{
// Compile program bytes
foreach (ProgramSegment segment in program.Segments)
{
if (segment is StringValue)
foreach (var character in ((StringValue)segment).Value)
writer.Write((short)character);
else if (segment is LongValue)
writer.Write((short)((LongValue)segment).Value);
else if (segment is AddressOf)
writer.Write((short)((AddressOf)segment).Segment.Address.Offset);
}
}
public override uint GetLength(ProgramSegment segment)
{
if (segment is StringValue)
return (uint)(((StringValue)segment).Value.Length * 2);
else if (segment is Label)
return 0;
else
return 2;
}
}
}
|
gpl-3.0
|
gi0e5b06/lmms
|
plugins/SynthGDX/SynthGDX.cpp
|
45670
|
/*
* SynthGDX.cpp - modular synth
*
* Copyright (c) 2018 gi0e5b06 (on github.com)
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* 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
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "SynthGDX.h"
#include "BufferManager.h"
#include "Engine.h"
#include "InstrumentPlayHandle.h"
#include "InstrumentTrack.h"
#include "MixHelpers.h"
#include "Mixer.h"
#include "NotePlayHandle.h"
#include "PerfLog.h"
#include "SynthGDXView.h"
#include "WaveFormStandard.h"
#include "debug.h"
#include "embed.h"
#include <QDomDocument>
//#include "lmms_math.h"
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT synthgdx_plugin_descriptor = {
STRINGIFY(PLUGIN_NAME),
"SynthGDX",
QT_TRANSLATE_NOOP("pluginBrowser", "Oscillators vs Modulators"),
"gi0e5b06 (on github.com)",
0x0110,
Plugin::Instrument,
new PluginPixmapLoader("logo"),
NULL,
NULL};
}
OscillatorObject::OscillatorObject(Model* _parent, int _idx) :
Model(_parent, QString("SynthGDX Osc #%1").arg(_idx)),
m_enabledModel(_idx == 0, this, tr("O%1 active").arg(_idx + 1)),
m_wave1SymetricModel(
false, this, tr("O%1 symetric wave").arg(_idx + 1)),
m_wave1ReverseModel(false, this, tr("O%1 reverse wave").arg(_idx + 1)),
m_wave1BankModel(this, tr("O%1 wave bank").arg(_idx + 1)),
m_wave1IndexModel(this, tr("O%1 wave index").arg(_idx + 1)),
m_wave1AbsoluteModel(
false, this, tr("O%1 absolute wave").arg(_idx + 1)),
m_wave1OppositeModel(
false, this, tr("O%1 opposite wave").arg(_idx + 1)),
m_wave1ComplementModel(
false, this, tr("O%1 complementary wave").arg(_idx + 1)),
m_wave2SymetricModel(
false, this, tr("O%1 symetric wave").arg(_idx + 1)),
m_wave2ReverseModel(false, this, tr("O%1 reverse wave").arg(_idx + 1)),
m_wave2BankModel(this, tr("O%1 wave bank").arg(_idx + 1)),
m_wave2IndexModel(this, tr("O%1 wave index").arg(_idx + 1)),
m_wave2AbsoluteModel(
false, this, tr("O%1 absolute wave").arg(_idx + 1)),
m_wave2OppositeModel(
false, this, tr("O%1 opposite wave").arg(_idx + 1)),
m_wave2ComplementModel(
false, this, tr("O%1 complementary wave").arg(_idx + 1)),
m_waveMixModel(
0., 0., 1., 0.00001, this, tr("O%1 wave mix").arg(_idx + 1)),
m_waveAntialiasModel(
0., 0., 1., 0.001, this, tr("O%1 antialiassing").arg(_idx + 1)),
m_volumeModel(DefaultVolume / NB_OSCILLATORS,
MinVolume,
DefaultVolume,
0.01,
this,
tr("O%1 volume").arg(_idx + 1)),
m_panModel(DefaultPanning,
PanningLeft,
PanningRight,
0.01,
this,
tr("O%1 panning").arg(_idx + 1)),
m_coarseModel(0., //-_idx * KeysPerOctave,
-12 * KeysPerOctave,
12 * KeysPerOctave,
1.,
this,
tr("O%1 coarse detuning").arg(_idx + 1)),
m_fineLeftModel(0.,
-100.,
100.,
1.,
this,
tr("O%1 fine detuning left").arg(_idx + 1)),
m_fineRightModel(0.,
-100.,
100.,
1.,
this,
tr("O%1 fine detuning right").arg(_idx + 1)),
m_phaseOffsetModel(
0., 0., 360., 1., this, tr("O%1 phase-offset").arg(_idx + 1)),
m_stereoPhaseDetuningModel(
0.,
0.,
360.,
1.,
this,
tr("O%1 stereo phase-detuning").arg(_idx + 1)),
m_pulseCenterModel(0.5,
0.,
1.,
0.00001,
this,
tr("O%1 pulse center").arg(_idx + 1)),
m_pulseWidthModel(0.5,
0.,
1.,
0.00001,
this,
tr("O%1 pulse width").arg(_idx + 1)),
m_lfoEnabledModel(false, this, tr("O%1 LFO active").arg(_idx + 1)),
m_lfoTimeModel(55.,
0.001,
20000.,
0.001,
20000.,
this,
tr("O%1 LFO time").arg(_idx + 1)),
m_velocityAmountModel(
0., -1., 1., 0.01, this, tr("O%1 velocity").arg(_idx + 1)),
m_harm2Model(
0., -1., 1., 0.0001, this, tr("O%1 harmonics 2").arg(_idx + 1)),
m_harm3Model(
0., -1., 1., 0.0001, this, tr("O%1 harmonics 3").arg(_idx + 1)),
m_harm4Model(
0., -1., 1., 0.0001, this, tr("O%1 harmonics 4").arg(_idx + 1)),
m_harm5Model(
0., -1., 1., 0.0001, this, tr("O%1 harmonics 5").arg(_idx + 1)),
m_harm6Model(
0., -1., 1., 0.0001, this, tr("O%1 harmonics 6").arg(_idx + 1)),
m_harm7Model(
0., -1., 1., 0.0001, this, tr("O%1 harmonics 7").arg(_idx + 1)),
m_skewModel(1., 0., 1., 0.001, this, tr("O%1 anti-skew").arg(_idx + 1)),
m_smoothModel(
0., 0., 1.999, 0.001, this, tr("O%1 smoothing").arg(_idx + 1)),
m_slopeModel(
0., -144., 144., 0.00001, this, tr("O%1 slope").arg(_idx + 1)),
m_portamentoModel(
0., 0., 0.999, 0.001, this, tr("O%1 portamento").arg(_idx + 1)),
m_lowPassModel(
0., 0., 0.999, 0.001, this, tr("O%1 low pass").arg(_idx + 1)),
m_highPassModel(
0., 0., 0.999, 0.001, this, tr("O%1 high pass").arg(_idx + 1)),
m_wallModel(0., 0., 1., 0.001, this, tr("O%1 wall").arg(_idx + 1)),
m_frequencyModel(440.,
1.,
25000.,
0.01,
this,
tr("O%1 frequency").arg(_idx + 1)),
m_velocityModel(
0., 0., 1., 0.0001, this, tr("O%1 velocity").arg(_idx + 1))
{
WaveFormStandard::fillBankModel(m_wave1BankModel);
WaveFormStandard::fillBankModel(m_wave2BankModel);
WaveFormStandard::fillIndexModel(m_wave1IndexModel, 0);
WaveFormStandard::fillIndexModel(m_wave2IndexModel, 0);
m_wave1 = WaveFormStandard::get(0, 0);
m_wave2 = WaveFormStandard::get(0, 0);
m_lfoTimeModel.setScaleLogarithmic(true);
// const fpp_t FPP = Engine::mixer()->framesPerPeriod();
// m_GraphModel = new GraphModel(0., 1., FPP, NULL);
m_waveRing = new Ring(600); // Engine::mixer()->framesPerPeriod());
connect(&m_wave1BankModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave1IndexModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave1SymetricModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave1ReverseModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave1BankModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave1IndexModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave1AbsoluteModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave1OppositeModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave1ComplementModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave2BankModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave2IndexModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave2SymetricModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave2ReverseModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave2BankModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave2IndexModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave2AbsoluteModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave2OppositeModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_wave2ComplementModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_waveMixModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
connect(&m_waveAntialiasModel, SIGNAL(dataChanged()), this,
SLOT(updateWaveRing()));
}
OscillatorObject::~OscillatorObject()
{
}
Ring* OscillatorObject::waveRing()
{
return m_waveRing;
}
void OscillatorObject::updateWaveRing()
{
// qInfo("OscillatorObject::updateWaveRing()");
// m_waveRing->reset();
updateWaves(0); // reset(0);
const int rs = m_waveRing->size();
// const real_t step = 1. / 600.;
// real_t(Engine::mixer()->framesPerPeriod());
// for(real_t x = 1. - step; x >= 0.; x -= step)
for(int f = 0; f < rs; f++)
{
real_t x = real_t(f) / real_t(rs);
sampleFrame s;
s[0] = waveAt(0, x, 440.);
s[1] = waveAt(1, x, 440.);
m_waveRing->write(s);
}
// qInfo("wr: %f %f", waveAt(0, 0.45, 440.), waveAt(1, 0.45, 440.));
emit waveUpdated();
}
void OscillatorObject::reset(const fpp_t _f)
{
if(m_enabledModel.value())
{
m_updated = false;
updateWaves(_f);
updateVolumes(_f);
updateDetunings(_f);
updatePhaseOffsets(_f);
updateFrequencies(_f);
updatePulses(_f);
for(int ch = 1; ch >= 0; --ch)
{
m_toneBase[ch] = 0.;
m_addOutputBase[ch] = 0.;
m_previousInput1[ch] += m_currentInput1[ch];
m_previousInput2[ch] += m_currentInput2[ch];
m_currentInput1[ch] = 0.;
m_currentInput2[ch] = 0.;
m_waveMixModAmp[ch] = 1.;
m_waveMixModVal[ch] = 0.;
m_volumeModAmp[ch] = 1.;
m_volumeModVal[ch] = 0.;
m_detuningModAmp[ch] = 1.;
m_detuningModVal[ch] = 0.;
m_phaseOffsetModAmp[ch] = 1.;
m_phaseOffsetModVal[ch] = 0.;
m_frequencyModAmp[ch] = 1.;
m_frequencyModVal[ch] = 0.;
m_toneModAmp[ch] = 1.;
m_toneModVal[ch] = 0.;
m_pulseCenterModAmp[ch] = 0.5;
m_pulseCenterModVal[ch] = 0.;
m_pulseWidthModAmp[ch] = 0.5;
m_pulseWidthModVal[ch] = 0.;
m_addOutputModAmp[ch] = 1.;
m_addOutputModVal[ch] = 0.;
}
}
else
{
m_updated = true;
m_velocity = 0.5;
for(int ch = 1; ch >= 0; --ch)
{
m_frequencyBase[ch] = 55.;
m_phase[ch] = 0.;
m_phaseOffset[ch] = 0.;
m_currentOutput[ch] = 0.;
m_previousOutput[ch] = 0.;
m_averageOutput[ch] = 0.;
m_currentInput1[ch] = 0.;
m_previousInput1[ch] = 0.;
m_currentInput2[ch] = 0.;
m_previousInput2[ch] = 0.;
}
}
}
bool OscillatorObject::isUpdated()
{
return m_updated;
}
real_t OscillatorObject::waveAt(ch_cnt_t ch, real_t x, real_t w)
{
// pulse 0--p1=pc-pw/2--p--p2=pc+pw/2--1
real_t pc = m_pulseCenterBase[ch]
* (1. + m_pulseCenterModAmp[ch] * m_pulseCenterModVal[ch]);
real_t pw = m_pulseWidthBase[ch]
* (1. + m_pulseWidthModAmp[ch] * m_pulseWidthModVal[ch]);
pc = bound(0., pc, 1.);
pw = bound(0., pw, 1.);
real_t p1 = bound(0., pc - 0.5 * pw, 1.);
real_t p2 = bound(0., pc + 0.5 * pw, 1.);
if(x > 0. && x < 1.) // && pw < 1.)
{
if(x < 0.25)
x = p1 * x / 0.25;
else if(x < 0.75)
x = p1 + (p2 - p1) * (x - 0.25) / 0.5;
else
x = p2 + (1. - p2) * (x - 0.75) / 0.25;
}
x = qBound(0., x, 1.);
const real_t wm = bound(
0., m_waveMixBase[ch] + m_waveMixModAmp[ch] * m_waveMixModVal[ch],
1.);
real_t y = 0.;
if(wm < 1.)
{
real_t x1 = x;
if(m_reverse1)
x1 = 1. - x1;
if(m_symetric1)
{
if(x1 < 0.5)
x1 = 2. * x1;
else
x1 = 2. * (1. - x1);
}
real_t y1 = m_wave1->f(x1, m_waveAntialias * w);
if(m_complement1)
{
if(y1 < 0.)
y1 = -1. - y1;
else if(y1 > 0.)
y1 = 1. - y1;
else
{
real_t y1p = m_wave1->f(positivefraction(x1 + 0.99));
real_t y1n = m_wave1->f(positivefraction(x1 + 0.01));
if((y1p < 0. && y1n <= 0.) || (y1p <= 0. && y1n < 0.))
y1 = -1;
else if((y1p > 0. && y1n >= 0.) || (y1p >= 0. && y1n > 0.))
y1 = 1.;
// else y1=0.;
}
}
if(m_absolute1 && y1 < 0.)
y1 = -y1;
if(m_opposite1)
y1 = -y1;
y += (1. - wm) * y1;
}
if(wm > 0.)
{
real_t x2 = x;
if(m_reverse2)
x2 = 1. - x2;
if(m_symetric2)
{
if(x2 < 0.5)
x2 = 2. * x2;
else
x2 = 2. * (1. - x2);
}
real_t y2 = m_wave2->f(x2, m_waveAntialias * w);
if(m_complement2)
{
if(y2 < 0.)
y2 = -1. - y2;
else if(y2 > 0.)
y2 = 1. - y2;
else
{
real_t y2p = m_wave2->f(positivefraction(x2 + 0.99));
real_t y2n = m_wave2->f(positivefraction(x2 + 0.01));
if((y2p < 0. && y2n <= 0.) || (y2p <= 0. && y2n < 0.))
y2 = -1;
else if((y2p > 0. && y2n >= 0.) || (y2p >= 0. && y2n > 0.))
y2 = 1.;
// else y2=0.;
}
}
if(m_absolute2 && y2 < 0.)
y2 = -y2;
if(m_opposite2)
y2 = -y2;
y += wm * y2;
}
return y;
}
void OscillatorObject::update()
{
if(m_updated)
return;
for(int ch = 1; ch >= 0; --ch)
{
real_t w
= (m_frequencyBase[ch]
* (1.
+ m_frequencyModAmp[ch] * m_frequencyModVal[ch])
+ 1000. * m_toneModAmp[ch] * m_toneModVal[ch])
* (m_detuningBase[ch]
* (1. + m_detuningModAmp[ch] * m_detuningModVal[ch]));
w = qBound(-192000., w, 192000.);
real_t a = m_volumeBase[ch]
* (1. + m_volumeModAmp[ch] * m_volumeModVal[ch]);
a = qMin(abs(a), 1.);
// a=qBound(0.,a,1.);
real_t x = m_phase[ch];
// x += 44100. / Engine::mixer()->processingSampleRate();
x -= m_phaseOffset[ch];
m_phaseOffset[ch]
= m_phaseOffsetBase[ch]
* (1. + m_phaseOffsetModAmp[ch] * m_phaseOffsetModVal[ch]);
x += m_phaseOffset[ch];
x = fraction(x);
if(x < 0.)
x = fraction(x + 2.);
m_phase[ch] = x;
// x *= 44100. / Engine::mixer()->processingSampleRate();
x = fraction(x);
real_t y = waveAt(ch, x, w);
// harmonics
if(m_harm2 != 0.)
{
real_t xh2 = 2. * (x - m_phaseOffset[ch]) + m_phaseOffset[ch];
real_t yh2 = m_harm2 * waveAt(ch, xh2, 2. * w);
y += yh2;
}
if(m_harm3 != 0.)
{
real_t xh3 = 3. * (x - m_phaseOffset[ch]) + m_phaseOffset[ch];
real_t yh3 = m_harm3 * waveAt(ch, xh3, 3. * w);
y += yh3;
}
if(m_harm4 != 0.)
{
real_t xh4 = 4. * (x - m_phaseOffset[ch]) + m_phaseOffset[ch];
real_t yh4 = m_harm4 * waveAt(ch, xh4, 4. * w);
y += yh4;
}
if(m_harm5 != 0.)
{
real_t xh5 = 5. * (x - m_phaseOffset[ch]) + m_phaseOffset[ch];
real_t yh5 = m_harm5 * waveAt(ch, xh5, 5. * w);
y += yh5;
}
if(m_harm6 != 0.)
{
real_t xh6 = 6. * (x - m_phaseOffset[ch]) + m_phaseOffset[ch];
real_t yh6 = m_harm6 * waveAt(ch, xh6, 6. * w);
y += yh6;
}
if(m_harm7 != 0.)
{
real_t xh7 = 7. * (x - m_phaseOffset[ch]) + m_phaseOffset[ch];
real_t yh7 = m_harm7 * waveAt(ch, xh7, 7. * w);
y += yh7;
}
if(m_wall > 0.)
y = (y + waveAt(ch, fraction(x + 1. - m_wall), w)) / 2.;
y = a * y + m_addOutputModAmp[ch] * m_addOutputModVal[ch];
y *= m_velocity;
if(m_lowPass > 0.)
{
y = m_lowPass * m_previousOutput[ch] + (1. - m_lowPass) * y;
y = qBound(-1., y, 1.);
}
if(m_highPass > 0.)
{
y = (1. - m_highPass) * y - m_highPass * m_previousOutput[ch];
y = qBound(-1., y, 1.);
}
if(m_smooth > 0.)
{
real_t dy = 2. - m_smooth;
real_t py = m_previousOutput[ch];
// qInfo("y=%f py=%f dy=%f", y, py, dy);
if(abs(y - py) > dy)
{
y = py + dy * sign(y - py);
// qInfo("--> y=%f", y);
}
}
m_previousOutput[ch] = m_currentOutput[ch];
m_averageOutput[ch] = 0.999 * m_averageOutput[ch] + 0.001 * y;
if(m_skew < 1.)
y -= (1. - m_skew) * m_averageOutput[ch];
m_currentOutput[ch] = y;
m_phase[ch] += w;
}
m_updated = true;
}
real_t OscillatorObject::output(const ch_cnt_t _ch)
{
return m_updated ? m_currentOutput[_ch] : m_previousOutput[_ch];
}
void OscillatorObject::input1(const ch_cnt_t _ch, const real_t _in)
{
if(!m_updated)
m_previousInput1[_ch] = _in;
else
m_currentInput1[_ch] = _in;
}
void OscillatorObject::input2(const ch_cnt_t _ch, const real_t _in)
{
if(!m_updated)
m_previousInput2[_ch] = _in;
else
m_currentInput2[_ch] = _in;
}
OscillatorObject::OscState::OscState()
{
// m_wave1 = WaveFormStandard::get(0, 0);
// m_wave2 = WaveFormStandard::get(0, 0);
for(int ch = 1; ch >= 0; --ch)
{
m_phase[ch] = 0.;
m_phaseOffset[ch] = 0.;
m_currentOutput[ch] = 0.;
m_previousOutput[ch] = 0.;
m_averageOutput[ch] = 0.;
m_currentInput1[ch] = 0.;
m_previousInput1[ch] = 0.;
m_currentInput2[ch] = 0.;
m_previousInput2[ch] = 0.;
}
}
void OscillatorObject::restoreFromState(OscState* _state)
{
if(_state == NULL)
return;
m_frequencyModel.setAutomatedValue(_state->m_frequency);
m_velocityModel.setAutomatedValue(_state->m_velocity);
// m_wave1 = _state->m_wave1;
// m_wave2 = _state->m_wave2;
for(int ch = 1; ch >= 0; --ch)
{
m_phase[ch] = _state->m_phase[ch];
m_phaseOffset[ch] = _state->m_phaseOffset[ch];
m_currentOutput[ch] = _state->m_currentOutput[ch];
m_previousOutput[ch] = _state->m_previousOutput[ch];
m_averageOutput[ch] = _state->m_averageOutput[ch];
m_currentInput1[ch] = _state->m_currentInput1[ch];
m_previousInput1[ch] = _state->m_previousInput1[ch];
m_currentInput2[ch] = _state->m_currentInput2[ch];
m_previousInput2[ch] = _state->m_previousInput2[ch];
}
}
void OscillatorObject::saveToState(OscState* _state)
{
if(_state == NULL)
return;
_state->m_frequency = m_frequencyModel.value();
_state->m_velocity = m_velocityModel.value();
//_state->m_wave1 = m_wave1;
//_state->m_wave2 = m_wave2;
for(int ch = 1; ch >= 0; --ch)
{
_state->m_phase[ch] = m_phase[ch];
_state->m_phaseOffset[ch] = m_phaseOffset[ch];
_state->m_currentOutput[ch] = m_currentOutput[ch];
_state->m_previousOutput[ch] = m_previousOutput[ch];
_state->m_averageOutput[ch] = m_averageOutput[ch];
_state->m_currentInput1[ch] = m_currentInput1[ch];
_state->m_previousInput1[ch] = m_previousInput1[ch];
_state->m_currentInput2[ch] = m_currentInput2[ch];
_state->m_previousInput2[ch] = m_previousInput2[ch];
}
}
/*
bool OscillatorObject::syncOK(const real_t _coeff, const ch_cnt_t _ch)
{
const real_t old = m_phase[_ch];
m_phase[_ch] += _coeff;
// check whether m_phase is in next period
return (floor(m_phase[_ch]) > floor(old));
}
real_t OscillatorObject::syncInit(const ch_cnt_t _ch)
{
recalculatePhase(_ch);
return m_frequency[_ch] * m_detuning[_ch];
}
*/
void OscillatorObject::updateWaves(const fpp_t _f)
{
m_wave1 = WaveFormStandard::get(m_wave1BankModel.value(),
m_wave1IndexModel.value());
m_symetric1 = m_wave1SymetricModel.value();
m_reverse1 = m_wave1ReverseModel.value();
m_absolute1 = m_wave1AbsoluteModel.value();
m_opposite1 = m_wave1OppositeModel.value();
m_complement1 = m_wave1ComplementModel.value();
m_wave2 = WaveFormStandard::get(m_wave2BankModel.value(),
m_wave2IndexModel.value());
m_symetric2 = m_wave2SymetricModel.value();
m_reverse2 = m_wave2ReverseModel.value();
m_absolute2 = m_wave2AbsoluteModel.value();
m_opposite2 = m_wave2OppositeModel.value();
m_complement2 = m_wave2ComplementModel.value();
m_waveMixBase[0] = m_waveMixModel.value(); // * 2. - 1;
m_waveMixBase[1] = m_waveMixBase[0];
m_waveAntialias = m_waveAntialiasModel.value();
m_harm2 = m_harm2Model.value();
m_harm3 = m_harm3Model.value();
m_harm4 = m_harm4Model.value();
m_harm5 = m_harm5Model.value();
m_harm6 = m_harm6Model.value();
m_harm7 = m_harm7Model.value();
}
void OscillatorObject::updatePulses(const fpp_t _f)
{
m_pulseCenterBase[0] = m_pulseCenterModel.value();
m_pulseCenterBase[1] = m_pulseCenterBase[0];
m_pulseWidthBase[0] = m_pulseWidthModel.value();
m_pulseWidthBase[1] = m_pulseWidthBase[0];
}
void OscillatorObject::updateFrequencies(const fpp_t _f)
{
real_t w;
if(m_lfoEnabledModel.value())
w = 1000. / m_lfoTimeModel.value();
else
w = m_frequencyModel.value();
m_frequencyBase[0] = w;
m_frequencyBase[1] = w;
m_lowPass = m_lowPassModel.value();
m_highPass = m_highPassModel.value();
m_wall = m_wallModel.value();
}
void OscillatorObject::updateVolumes(const fpp_t _f)
{
if(m_panModel.value() >= 0.)
{
m_volumeBase[1] = m_volumeModel.value() / DefaultVolume;
const real_t panningFactorLeft
= 1. - m_panModel.value() / (real_t)PanningRight;
m_volumeBase[0] = panningFactorLeft * m_volumeBase[1];
}
else
{
m_volumeBase[0] = m_volumeModel.value() / DefaultVolume;
const real_t panningFactorRight
= 1. + m_panModel.value() / (real_t)PanningRight;
m_volumeBase[1] = panningFactorRight * m_volumeBase[0];
}
real_t vv = m_velocityModel.value();
real_t va = m_velocityAmountModel.value();
m_velocity = (1. - va) + va * (vv - 0.5);
real_t sv = m_smoothModel.value();
m_smooth = sv * sv / 2.;
real_t sk = m_skewModel.value();
m_skew = sk;
}
void OscillatorObject::updateDetunings(const fpp_t _f)
{
m_detuningBase[0] = fastexp2((m_coarseModel.value() * 100.
+ m_fineLeftModel.value())
/ 1200.)
/ Engine::mixer()->processingSampleRate();
m_detuningBase[1] = fastexp2((m_coarseModel.value() * 100.
+ m_fineRightModel.value())
/ 1200.)
/ Engine::mixer()->processingSampleRate();
}
void OscillatorObject::updatePhaseOffsets(const fpp_t _f)
{
m_stereoPhase = m_stereoPhaseDetuningModel.value() / 360.;
m_phaseOffsetBase[1] = m_phaseOffsetModel.value() / 360.;
m_phaseOffsetBase[0] = m_phaseOffsetBase[1] + m_stereoPhase;
}
ModulatorObject::ModulatorObject(Model* _parent, int _idx) :
Model(_parent, QString("SynthGDX Mod #%1").arg(_idx)),
m_enabledModel(false, this, tr("M%1 active").arg(_idx + 1)),
m_algoModel(this, tr("M%1 type").arg(_idx + 1)),
m_modulatedModel(this, tr("Modulated oscillator")), //.arg(_idx + 1)),
m_modulatorModel(this, tr("Modulating oscillator")) //.arg(_idx + 1))
{
m_algoModel.addItem("Phase"); // 0
m_algoModel.addItem("Amplitude"); // 1
m_algoModel.addItem("Signal mix"); // 2
m_algoModel.addItem("Synchronization"); // 3
m_algoModel.addItem("Frequency"); // 4
m_algoModel.addItem("Tone (CV VpO)"); // 5
m_algoModel.addItem("Pulse Center"); // 6
m_algoModel.addItem("Pulse Width"); // 7
m_algoModel.addItem("Additive Output"); // 8
m_algoModel.addItem("Substractive Output"); // 9
m_algoModel.addItem("Wave Mixing"); // 10
m_algoModel.addItem("Input 1"); // 11
m_algoModel.addItem("Input 2"); // 12
for(int o = 0; o < NB_OSCILLATORS; ++o)
{
m_modulatedModel.addItem(QString::number(o + 1));
m_modulatorModel.addItem(QString::number(o + 1));
}
}
ModulatorObject::~ModulatorObject()
{
}
bool ModulatorObject::isApplied()
{
return m_applied;
}
void ModulatorObject::reset(f_cnt_t)
{
m_applied = !m_enabledModel.value();
}
void ModulatorObject::apply(OscillatorObject* _modulated,
OscillatorObject* _modulator)
{
for(int ch = 1; ch >= 0; --ch)
{
real_t val = _modulator->output(ch);
switch(m_algoModel.value())
{
case 0:
_modulated->m_phaseOffsetModVal[ch] += val;
break;
case 1:
_modulated->m_volumeModVal[ch] += val;
break;
case 4:
_modulated->m_frequencyModVal[ch] += val;
break;
case 5:
_modulated->m_toneModVal[ch] += val;
break;
case 6:
_modulated->m_pulseCenterModVal[ch] += val;
break;
case 7:
_modulated->m_pulseWidthModVal[ch] += val;
break;
case 8:
_modulated->m_addOutputModVal[ch] += val;
break;
case 9:
_modulated->m_addOutputModVal[ch] -= val;
break;
case 10:
_modulated->m_waveMixModVal[ch] += val;
break;
case 11:
_modulated->input1(ch, val);
break;
case 12:
_modulated->input2(ch, val);
break;
}
}
m_applied = true;
}
SynthGDX::SynthGDX(InstrumentTrack* _instrumentTrack) :
Instrument(_instrumentTrack, &synthgdx_plugin_descriptor)
{
for(int o = NB_OSCILLATORS - 1; o >= 0; --o)
{
m_osc[o] = new OscillatorObject(this, o);
// m_osc[o]->m_enabledModel.setValue(o == 0);
}
for(int m = NB_MODULATORS - 1; m >= 0; --m)
{
m_mod[m] = new ModulatorObject(this, m);
// m_mod[m]->m_enabledModel.setValue(false);
m_mod[m]->m_modulatedModel.setValue(0);
m_mod[m]->m_modulatorModel.setValue((m + 1) % NB_OSCILLATORS);
}
connect(Engine::mixer(), SIGNAL(sampleRateChanged()), this,
SLOT(updateAllDetuning()));
}
SynthGDX::~SynthGDX()
{
for(int o = NB_OSCILLATORS - 1; o >= 0; --o)
{
// delete m_osc[i];
m_osc[o] = NULL;
}
for(int m = NB_MODULATORS - 1; m >= 0; --m)
{
// delete m_mod[i];
m_mod[m] = NULL;
}
}
void SynthGDX::saveSettings(QDomDocument& _doc, QDomElement& _this)
{
for(int i = 0; i < NB_OSCILLATORS; ++i)
{
QString is = QString::number(i);
m_osc[i]->m_enabledModel.saveSettings(_doc, _this,
"osc_enabled" + is);
m_osc[i]->m_waveMixModel.saveSettings(_doc, _this, "wave_mix" + is);
m_osc[i]->m_wave1SymetricModel.saveSettings(_doc, _this,
"wave1_symetric" + is);
m_osc[i]->m_wave1ReverseModel.saveSettings(_doc, _this,
"wave1_reverse" + is);
/* deprecated
m_osc[i]->m_wave1IndexModel.saveSettings(_doc, _this,
"wave1type" + is);
m_osc[i]->m_wave2IndexModel.saveSettings(_doc, _this,
"wave2type" + is);
*/
m_osc[i]->m_wave1BankModel.saveSettings(_doc, _this,
"wave1_bank" + is);
m_osc[i]->m_wave1IndexModel.saveSettings(_doc, _this,
"wave1_index" + is);
m_osc[i]->m_wave1AbsoluteModel.saveSettings(_doc, _this,
"wave1_absolute" + is);
m_osc[i]->m_wave1OppositeModel.saveSettings(_doc, _this,
"wave1_opposite" + is);
m_osc[i]->m_wave1ComplementModel.saveSettings(
_doc, _this, "wave1_complement" + is);
m_osc[i]->m_wave2SymetricModel.saveSettings(_doc, _this,
"wave2_symetric" + is);
m_osc[i]->m_wave2ReverseModel.saveSettings(_doc, _this,
"wave2_reverse" + is);
m_osc[i]->m_wave2BankModel.saveSettings(_doc, _this,
"wave2_bank" + is);
m_osc[i]->m_wave2IndexModel.saveSettings(_doc, _this,
"wave2_index" + is);
m_osc[i]->m_wave2AbsoluteModel.saveSettings(_doc, _this,
"wave2_absolute" + is);
m_osc[i]->m_wave2OppositeModel.saveSettings(_doc, _this,
"wave2_opposite" + is);
m_osc[i]->m_wave2ComplementModel.saveSettings(
_doc, _this, "wave2_complement" + is);
m_osc[i]->m_volumeModel.saveSettings(_doc, _this, "vol" + is);
m_osc[i]->m_panModel.saveSettings(_doc, _this, "pan" + is);
m_osc[i]->m_coarseModel.saveSettings(_doc, _this, "coarse" + is);
m_osc[i]->m_fineLeftModel.saveSettings(_doc, _this, "finel" + is);
m_osc[i]->m_fineRightModel.saveSettings(_doc, _this, "finer" + is);
m_osc[i]->m_lowPassModel.saveSettings(_doc, _this,
"filter_lowpass" + is);
m_osc[i]->m_highPassModel.saveSettings(_doc, _this,
"filter_highpass" + is);
m_osc[i]->m_wallModel.saveSettings(_doc, _this, "filter_wall" + is);
m_osc[i]->m_phaseOffsetModel.saveSettings(_doc, _this,
"phoffset" + is);
m_osc[i]->m_stereoPhaseDetuningModel.saveSettings(_doc, _this,
"stphdetun" + is);
m_osc[i]->m_pulseCenterModel.saveSettings(_doc, _this,
"pulse_center" + is);
m_osc[i]->m_pulseWidthModel.saveSettings(_doc, _this,
"pulse_width" + is);
m_osc[i]->m_lfoEnabledModel.saveSettings(_doc, _this,
"lfo_enabled" + is);
m_osc[i]->m_lfoTimeModel.saveSettings(_doc, _this, "lfo_time" + is);
m_osc[i]->m_slopeModel.saveSettings(_doc, _this, "slope" + is);
m_osc[i]->m_portamentoModel.saveSettings(_doc, _this,
"portamento" + is);
}
for(int i = 0; i < NB_MODULATORS; ++i)
{
QString is = QString::number(i);
m_mod[i]->m_enabledModel.saveSettings(_doc, _this,
"mod_enabled" + is);
m_mod[i]->m_algoModel.saveSettings(_doc, _this, "algo" + is);
m_mod[i]->m_modulatedModel.saveSettings(_doc, _this,
"modulated" + is);
m_mod[i]->m_modulatorModel.saveSettings(_doc, _this,
"modulator" + is);
}
}
void SynthGDX::loadSettings(const QDomElement& _this)
{
for(int i = 0; i < NB_OSCILLATORS; ++i)
{
const QString is = QString::number(i);
// tmp compat
m_osc[i]->m_enabledModel.loadSettings(_this, "enabled" + is, false);
m_osc[i]->m_wave1IndexModel.loadSettings(_this, "wave1type" + is,
false);
m_osc[i]->m_wave2IndexModel.loadSettings(_this, "wave2type" + is,
false);
m_osc[i]->m_wave1ReverseModel.loadSettings(_this, "wave_reverse" + is,
false);
m_osc[i]->m_wave1AbsoluteModel.loadSettings(
_this, "wave_absolute" + is, false);
m_osc[i]->m_wave1OppositeModel.loadSettings(
_this, "wave_opposite" + is, false);
m_osc[i]->m_wave1ComplementModel.loadSettings(
_this, "wave_complement" + is, false);
m_osc[i]->m_wave1IndexModel.loadSettings(_this, "wave1_shape" + is,
false);
m_osc[i]->m_wave2IndexModel.loadSettings(_this, "wave2_shape" + is,
false);
// correct
m_osc[i]->m_enabledModel.loadSettings(_this, "osc_enabled" + is);
m_osc[i]->m_waveMixModel.loadSettings(_this, "wave_mix" + is);
m_osc[i]->m_wave1SymetricModel.loadSettings(_this,
"wave1_symetric" + is);
m_osc[i]->m_wave1ReverseModel.loadSettings(_this,
"wave1_reverse" + is);
m_osc[i]->m_wave1BankModel.loadSettings(_this, "wave1_bank" + is);
m_osc[i]->m_wave1IndexModel.loadSettings(_this, "wave1_index" + is);
m_osc[i]->m_wave1AbsoluteModel.loadSettings(_this,
"wave1_absolute" + is);
m_osc[i]->m_wave1OppositeModel.loadSettings(_this,
"wave1_opposite" + is);
m_osc[i]->m_wave1ComplementModel.loadSettings(
_this, "wave1_complement" + is);
m_osc[i]->m_wave2SymetricModel.loadSettings(_this,
"wave2_symetric" + is);
m_osc[i]->m_wave2ReverseModel.loadSettings(_this,
"wave2_reverse" + is);
m_osc[i]->m_wave2BankModel.loadSettings(_this, "wave2_bank" + is);
m_osc[i]->m_wave2IndexModel.loadSettings(_this, "wave2_index" + is);
m_osc[i]->m_wave2AbsoluteModel.loadSettings(_this,
"wave2_absolute" + is);
m_osc[i]->m_wave2OppositeModel.loadSettings(_this,
"wave2_opposite" + is);
m_osc[i]->m_wave2ComplementModel.loadSettings(
_this, "wave2_complement" + is);
m_osc[i]->m_volumeModel.loadSettings(_this, "vol" + is);
m_osc[i]->m_panModel.loadSettings(_this, "pan" + is);
m_osc[i]->m_coarseModel.loadSettings(_this, "coarse" + is);
m_osc[i]->m_fineLeftModel.loadSettings(_this, "finel" + is);
m_osc[i]->m_fineRightModel.loadSettings(_this, "finer" + is);
m_osc[i]->m_lowPassModel.loadSettings(_this, "filter_lowpass" + is);
m_osc[i]->m_highPassModel.loadSettings(_this, "filter_highpass" + is);
m_osc[i]->m_wallModel.loadSettings(_this, "filter_wall" + is);
m_osc[i]->m_phaseOffsetModel.loadSettings(_this, "phoffset" + is);
m_osc[i]->m_stereoPhaseDetuningModel.loadSettings(_this,
"stphdetun" + is);
m_osc[i]->m_pulseCenterModel.loadSettings(_this, "pulse_center" + is);
m_osc[i]->m_pulseWidthModel.loadSettings(_this, "pulse_width" + is);
m_osc[i]->m_lfoEnabledModel.loadSettings(_this, "lfo_enabled" + is);
m_osc[i]->m_lfoTimeModel.loadSettings(_this, "lfo_time" + is);
m_osc[i]->m_slopeModel.loadSettings(_this, "slope" + is);
m_osc[i]->m_portamentoModel.loadSettings(_this, "portamento" + is);
}
for(int i = 0; i < NB_MODULATORS; ++i)
{
const QString is = QString::number(i);
m_mod[i]->m_enabledModel.loadSettings(_this, "mod_enabled" + is);
m_mod[i]->m_algoModel.loadSettings(_this, "algo" + is);
m_mod[i]->m_modulatedModel.loadSettings(_this, "modulated" + is);
m_mod[i]->m_modulatorModel.loadSettings(_this, "modulator" + is);
}
}
/*
QString SynthGDX::nodeName() const
{
return synthgdx_plugin_descriptor.name;
}
*/
void SynthGDX::playNote(NotePlayHandle* _n, sampleFrame* _buf)
{
if(_n == nullptr)
{
qWarning("SynthGDX::playNote _n is null");
return;
}
if(_buf == nullptr)
{
qWarning("SynthGDX::playNote _buf is null");
return;
}
const fpp_t FPP = Engine::mixer()->framesPerPeriod();
// const bool isFinished = _n->isFinished();
// const bool isReleased = _n->isReleased();
const fpp_t frames = _n->framesLeftForCurrentPeriod();
const f_cnt_t offset = _n->noteOffset();
if(offset < 0 || offset >= FPP)
{
qWarning("SynthGDX::playNote invalid offset %d", offset);
return;
}
if(frames < 0 || frames > FPP)
{
qWarning("SynthGDX::playNote invalid frames %d, offset %d", frames,
offset);
return;
}
if(frames == 0)
{
qWarning("SynthGDX::playNote zero frames");
return;
}
QMutexLocker locker(&m_mtx);
SynthGDX::InstrState* state
= static_cast<SynthGDX::InstrState*>(_n->m_pluginData);
if(state == nullptr)
{
state = new SynthGDX::InstrState();
for(int o = NB_OSCILLATORS - 1; o >= 0; --o)
{
state->m_oscState[o].m_frequency
= m_osc[o]->m_frequencyModel.value();
state->m_oscState[o].m_velocity
= m_osc[o]->m_velocityModel.value();
/*
qInfo("new state n=%p O%d: f=%f v=%f", _n, o,
m_osc[o]->m_frequencyModel.value(),
m_osc[o]->m_velocityModel.value());
*/
}
_n->m_pluginData = state;
/*
qTrace("start phases: %f / %f", m_osc[0]->m_phase[0],
m_osc[0]->m_phase[1]);
*/
}
restoreFromState(state);
// PL_BEGIN("synthgdx computing");
const int tfp = _n->totalFramesPlayed();
const int fl = _n->framesLeft();
/*
qTrace("before phases: %f / %f", m_osc[0]->m_phase[0],
m_osc[0]->m_phase[1]);
*/
for(f_cnt_t f = offset; f < frames; ++f)
{
for(int o = NB_OSCILLATORS - 1; o >= 0; --o)
{
real_t slope = m_osc[o]->m_slopeModel.value();
if(slope != 0.)
slope = fastexp2(slope / 12. * (tfp + f - offset)
/ Engine::mixer()->processingSampleRate());
else
slope = 1.;
real_t portamento = m_osc[o]->m_portamentoModel.value();
portamento = 1.
- (1. - portamento) * 44.1
/ Engine::mixer()->processingSampleRate();
real_t ow = m_osc[o]->m_frequencyModel.value();
real_t nw = _n->frequency() * slope;
if(ow != nw)
{
ow = nw * (1. - portamento) + ow * portamento;
/*
if(f == 0)
qTrace("portamento n=%p p=%f nw=%f ow=%f", _n, portamento,
nw, ow);
if(f == 0 && slope != 1.)
qTrace("slope n=%p s=%f nw=%f ow=%f", _n, slope, nw, ow);
*/
m_osc[o]->m_frequencyModel.setAutomatedValue(ow);
}
real_t ov = m_osc[o]->m_velocityModel.value();
real_t nv = _n->getVolume() / DefaultVolume;
if(ov != nv)
{
ov = nv * (1. - portamento) + ov * portamento;
m_osc[o]->m_velocityModel.setAutomatedValue(nv);
}
}
for(int o = NB_OSCILLATORS - 1; o >= 0; --o)
m_osc[o]->reset(f);
for(int m = NB_MODULATORS - 1; m >= 0; --m)
m_mod[m]->reset(f);
for(int t = 1; t >= 0; --t)
{
for(int o = NB_OSCILLATORS - 1; o >= 0; --o)
{
if(m_osc[o]->isUpdated())
continue;
bool ready = true;
for(int m = NB_MODULATORS - 1; m >= 0; --m)
{
if(m_mod[m]->isApplied())
continue;
int modulated = m_mod[m]->m_modulatedModel.value();
if(modulated != o)
continue;
if(modulated < 0 || modulated >= NB_OSCILLATORS)
continue;
int modulator = m_mod[m]->m_modulatorModel.value();
if(modulator < 0 || modulator >= NB_OSCILLATORS)
continue;
ready = false;
if(m_osc[modulator]->isUpdated())
{
// qInfo("apply modulation %d <-- %d",
// modulated, modulator);
m_mod[m]->apply(m_osc[modulated], m_osc[modulator]);
}
}
if(ready || t == 0)
{
// qInfo("update oscillator %d (t=%d)", o, t);
m_osc[o]->update();
}
}
}
// if(f == FPP - 1)
// qTrace("before: signal %f/%f", _buf[f][0], _buf[f][1]);
const int fadeSz = 1024; // 256;
real_t fadeIn = (tfp + f - offset < fadeSz
? real_t(tfp + f - offset) / fadeSz
: 1.);
real_t fadeOut
= (fl < fadeSz ? real_t(fl + f - offset) / fadeSz : 1.);
_buf[f][0] += fadeIn * fadeOut * bound(-1., m_osc[0]->output(0), 1.);
_buf[f][1] += fadeIn * fadeOut * bound(-1., m_osc[0]->output(1), 1.);
// if(fadeOut<1.)
// qTrace("after: signal %f/%f fade %f/%f", _buf[f][0], _buf[f][1],
// fadeIn, fadeOut);
}
// PL_END("synthgdx computing");
/*
qTrace("end phases: %f / %f",
m_osc[0]->m_phase[0],
m_osc[0]->m_phase[1]);
*/
saveToState(state);
applyRelease(_buf, _n);
// m_GraphModel->setSamples(_buf);
instrumentTrack()->processAudioBuffer(_buf, frames + offset, _n);
}
void SynthGDX::saveToState(InstrState* _state)
{
for(int o = NB_OSCILLATORS - 1; o >= 0; --o)
m_osc[o]->saveToState(&_state->m_oscState[o]);
}
void SynthGDX::restoreFromState(InstrState* _state)
{
for(int o = NB_OSCILLATORS - 1; o >= 0; --o)
m_osc[o]->restoreFromState(&_state->m_oscState[o]);
}
void SynthGDX::deleteNotePluginData(NotePlayHandle* _n)
{
delete static_cast<OscillatorObject::OscState*>(_n->m_pluginData);
_n->m_pluginData = nullptr; // TMP ???
}
PluginView* SynthGDX::instantiateView(QWidget* _parent)
{
return new SynthGDXView(this, _parent);
}
void SynthGDX::updateAllDetuning()
{
for(int i = 0; i < NB_OSCILLATORS; ++i)
{
m_osc[i]->updateDetunings(0);
}
}
extern "C"
{
// necessary for getting instance out of shared lib
Plugin* PLUGIN_EXPORT lmms_plugin_main(Model*, void* _data)
{
return new SynthGDX(static_cast<InstrumentTrack*>(_data));
}
}
|
gpl-3.0
|
Fosstrak/fosstrak-webadapters
|
src/main/java/org/fosstrak/webadapters/epcis/ws/generated/Document.java
|
2521
|
package org.fosstrak.webadapters.epcis.ws.generated;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
*
* EPCglobal document properties for all messages.
*
*
* <p>Java class for Document complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Document">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="schemaVersion" use="required" type="{http://www.w3.org/2001/XMLSchema}decimal" />
* <attribute name="creationDate" use="required" type="{http://www.w3.org/2001/XMLSchema}dateTime" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Document", namespace = "urn:epcglobal:xsd:1")
@XmlSeeAlso({
EPCISDocumentType.class,
EPCISQueryDocumentType.class,
EPCISMasterDataDocumentType.class
})
public abstract class Document {
@XmlAttribute(required = true)
protected BigDecimal schemaVersion;
@XmlAttribute(required = true)
protected XMLGregorianCalendar creationDate;
/**
* Gets the value of the schemaVersion property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getSchemaVersion() {
return schemaVersion;
}
/**
* Sets the value of the schemaVersion property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setSchemaVersion(BigDecimal value) {
this.schemaVersion = value;
}
/**
* Gets the value of the creationDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getCreationDate() {
return creationDate;
}
/**
* Sets the value of the creationDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setCreationDate(XMLGregorianCalendar value) {
this.creationDate = value;
}
}
|
gpl-3.0
|
bozhink/ProcessingTools
|
src/ProcessingTools/Desktop/DbSeeder/Providers/SeederTypesProvider.cs
|
1570
|
namespace ProcessingTools.DbSeeder.Providers
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Contracts.Seeders;
using ProcessingTools.Contracts;
internal class SeederTypesProvider : ITypesProvider
{
private readonly string baseName = typeof(IDbSeeder).FullName;
private IEnumerable<Type> types;
public IEnumerable<Type> Types
{
get
{
if (this.types == null)
{
var lockKey = new object();
lock (lockKey)
{
if (this.types == null)
{
var assembly = Assembly.GetExecutingAssembly();
var types = assembly.GetTypes()
.Where(t => t.IsInterface &&
!t.IsGenericType &&
t.GetInterfaces()
.Any(i => i.FullName == this.baseName))
.ToArray();
if (types == null || types.Length < 1)
{
throw new ApplicationException("No seeders are found");
}
this.types = types;
}
}
}
return this.types;
}
}
}
}
|
gpl-3.0
|
screamer/netcoffee
|
include/lemon-1.2.3/test/graph_copy_test.cc
|
6452
|
/* -*- mode: C++; indent-tabs-mode: nil; -*-
*
* This file is a part of LEMON, a generic C++ optimization library.
*
* Copyright (C) 2003-2011
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
* (Egervary Research Group on Combinatorial Optimization, EGRES).
*
* Permission to use, modify and distribute this software is granted
* provided that this copyright notice appears in all copies. For
* precise terms see the accompanying LICENSE file.
*
* This software is provided "AS IS" with no warranty of any kind,
* express or implied, and with no claim as to its suitability for any
* purpose.
*
*/
#include <lemon/smart_graph.h>
#include <lemon/list_graph.h>
#include <lemon/lgf_reader.h>
#include <lemon/error.h>
#include "test_tools.h"
using namespace std;
using namespace lemon;
void digraph_copy_test() {
const int nn = 10;
// Build a digraph
SmartDigraph from;
SmartDigraph::NodeMap<int> fnm(from);
SmartDigraph::ArcMap<int> fam(from);
SmartDigraph::Node fn = INVALID;
SmartDigraph::Arc fa = INVALID;
std::vector<SmartDigraph::Node> fnv;
for (int i = 0; i < nn; ++i) {
SmartDigraph::Node node = from.addNode();
fnv.push_back(node);
fnm[node] = i * i;
if (i == 0) fn = node;
}
for (int i = 0; i < nn; ++i) {
for (int j = 0; j < nn; ++j) {
SmartDigraph::Arc arc = from.addArc(fnv[i], fnv[j]);
fam[arc] = i + j * j;
if (i == 0 && j == 0) fa = arc;
}
}
// Test digraph copy
ListDigraph to;
ListDigraph::NodeMap<int> tnm(to);
ListDigraph::ArcMap<int> tam(to);
ListDigraph::Node tn;
ListDigraph::Arc ta;
SmartDigraph::NodeMap<ListDigraph::Node> nr(from);
SmartDigraph::ArcMap<ListDigraph::Arc> er(from);
ListDigraph::NodeMap<SmartDigraph::Node> ncr(to);
ListDigraph::ArcMap<SmartDigraph::Arc> ecr(to);
digraphCopy(from, to).
nodeMap(fnm, tnm).arcMap(fam, tam).
nodeRef(nr).arcRef(er).
nodeCrossRef(ncr).arcCrossRef(ecr).
node(fn, tn).arc(fa, ta).run();
check(countNodes(from) == countNodes(to), "Wrong copy.");
check(countArcs(from) == countArcs(to), "Wrong copy.");
for (SmartDigraph::NodeIt it(from); it != INVALID; ++it) {
check(ncr[nr[it]] == it, "Wrong copy.");
check(fnm[it] == tnm[nr[it]], "Wrong copy.");
}
for (SmartDigraph::ArcIt it(from); it != INVALID; ++it) {
check(ecr[er[it]] == it, "Wrong copy.");
check(fam[it] == tam[er[it]], "Wrong copy.");
check(nr[from.source(it)] == to.source(er[it]), "Wrong copy.");
check(nr[from.target(it)] == to.target(er[it]), "Wrong copy.");
}
for (ListDigraph::NodeIt it(to); it != INVALID; ++it) {
check(nr[ncr[it]] == it, "Wrong copy.");
}
for (ListDigraph::ArcIt it(to); it != INVALID; ++it) {
check(er[ecr[it]] == it, "Wrong copy.");
}
check(tn == nr[fn], "Wrong copy.");
check(ta == er[fa], "Wrong copy.");
// Test repeated copy
digraphCopy(from, to).run();
check(countNodes(from) == countNodes(to), "Wrong copy.");
check(countArcs(from) == countArcs(to), "Wrong copy.");
}
void graph_copy_test() {
const int nn = 10;
// Build a graph
SmartGraph from;
SmartGraph::NodeMap<int> fnm(from);
SmartGraph::ArcMap<int> fam(from);
SmartGraph::EdgeMap<int> fem(from);
SmartGraph::Node fn = INVALID;
SmartGraph::Arc fa = INVALID;
SmartGraph::Edge fe = INVALID;
std::vector<SmartGraph::Node> fnv;
for (int i = 0; i < nn; ++i) {
SmartGraph::Node node = from.addNode();
fnv.push_back(node);
fnm[node] = i * i;
if (i == 0) fn = node;
}
for (int i = 0; i < nn; ++i) {
for (int j = 0; j < nn; ++j) {
SmartGraph::Edge edge = from.addEdge(fnv[i], fnv[j]);
fem[edge] = i * i + j * j;
fam[from.direct(edge, true)] = i + j * j;
fam[from.direct(edge, false)] = i * i + j;
if (i == 0 && j == 0) fa = from.direct(edge, true);
if (i == 0 && j == 0) fe = edge;
}
}
// Test graph copy
ListGraph to;
ListGraph::NodeMap<int> tnm(to);
ListGraph::ArcMap<int> tam(to);
ListGraph::EdgeMap<int> tem(to);
ListGraph::Node tn;
ListGraph::Arc ta;
ListGraph::Edge te;
SmartGraph::NodeMap<ListGraph::Node> nr(from);
SmartGraph::ArcMap<ListGraph::Arc> ar(from);
SmartGraph::EdgeMap<ListGraph::Edge> er(from);
ListGraph::NodeMap<SmartGraph::Node> ncr(to);
ListGraph::ArcMap<SmartGraph::Arc> acr(to);
ListGraph::EdgeMap<SmartGraph::Edge> ecr(to);
graphCopy(from, to).
nodeMap(fnm, tnm).arcMap(fam, tam).edgeMap(fem, tem).
nodeRef(nr).arcRef(ar).edgeRef(er).
nodeCrossRef(ncr).arcCrossRef(acr).edgeCrossRef(ecr).
node(fn, tn).arc(fa, ta).edge(fe, te).run();
check(countNodes(from) == countNodes(to), "Wrong copy.");
check(countEdges(from) == countEdges(to), "Wrong copy.");
check(countArcs(from) == countArcs(to), "Wrong copy.");
for (SmartGraph::NodeIt it(from); it != INVALID; ++it) {
check(ncr[nr[it]] == it, "Wrong copy.");
check(fnm[it] == tnm[nr[it]], "Wrong copy.");
}
for (SmartGraph::ArcIt it(from); it != INVALID; ++it) {
check(acr[ar[it]] == it, "Wrong copy.");
check(fam[it] == tam[ar[it]], "Wrong copy.");
check(nr[from.source(it)] == to.source(ar[it]), "Wrong copy.");
check(nr[from.target(it)] == to.target(ar[it]), "Wrong copy.");
}
for (SmartGraph::EdgeIt it(from); it != INVALID; ++it) {
check(ecr[er[it]] == it, "Wrong copy.");
check(fem[it] == tem[er[it]], "Wrong copy.");
check(nr[from.u(it)] == to.u(er[it]) || nr[from.u(it)] == to.v(er[it]),
"Wrong copy.");
check(nr[from.v(it)] == to.u(er[it]) || nr[from.v(it)] == to.v(er[it]),
"Wrong copy.");
check((from.u(it) != from.v(it)) == (to.u(er[it]) != to.v(er[it])),
"Wrong copy.");
}
for (ListGraph::NodeIt it(to); it != INVALID; ++it) {
check(nr[ncr[it]] == it, "Wrong copy.");
}
for (ListGraph::ArcIt it(to); it != INVALID; ++it) {
check(ar[acr[it]] == it, "Wrong copy.");
}
for (ListGraph::EdgeIt it(to); it != INVALID; ++it) {
check(er[ecr[it]] == it, "Wrong copy.");
}
check(tn == nr[fn], "Wrong copy.");
check(ta == ar[fa], "Wrong copy.");
check(te == er[fe], "Wrong copy.");
// Test repeated copy
graphCopy(from, to).run();
check(countNodes(from) == countNodes(to), "Wrong copy.");
check(countEdges(from) == countEdges(to), "Wrong copy.");
check(countArcs(from) == countArcs(to), "Wrong copy.");
}
int main() {
digraph_copy_test();
graph_copy_test();
return 0;
}
|
gpl-3.0
|
gohdan/DFC
|
known_files/hashes/bitrix/modules/form/install/components/bitrix/form.result.list.my/lang/ru/.parameters.php
|
61
|
Bitrix 16.5 Business Demo = 60945ef7be6f1fb5d4f7a1e65df312c2
|
gpl-3.0
|
gottcode/kapow
|
src/settings.cpp
|
1078
|
/*
SPDX-FileCopyrightText: 2012 Graeme Gott <graeme@gottcode.org>
SPDX-License-Identifier: GPL-3.0-or-later
*/
#include "settings.h"
#include <QDir>
//-----------------------------------------------------------------------------
static QString f_path;
static QWeakPointer<QSettings> f_settings;
//-----------------------------------------------------------------------------
Settings::Settings()
{
if (f_settings) {
m_settings = f_settings;
} else if (f_path.isEmpty()) {
f_settings = m_settings = QSharedPointer<QSettings>(new QSettings);
} else {
f_settings = m_settings = QSharedPointer<QSettings>(new QSettings(f_path, QSettings::IniFormat));
}
}
//-----------------------------------------------------------------------------
void Settings::setPath(const QString& path)
{
// Set path
f_path = path;
if (f_path.isEmpty()) {
return;
}
// Make sure location of INI file exists
QDir dir(f_path + "/../");
if (!dir.exists()) {
dir.mkpath(dir.absolutePath());
}
}
//-----------------------------------------------------------------------------
|
gpl-3.0
|
egwk/egwk
|
app/Console/Commands/Install/ApproveTranslationDraft.php
|
6523
|
<?php
namespace App\Console\Commands\Install;
use App\Models\Tables\Edition;
use Illuminate\Console\Command;
use Facades\ {
App\EGWK\Synch
};
class ApproveTranslationDraft extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'approve:draft {--f|file=} {--c|cleanup} {--x|noexport} {--r|refreshcache}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Approve translation draft by importing it to the live translation table';
/**
* Translation table
*
* @var string
*/
protected $translationTable = 'translation';
/**
* Metadata fields
*
* @var array
*/
protected $mandatoryMetadataFields = ['book_code', 'tr_code', 'tr_title', 'publisher_code', 'year', 'no', 'start_para_id', 'translator', 'language', 'text_id'];
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Export draft to txt
*
* @param string $translationCode
* @return void
*/
protected function export(string $translationCode): void
{
$this->output->writeln('Creating backup first.');
$this->call('export:draft', [
'--file' => $translationCode
]);
}
/**
* Cleanup book translation
*
* @param string $halfRecord
* @return void
*/
protected function cleanup(array $halfRecord): void
{
\DB::table($this->translationTable)
->where($halfRecord)
->delete();
}
/**
* Save metadata
*
* @param array $metadata
* @return void
*/
protected function saveMetadata(array $metadata): void
{
$edition = Edition::firstOrNew($metadata);
$edition->save();
$this->output->writeln('Metadata saved.');
}
/**
* Load metadata
*
* @param string $translationCode
* @return array
*/
protected function getMetadata(string $translationCode): array
{
$this->output->writeln('Checking metadata...');
$metadataFile = "synch/$translationCode.json";
$metadata = null;
if (!\Storage::exists($metadataFile)) {
$this->output->warning("Metadata file not found. Trying database.");
$bookCode = Synch::getBookCode($translationCode);
try {
$metadata = Edition::where('book_code', $bookCode)
->firstOrFail()
->toArray();
} catch (\Exception $e) {
$this->output->error("Metadata not found. Create $metadataFile first with relevant data.");
exit(1);
}
} else {
$metadata = json_decode(\Storage::get($metadataFile), true);
}
if (!array_has($metadata, $this->mandatoryMetadataFields)) {
$this->output->error("Invalid Metadata, missing fields in $metadataFile.");
exit(2);
}
$bookCode = array_get($metadata, 'book_code', '');
$halfRecord = [
'book_code' => $bookCode,
'lang' => array_get($metadata, 'language', ''),
'publisher' => array_get($metadata, 'publisher_code', ''),
'year' => array_get($metadata, 'year', ''),
'no' => array_get($metadata, 'no', ''),
];
return [
$bookCode,
$metadata,
$halfRecord
];
}
/**
* Merge translation draft with original
*
* @param string $bookCode
* @param string $translationCode
* @param array $halfRecord
* @return array
*/
protected function merge(string $bookCode, string $translationCode, array $halfRecord): array
{
//
// Joining translation draft with original:
//
// SELECT puborder, para_id, refcode_short,db_original.content, db_translation_draft.content as tr_content FROM db_original
// JOIN db_translation_draft ON db_translation_draft.seq = db_original.puborder
// WHERE db_translation_draft.code = '$translationCode'
// AND db_original.refcode_1 = '$metadata->book_code'
// ORDER BY puborder;
//
$this->output->writeln('Merging Translation with Original...');
$merged = Synch::merge($translationCode, $bookCode)
->get()
->map(function ($item) use ($halfRecord) {
return array_merge($halfRecord, [
'content' => $item->tr_content,
'para_id' => $item->para_id,
]);
})
->toArray();
return $merged;
}
/**
* Saving translations
*
* @param array $merged
*/
protected function saveTranslations(array $merged): void
{
$this->output->writeln('Inserting into Translation data table');
try {
\DB::table($this->translationTable)
->insert($merged);
} catch (\PDOException $e) {
if (str_contains($e->getMessage(), 'Duplicate entry')) {
$this->output->error("Translation already exists. Run with --cleanup.");
}
} catch (\Exception $e) {
}
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$translationCode = $this->option('file');
$cleanup = $this->option('cleanup');
$export = !$this->option('noexport');
$refreshcache = $this->option('refreshcache');
$this->output->writeln('Approving: ' . $translationCode);
if ($export) {
$this->export($translationCode);
}
[$bookCode, $metadata, $halfRecord] = $this->getMetadata($translationCode);
$this->saveMetadata($metadata);
if ($cleanup) {
$this->cleanup($halfRecord);
}
$merged = $this->merge($bookCode, $translationCode, $halfRecord);
$this->saveTranslations($merged);
if ($refreshcache) {
$this->refreshcache();
}
}
protected function refreshcache()
{
$this->call('migrate:rollback', [
'--path' => '/database/migrations/api/'
]);
$this->call('migrate', [
'--path' => '/database/migrations/api/'
]);
}
}
|
gpl-3.0
|
DBCDK/content-first
|
src/client/components/hoc/Holding/withHoldings.hoc.js
|
879
|
import React, {useState, useEffect} from 'react';
import {useDispatch, useSelector} from 'react-redux';
import {fetchHoldings} from '../../../redux/holdings.thunk';
/**
*
* withHoldings
*
* @param {object} pid - The pid for the material to fetch Holdings for
* @return {object} - returns the Holdings
**/
export const withHoldings = WrappedComponent => props => {
const {agencyId, branch, pid} = props;
const [hasDispatched, setHasDispatched] = useState(false);
const holdings = useSelector(store => store.holdings[pid]);
const dispatch = useDispatch();
useEffect(() => {
if (agencyId && branch && !hasDispatched) {
dispatch(fetchHoldings(agencyId, branch, pid));
setHasDispatched(true);
}
}, [agencyId, branch, pid, dispatch, hasDispatched]);
return <WrappedComponent pid={pid} holdings={holdings} />;
};
export default withHoldings;
|
gpl-3.0
|
BilledTrain380/sporttag-psa
|
app/frontend/e2e/protractor.conf.js
|
1858
|
// @ts-check
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const {SpecReporter} = require('jasmine-spec-reporter');
/**
* @type { import("protractor").Config }
*/
exports.config = {
allScriptsTimeout: 11000,
specs: [
"./src/app.e2e-spec.ts",
"./src/**/*.bpc.e2e-spec.ts",
"./src/**/close-participation.e2e-spec.ts",
"./src/**/*.apc.e2e-spec.ts",
"./src/**/reset-participation.e2e-spec.ts",
"./src/**/*.e2e-spec.ts"
],
capabilities: {
browserName: "chrome"
},
directConnect: true,
baseUrl: "http://127.0.0.1:4200",
params: {
username: "admin",
password: "admin",
psaLoginUrl: "http://127.0.0.1:8080/login",
},
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: () => {
}
},
onPrepare: async () => {
require("ts-node").register({
project: require('path').join(__dirname, './tsconfig.json')
});
jasmine.getEnv().addReporter(new SpecReporter({spec: {displayStacktrace: true}}));
await browser.waitForAngularEnabled(false);
console.log("Load login page: ", browser.params.psaLoginUrl);
await browser.driver.get(browser.params.psaLoginUrl);
browser.driver.sleep(500);
console.log("Perform login");
await browser.findElement(by.id("username")).sendKeys(browser.params.username);
await browser.findElement(by.id("password")).sendKeys(browser.params.password);
await browser.findElement(by.buttonText("Sign In")).click();
browser.driver.sleep(500);
console.log("Load psa application");
// await browser.driver.get(browser.baseUrl);
console.log("Wait for implicit flow redirect")
await browser.driver.sleep(5000);
await browser.waitForAngularEnabled(true);
}
};
|
gpl-3.0
|
lordantonelli/adapte-me
|
website/application/views/pages/dashboard.php
|
57
|
<?php
// Load Menu
$this->template->menu('dashboard');
?>
|
gpl-3.0
|
ankostis/ViTables
|
examples/scripts/nested_samples.py
|
3046
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2005-2007 Carabos Coop. V. All rights reserved
# Copyright (C) 2008-2017 Vicent Mas. All rights reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Author: Vicent Mas - vmas@vitables.org
#
# This script is based on a set of scripts by Francesc Alted.
"""A Table with nested records."""
import random
import tables
fileout = "nested_samples.h5"
# An example of enumerated structure
colors = tables.Enum(['red', 'green', 'blue'])
def write(h5file, desc, indexed):
fileh = tables.open_file(h5file, "w")
table = fileh.create_table(fileh.root, 'table', desc)
#for colname in indexed:
# table.colinstances[colname].create_index()
row = table.row
for i in range(10):
row['x'] = i
row['y'] = 10.2-i
row['z'] = i
row['color'] = colors[random.choice(['red', 'green', 'blue'])]
row['extra_info/name'] = "name%s" % i
row['extra_info/info2/info3/z4'] = i
# All the rest will be filled with defaults
row.append()
fileh.close()
# The sample nested class description
class Info(tables.IsDescription):
_v_pos = 2
Name = tables.StringCol(16, dflt='sample string')
Value = tables.Float64Col()
class Test(tables.IsDescription):
"""A description that has several columns"""
x = tables.Int32Col(shape=2, dflt=0, pos=0)
y = tables.Float64Col(dflt=1.2, shape=(2, 3))
z = tables.UInt8Col(dflt=1)
color = tables.EnumCol(colors, 'red', base='uint32', shape=(2,))
Info = Info()
class extra_info(tables.IsDescription):
_v_pos = 1
name = tables.StringCol(10)
value = tables.Float64Col(pos=0)
y2 = tables.Float64Col(dflt=1, shape=(2, 3), pos=1)
z2 = tables.UInt8Col(dflt=1)
class info2(tables.IsDescription):
y3 = tables.Float64Col(dflt=1, shape=(2, 3))
z3 = tables.UInt8Col(dflt=1)
name = tables.StringCol(10)
value = tables.EnumCol(colors, 'blue', base='uint32', shape=(1,))
class info3(tables.IsDescription):
name = tables.StringCol(10)
value = tables.Time64Col()
y4 = tables.Float64Col(dflt=1, shape=(2, 3))
z4 = tables.UInt8Col(dflt=1)
# Write the file and read it
write(fileout, Test, ['info/info2/z3'])
|
gpl-3.0
|
erudit/eruditorg
|
eruditorg/erudit/migrations/0031_auto_20160808_1613.py
|
2955
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-08-08 21:13
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
("contenttypes", "0002_remove_content_type_name"),
("erudit", "0030_auto_20160808_1531"),
]
operations = [
migrations.CreateModel(
name="KeywordTag",
fields=[
(
"id",
models.AutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
),
),
("name", models.CharField(max_length=100, unique=True, verbose_name="Name")),
("slug", models.SlugField(max_length=100, unique=True, verbose_name="Slug")),
(
"language",
models.CharField(
blank=True, max_length=10, null=True, verbose_name="Code langue"
),
),
],
options={
"verbose_name": "Mot-clé",
"verbose_name_plural": "Mots-clés",
},
),
migrations.CreateModel(
name="KeywordTaggedWhatever",
fields=[
(
"id",
models.AutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
),
),
("object_id", models.IntegerField(db_index=True, verbose_name="Object id")),
(
"content_type",
models.ForeignKey(
on_delete=models.deletion.CASCADE,
related_name="erudit_keywordtaggedwhatever_tagged_items",
to="contenttypes.ContentType",
verbose_name="Content type",
),
),
(
"tag",
models.ForeignKey(
on_delete=models.deletion.CASCADE,
related_name="erudit_keywordtaggedwhatever_items",
to="erudit.KeywordTag",
),
),
],
options={
"abstract": False,
},
),
migrations.RemoveField(
model_name="thesis",
name="keywords",
),
migrations.AddField(
model_name="eruditdocument",
name="keywords",
field=taggit.managers.TaggableManager(
help_text="A comma-separated list of tags.",
through="erudit.KeywordTaggedWhatever",
to="erudit.KeywordTag",
verbose_name="Tags",
),
),
]
|
gpl-3.0
|
CIFASIS/qss-solver
|
src/mmoc/ast/composition.cpp
|
8492
|
/*****************************************************************************
This file is part of QSS Solver.
QSS Solver is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QSS Solver 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with QSS Solver. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "composition.h"
#include <iostream>
#include <list>
#include "../util/ast_util.h"
#include "ast_builder.h"
#include "element.h"
#include "equation.h"
#include "expression.h"
#include "modification.h"
#include "statement.h"
/* Composition Class */
AST_Composition_::AST_Composition_(AST_ElementList el, AST_CompositionElementList cl)
: _composition_list(cl), _element_list(el), _annot(nullptr), _ext(nullptr)
{
}
CLASSP_PRINTER_IMP(AST_Composition);
AST_ElementList AST_Composition_::elementList() const { return _element_list; }
AST_CompositionElementList AST_Composition_::compositionList() const { return _composition_list; }
ostream &operator<<(ostream &ret, const AST_Composition_ &cm)
{
AST_CompositionElementListIterator it;
AST_ElementListIterator el_it;
foreach (el_it, cm.elementList())
ret << current_element(el_it) << endl;
foreach (it, cm.compositionList()) {
ret << current_element(it);
}
if (cm.externalCall() != nullptr) {
ret << " external ";
if (cm.externalCall()->language() != nullptr) {
ret << "\"" << cm.externalCall()->language() << "\"";
}
if (cm.externalCall()->annotation()->size()) {
AST_ListPrint(cm.externalCall()->annotation(), ret, "annotation(", ",", "", ")", true);
}
ret << ";" << endl;
}
return ret;
}
void AST_Composition_::setExternalFunctionCall(AST_External_Function_Call ext) { _ext = ext; }
AST_External_Function_Call AST_Composition_::externalCall() const { return _ext; }
void AST_Composition_::setAnnotation(AST_ArgumentList al) { _annot = al; }
void AST_Composition_::accept(AST_Visitor *visitor)
{
visitor->visit(this);
AST_ElementListIterator _element_list_it;
foreach (_element_list_it, _element_list) {
current_element(_element_list_it)->accept(visitor);
}
AST_CompositionElementListIterator _composition_list_it;
foreach (_composition_list_it, _composition_list) {
if (current_element(_composition_list_it)->hasElements()) {
current_element(_composition_list_it)->accept(visitor);
}
}
foreach (_composition_list_it, _composition_list) {
if (current_element(_composition_list_it)->hasEquations()) {
current_element(_composition_list_it)->accept(visitor);
}
}
foreach (_composition_list_it, _composition_list) {
if (current_element(_composition_list_it)->hasStatements()) {
current_element(_composition_list_it)->accept(visitor);
}
}
AST_ArgumentListIterator _annot_it;
foreach (_annot_it, _annot) {
current_element(_annot_it)->accept(visitor);
}
if (_ext != nullptr) {
_ext->accept(visitor);
}
visitor->leave(this);
}
bool AST_Composition_::hasCompositionList()
{
if (_composition_list == nullptr) {
return false;
}
return _composition_list->size() > 0;
}
bool AST_Composition_::hasExternalFunctionCall()
{
if (_ext == nullptr) {
return false;
}
return true;
}
bool AST_Composition_::hasAnnotation()
{
if (_annot == nullptr) {
return false;
}
return true;
}
/* Composition Element class */
AST_CompositionElement_::AST_CompositionElement_(AST_CompositionEqsAlgs eqs_algs) : _eqs_algs(eqs_algs), _el(newAST_ElementList()) {}
AST_CompositionElement_::AST_CompositionElement_(AST_ElementList el) : _eqs_algs(newAST_NullCompositionEquations()), _el(el)
{
AST_ElementListIterator it;
}
AST_CompositionEqsAlgs AST_CompositionElement_::getEquationsAlgs() { return _eqs_algs; }
AST_ElementList AST_CompositionElement_::getElementList() { return _el; }
ostream &operator<<(ostream &ret, const AST_CompositionElement_ &ce)
{
AST_EquationListIterator it;
AST_StatementListIterator st_it;
if (ce._eqs_algs != nullptr) {
if (ce._eqs_algs->getEquations()->size() > 0) {
MAKE_SPACE;
ret << (ce._eqs_algs->isInitial() ? "initial " : "");
ret << "equation" << endl;
}
BEGIN_BLOCK;
foreach (it, ce._eqs_algs->getEquations()) {
ret << current_element(it);
}
END_BLOCK;
if (ce._eqs_algs->getAlgorithms()->size() > 0) {
MAKE_SPACE;
ret << (ce._eqs_algs->isInitial() ? "initial " : "");
ret << "algorithm" << endl;
}
BEGIN_BLOCK;
foreach (st_it, ce._eqs_algs->getAlgorithms()) {
ret << current_element(st_it);
}
END_BLOCK;
}
AST_ElementListIterator et;
if (ce._el != nullptr) {
if (ce._el->size() > 0) {
ret << "public" << endl;
}
foreach (et, ce._el) {
ret << " " << current_element(et) << endl;
}
}
return ret;
}
void AST_CompositionElement_::accept(AST_Visitor *visitor)
{
visitor->visit(this);
if (_eqs_algs != nullptr) {
_eqs_algs->accept(visitor);
}
AST_ElementListIterator _el_it;
foreach (_el_it, _el) {
current_element(_el_it)->accept(visitor);
}
visitor->leave(this);
}
bool AST_CompositionElement_::hasEquations()
{
if (_eqs_algs == nullptr) {
return false;
}
return _eqs_algs->hasEquations();
}
bool AST_CompositionElement_::hasStatements()
{
if (_eqs_algs == nullptr) {
return false;
}
return _eqs_algs->hasStatements();
}
bool AST_CompositionElement_::hasElements()
{
if (_el == nullptr) {
return false;
}
return _el->size() > 0;
}
/* Composition Equations and Algorithm class */
AST_CompositionEqsAlgs_::AST_CompositionEqsAlgs_(AST_EquationList eq) : _initial(false), _eq(eq), _st(newAST_StatementList()) {}
AST_CompositionEqsAlgs_::AST_CompositionEqsAlgs_(AST_EquationList eq, bool i) : _initial(i), _eq(eq), _st(newAST_StatementList()) {}
AST_CompositionEqsAlgs_::AST_CompositionEqsAlgs_(AST_StatementList st, bool i) : _initial(i), _eq(newAST_EquationList()), _st(st) {}
AST_CompositionEqsAlgs_::AST_CompositionEqsAlgs_(AST_StatementList st) : _initial(false), _eq(newAST_EquationList()), _st(st) {}
AST_EquationList AST_CompositionEqsAlgs_::getEquations() { return _eq; }
AST_StatementList AST_CompositionEqsAlgs_::getAlgorithms() { return _st; }
bool AST_CompositionEqsAlgs_::isInitial() { return _initial; }
void AST_CompositionEqsAlgs_::accept(AST_Visitor *visitor)
{
visitor->visit(this);
AST_EquationListIterator _eq_it;
foreach (_eq_it, _eq) {
current_element(_eq_it)->accept(visitor);
}
AST_StatementListIterator _st_it;
foreach (_st_it, _st) {
current_element(_st_it)->accept(visitor);
}
visitor->leave(this);
}
bool AST_CompositionEqsAlgs_::hasEquations()
{
if (_eq == nullptr) {
return false;
}
return _eq->size() > 0;
}
bool AST_CompositionEqsAlgs_::hasStatements()
{
if (_st == nullptr) {
return false;
}
return _st->size() > 0;
}
/* External function call class */
AST_String AST_External_Function_Call_::language() { return _lang; }
string AST_External_Function_Call_::languageString() { return *_lang; }
AST_ArgumentList AST_External_Function_Call_::annotation() { return _annot; }
AST_External_Function_Call_::AST_External_Function_Call_(AST_String lang, AST_Expression_ComponentReference cr, AST_Expression args,
AST_ArgumentList annot)
: _lang(lang), _annot(annot), _exp(args), _cr(cr)
{
_call = args->getAsCall();
}
AST_ExpressionList AST_External_Function_Call_::args() { return _call->arguments(); }
string AST_External_Function_Call_::name() { return *_call->name(); }
AST_Expression_ComponentReference AST_External_Function_Call_::componentReference() { return _cr; }
bool AST_External_Function_Call_::hasComponentReference() { return _cr != nullptr; }
void AST_External_Function_Call_::accept(AST_Visitor *visitor)
{
visitor->visit(this);
AST_ArgumentListIterator _annot_it;
foreach (_annot_it, _annot) {
current_element(_annot_it)->accept(visitor);
}
}
|
gpl-3.0
|
OpportunityLiu/ExViewer
|
ExClient/Launch/UriHelper.cs
|
1781
|
using System;
using System.Collections.Generic;
using Windows.Foundation;
namespace ExClient.Launch
{
internal static class UriHelper
{
public static bool QueryValueAsBoolean(this string value)
{
return value != "0" && value != "";
}
public static int QueryValueAsInt32(this string value)
{
if (int.TryParse(value, out var r))
{
return r;
}
value = value.Trim();
var i = 0;
for (; i < value.Length; i++)
{
if (value[i] < '0' || value[i] > '9')
{
break;
}
}
if (int.TryParse(value.Substring(0, i), out r))
{
return r;
}
return 0;
}
public static string GetString(this WwwFormUrlDecoder query, string key)
{
try
{
return query.GetFirstValueByName(key);
}
catch (ArgumentException)
{
return null;
}
}
public static int GetInt32(this WwwFormUrlDecoder query, string key)
{
try
{
return query.GetFirstValueByName(key).QueryValueAsInt32();
}
catch (ArgumentException)
{
return 0;
}
}
public static bool GetBoolean(this WwwFormUrlDecoder query, string key)
{
try
{
return query.GetFirstValueByName(key).QueryValueAsBoolean();
}
catch (ArgumentException)
{
return false;
}
}
}
}
|
gpl-3.0
|
AsteroidOS/asteroid-timer
|
i18n/asteroid-timer.fa.ts
|
339
|
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="fa">
<context>
<name></name>
<message id="id-app-launcher-name">
<location filename="asteroid-timer.desktop.h" line="6"/>
<source>Timer</source>
<translation>شمارش معکوس</translation>
</message>
</context>
</TS>
|
gpl-3.0
|
sunshineheader/Games
|
CrazyFram/proj.android/gen/org/cocos2dx/CrazyFram/BuildConfig.java
|
165
|
/** Automatically generated file. DO NOT MODIFY */
package org.cocos2dx.CrazyFram;
public final class BuildConfig {
public final static boolean DEBUG = false;
}
|
gpl-3.0
|
zeatul/poc
|
e-commerce/e-commerce-ecom-pay-service/src/main/java/com/alipay/api/domain/KbadvertVoucherManual.java
|
846
|
package com.alipay.api.domain;
import java.util.List;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
/**
* 口碑客券的使用说明
*
* @author auto create
* @since 1.0, 2017-02-20 21:18:14
*/
public class KbadvertVoucherManual extends AlipayObject {
private static final long serialVersionUID = 2367961246355161615L;
/**
* 说明
*/
@ApiListField("details")
@ApiField("string")
private List<String> details;
/**
* 标题
*/
@ApiField("title")
private String title;
public List<String> getDetails() {
return this.details;
}
public void setDetails(List<String> details) {
this.details = details;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
}
|
gpl-3.0
|
enigma1/i-metrics-cms
|
admin/multi_sites.php
|
22352
|
<?php
$copyright_string='
/*
//----------------------------------------------------------------------------
// Copyright (c) 2006-2011 Asymmetric Software - Innovation & Excellence
// Author: Mark Samios
// http://www.asymmetrics.com
// Admin: MultiSite Configuration script for Web-Front
//----------------------------------------------------------------------------
// I-Metrics CMS
//----------------------------------------------------------------------------
// Script is intended to be used with:
// osCommerce, Open Source E-Commerce Solutions
// http://www.oscommerce.com
// Copyright (c) 2003 osCommerce
//----------------------------------------------------------------------------
// Released under the GNU General Public License
//----------------------------------------------------------------------------
*/
';
require('includes/application_top.php');
$multi_filter = "/[^0-9a-z\-_]+/i";
$multi_prefix = 'multi_';
if (isset($_POST['delete_multi_x']) || isset($_POST['delete_multi_y'])) $action='delete_multi';
switch ($action) {
case 'restart':
case 'restart_confirm':
$site = (isset($_GET['site']) ? strtolower(tep_create_safe_string($_GET['site'],'_', $multi_filter)) : '');
$filename = DIR_FS_MODULES . $multi_prefix . $site . '.php';
if( empty($site) || !is_file($filename) ) {
$messageStack->add_session(ERROR_SITE_CONFIG_INVALID);
tep_redirect(tep_href_link($g_script));
}
if( $action == 'restart' ) break;
require($filename);
$contents =
'<?php' . $copyright_string . "\n" .
' define(\'HTTP_CATALOG_SERVER\', \'' . $http_server . '\');' . "\n" .
' define(\'HTTPS_CATALOG_SERVER\', \'' . $https_server . '\');' . "\n" .
' define(\'ENABLE_SSL_CATALOG\', \'' . $site_ssl . '\');' . "\n" .
' define(\'DIR_WS_CATALOG\', \'' . $ws_path . '\');' . "\n" .
' define(\'DIR_FS_CATALOG\', \'' . $fs_path . '\');' . "\n\n" .
' define(\'DIR_WS_CATALOG_INCLUDES\', DIR_WS_CATALOG . \'includes/\');' . "\n" .
' define(\'DIR_WS_CATALOG_IMAGES\', DIR_WS_CATALOG . \'images/\');' . "\n" .
' define(\'DIR_WS_CATALOG_ICONS\', DIR_WS_CATALOG_IMAGES . \'icons/\');' . "\n" .
' define(\'DIR_WS_CATALOG_STRINGS\', DIR_WS_CATALOG_INCLUDES . \'strings/\');' . "\n" .
' define(\'DIR_WS_CATALOG_MODULES\', DIR_WS_CATALOG_INCLUDES . \'modules/\');' . "\n" .
' define(\'DIR_WS_CATALOG_PLUGINS\', DIR_WS_CATALOG_INCLUDES . \'plugins/\');' . "\n" .
' define(\'DIR_WS_CATALOG_TEMPLATE\', DIR_WS_CATALOG_INCLUDES . \'template/\');' . "\n\n" .
' define(\'DB_SERVER\', \'' . $db_server . '\');' . "\n" .
' define(\'DB_SERVER_USERNAME\', \'' . $db_username . '\');' . "\n" .
' define(\'DB_SERVER_PASSWORD\', \'' . $db_password . '\');' . "\n" .
' define(\'DB_DATABASE\', \'' . $db_database . '\');' . "\n" .
' define(\'USE_PCONNECT\', \'false\');' . "\n" .
'?>' . "\n";
$site_file = DIR_FS_INCLUDES . 'configure_site.php';
if( !tep_write_contents(DIR_FS_INCLUDES . 'configure_site.php', $contents) ) {
$messageStack->add_session (sprintf(ERROR_SITE_CONFIG_WRITE, DIR_FS_ADMIN . $site_file) );
tep_redirect(tep_href_link($g_script));
}
$g_session->destroy();
header("HTTP/1.1 301");
header('P3P: CP="NOI ADM DEV PSAi COM NAV STP IND"');
header('Location: ' . $g_relpath);
exit();
break;
case 'add':
$config_name = (isset($_POST['config_name']) ? strtolower(tep_create_safe_string($_POST['config_name'], '_', $multi_filter)) : '');
$http_server = (isset($_POST['http_server']) ? $g_db->prepare_input($_POST['http_server']) : '');
$https_server = (isset($_POST['https_server']) ? $g_db->prepare_input($_POST['https_server']) : '');
$site_ssl = (isset($_POST['site_ssl']) ? 'true':'false');
$ws_path = (isset($_POST['ws_path']) ? $g_db->prepare_input($_POST['ws_path']) : '');
$fs_path = (isset($_POST['fs_path']) ? $g_db->prepare_input($_POST['fs_path']) : '');
$db_server = (isset($_POST['db_server']) ? $g_db->prepare_input($_POST['db_server']) : '');
$db_username = (isset($_POST['db_username']) ? $g_db->prepare_input($_POST['db_username']) : '');
$db_password = (isset($_POST['db_password']) ? $g_db->prepare_input($_POST['db_password']) : '');
$db_database = (isset($_POST['db_database']) ? $g_db->prepare_input($_POST['db_database']) : '');
$error = false;
if( empty($config_name) ) {
$messageStack->add_session(ERROR_EMPTY_CONFIG_NAME);
$error = true;
}
if( empty($http_server) ) {
$messageStack->add_session(ERROR_EMPTY_HTTP_SERVER);
$error = true;
}
//if( empty($https_server) ) {
// $messageStack->add_session(ERROR_EMPTY_HTTPS_SERVER);
// $error = true;
//}
if( empty($ws_path) ) {
$messageStack->add_session(ERROR_EMPTY_WS_PATH);
$error = true;
}
if( empty($fs_path) ) {
$messageStack->add_session(ERROR_EMPTY_FS_PATH);
$error = true;
}
if( empty($db_server) ) {
$messageStack->add_session(ERROR_EMPTY_DB_SERVER);
$error = true;
}
if( empty($db_username) ) {
$messageStack->add_session(ERROR_EMPTY_DB_USERNAME);
$error = true;
}
if( empty($db_password) ) {
$messageStack->add_session(ERROR_EMPTY_DB_PASSWORD);
$error = true;
}
if( empty($db_database) ) {
$messageStack->add_session(ERROR_EMPTY_DB_DATABASE);
$error = true;
}
if( $error ) {
tep_redirect(tep_href_link($g_script));
}
$config_name = strtolower($config_name);
$contents =
'<?php' . $copyright_string . "\n" .
' $http_server = \'' . $http_server . '\';' . "\n" .
' $https_server = \'' . $https_server . '\';' . "\n" .
' $site_ssl = \'' . $site_ssl . '\';' . "\n" .
' $ws_path = \'' . $ws_path . '\';' . "\n" .
' $fs_path = \'' . $fs_path . '\';' . "\n" .
' $db_server = \'' . $db_server . '\';' . "\n" .
' $db_username = \'' . $db_username . '\';' . "\n" .
' $db_password = \'' . $db_password . '\';' . "\n" .
' $db_database = \'' . $db_database . '\';' . "\n" .
'?>' . "\n";
$config_name = DIR_FS_MODULES . $multi_prefix . $config_name . '.php';
@unlink($config_name);
if( !tep_write_contents($config_name, $contents) ) {
$messageStack->add_session( sprintf(ERROR_SITE_CONFIG_WRITE, DIR_FS_ADMIN . $config_name) );
tep_redirect(tep_href_link($g_script));
}
$messageStack->add_session(SUCCESS_ENTRY_CREATE, 'success');
tep_redirect(tep_href_link($g_script));
break;
case 'delete':
case 'delete_confirm':
$site = (isset($_GET['site']) ? strtolower(tep_create_safe_string($_GET['site'], '_', $multi_filter)) : '');
$filename = DIR_FS_MODULES . $multi_prefix . $site . '.php';
if( empty($site) || !is_file($filename) ) {
$messageStack->add_session(ERROR_SITE_CONFIG_INVALID);
tep_redirect(tep_href_link($g_script));
}
if( $action == 'delete' ) break;
@unlink($filename);
$messageStack->add_session(WARNING_SITE_CONFIG_DELETED, 'warning');
tep_redirect(tep_href_link($g_script));
break;
case 'delete_multi':
case 'delete_multi_confirm':
if( !isset($_POST['mark']) || !is_array($_POST['mark']) || !count($_POST['mark']) ) {
$messageStack->add_session(WARNING_NOTHING_SELECTED, 'warning');
tep_redirect(tep_href_link($g_script, tep_get_all_get_params('action') ));
}
if( $action == 'delete_multi' ) break;
$result = false;
foreach ($_POST['mark'] as $key => $val) {
$site = strtolower(tep_create_safe_string($key, '_', $multi_filter));
$filename = DIR_FS_MODULES . $multi_prefix . $site . '.php';
if( empty($site) || !is_file($filename) ) {
$messageStack->add_session(sprintf(WARNING_SITE_CONFIG_INVALID, DIR_FS_ADMIN . $config_name) );
continue;
}
$result = true;
@unlink($filename);
}
if( $result ) {
$messageStack->add_session(WARNING_SITE_CONFIG_DELETED, 'warning');
}
tep_redirect(tep_href_link($g_script));
break;
case 'update':
if( !isset($_POST['mark']) || !is_array($_POST['mark']) || !count($_POST['mark']) ) {
$messageStack->add_session(WARNING_NOTHING_SELECTED, 'warning');
tep_redirect(tep_href_link($g_script, tep_get_all_get_params('action') ));
}
$result = false;
foreach ($_POST['mark'] as $key => $val) {
$config_name = (isset($_POST['config_name'][$key]) ? strtolower(tep_create_safe_string($_POST['config_name'][$key], '_', $multi_filter)) : '');
if( empty($config_name) ) {
continue;
}
$http_server = (isset($_POST['http_server'][$key]) ? $g_db->prepare_input($_POST['http_server'][$key]) : '');
$https_server = (isset($_POST['https_server'][$key]) ? $g_db->prepare_input($_POST['https_server'][$key]) : '');
$site_ssl = (isset($_POST['site_ssl'][$key]) ? 'true':'false');
$ws_path = (isset($_POST['ws_path'][$key]) ? $g_db->prepare_input($_POST['ws_path'][$key]) : '');
$fs_path = (isset($_POST['fs_path'][$key]) ? $g_db->prepare_input($_POST['fs_path'][$key]) : '');
$db_server = (isset($_POST['db_server'][$key]) ? $g_db->prepare_input($_POST['db_server'][$key]) : '');
$db_username = (isset($_POST['db_username'][$key]) ? $g_db->prepare_input($_POST['db_username'][$key]) : '');
$db_password = (isset($_POST['db_password'][$key]) ? $g_db->prepare_input($_POST['db_password'][$key]) : '');
$db_database = (isset($_POST['db_database'][$key]) ? $g_db->prepare_input($_POST['db_database'][$key]) : '');
$contents =
'<?php' . $copyright_string . "\n" .
' $http_server = \'' . $http_server . '\';' . "\n" .
' $https_server = \'' . $https_server . '\';' . "\n" .
' $site_ssl = \'' . $site_ssl . '\';' . "\n" .
' $ws_path = \'' . $ws_path . '\';' . "\n" .
' $fs_path = \'' . $fs_path . '\';' . "\n" .
' $db_server = \'' . $db_server . '\';' . "\n" .
' $db_username = \'' . $db_username . '\';' . "\n" .
' $db_password = \'' . $db_password . '\';' . "\n" .
' $db_database = \'' . $db_database . '\';' . "\n" .
'?>' . "\n";
$config_name = DIR_FS_MODULES . $multi_prefix . $config_name . '.php';
if( !tep_write_contents($config_name, $contents) ) {
$messageStack->add_session( sprintf(ERROR_SITE_CONFIG_WRITE, DIR_FS_ADMIN . $config_name) );
continue;
}
$result = true;
}
if( $result ) {
$messageStack->add_session(SUCCESS_ENTRY_UPDATED, 'success');
}
tep_redirect(tep_href_link($g_script));
break;
default:
$config_name = strtolower(tep_create_safe_string(STORE_NAME, '_', $multi_filter));
$http_server = HTTP_CATALOG_SERVER;
$https_server = HTTPS_CATALOG_SERVER;
$site_ssl = ENABLE_SSL_CATALOG;
$ws_path = DIR_WS_CATALOG;
$fs_path = DIR_FS_CATALOG;
$db_server = DB_SERVER;
$db_username = DB_SERVER_USERNAME;
$db_password = DB_SERVER_PASSWORD;
$db_database = DB_DATABASE;
break;
}
?>
<?php require(DIR_FS_OBJECTS . 'html_start_sub1.php'); ?>
<?php require(DIR_FS_OBJECTS . 'html_start_sub2.php'); ?>
<?php
if( $action == 'restart' ) {
?>
<div class="maincell wider">
<div class="comboHeadingTop">
<div><h1><?php echo HEADING_RESTART; ?></h1></div>
</div>
<div class="textInfo"><?php echo TEXT_INFO_RESTART; ?></div>
<?php
$site = strtolower(tep_create_safe_string($_GET['site'], '_', $multi_filter));
$filename = DIR_FS_MODULES . $multi_prefix . $site . '.php';
?>
<div class="formArea">
<div class="textInfo"><?php echo '<b style="color: #FF0000">' . $filename . '</b>'; ?></div>
</div>
<div class="formButtons">
<?php
echo '<a href="' . tep_href_link($g_script) . '">' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '</a>';
echo '<a href="' . tep_href_link($g_script, 'action=restart_confirm&site=' . $site) . '">' . tep_image_button('button_confirm.gif', IMAGE_CONFIRM) . '</a>';
?>
</div>
</div>
<?php
} elseif( $action == 'delete' ) {
?>
<div class="maincell wider">
<div class="comboHeadingTop">
<div><h1><?php echo HEADING_DELETE; ?></h1></div>
</div>
<div class="textInfo"><?php echo TEXT_INFO_DELETE; ?></div>
<?php
$site = strtolower(tep_create_safe_string($_GET['site'], '_', $multi_filter));
$filename = DIR_FS_MODULES . $multi_prefix . $site . '.php';
?>
<div class="formArea">
<div class="textInfo"><?php echo '<b style="color: #FF0000">' . $filename . '</b>'; ?></div>
</div>
<div class="formButtons">
<?php
echo '<a href="' . tep_href_link($g_script) . '">' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '</a>';
echo '<a href="' . tep_href_link($g_script, 'action=delete_confirm&site=' . $site) . '">' . tep_image_button('button_delete.gif', IMAGE_DELETE) . '</a>';
?>
</div>
</div>
<?php
} elseif( $action =='delete_multi' ) {
?>
<div class="maincell wider">
<div class="comboHeadingTop">
<div><h1><?php echo HEADING_MULTI_DELETE; ?></h1></div>
</div>
<div class="textInfo"><?php echo TEXT_INFO_MULTI_DELETE; ?></div>
<div><?php echo tep_draw_form('multi_delete', $g_script, 'action=delete_multi_confirm', 'post'); ?>
<?php
foreach( $_POST['mark'] as $key => $val) {
$site = strtolower(tep_create_safe_string($key, '_', $multi_filter));
$filename = DIR_FS_MODULES . $multi_prefix . $site . '.php';
if( !empty($site) && file_exists($filename) ) {
echo '<div class="textInfo"><b style="color: #FF0000">' . $filename . '</b>' . tep_draw_hidden_field('mark[' . $site . ']', $site) . '</div>' . "\n";
}
}
?>
<div class="formButtons">
<?php
echo '<a href="' . tep_href_link($g_script) . '">' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '</a>';
echo tep_image_submit('button_confirm.gif', IMAGE_CONFIRM);
?>
</div>
</form></div>
</div>
<?php
} else {
$buttons = array(
tep_image_submit('button_insert.gif', IMAGE_INSERT)
);
?>
<div class="maincell wider">
<div class="comboHeadingTop">
<div class="rspacer floater help_page"><?php echo '<a href="' . tep_href_link($g_script, 'action=help&ajax=list') . '" class="heading_help" title="' . HEADING_MULTI_SITES_ADD . '" target="_blank">' . tep_image(DIR_WS_ICONS . 'icon_help_32.png', HEADING_MULTI_SITES_ADD) . '</a>'; ?></div>
<div><h1><?php echo HEADING_MULTI_SITES_ADD; ?></h1></div>
</div>
<div class="comboHeading">
<div class="smallText"><?php echo TEXT_INFO_INSERT; ?></div>
</div>
<div class="formArea"><?php echo tep_draw_form("add_field", $g_script, 'action=add', 'post'); ?><fieldset><legend><?php echo TEXT_INFO_ADD_NEW_SITE; ?></legend><table class="tabledata">
<tr class="dataTableHeadingRow">
<th><?php echo TABLE_HEADING_MULTI_NAME; ?></th>
<th><?php echo TABLE_HEADING_MULTI_HTTP_SERVER; ?></th>
<th><?php echo TABLE_HEADING_MULTI_HTTPS_SERVER; ?></th>
<th><?php echo TABLE_HEADING_MULTI_SSL; ?></th>
</tr>
<tr>
<td><div class="rpad"><?php echo tep_draw_input_field('config_name'); ?></div></td>
<td><div class="rpad"><?php echo tep_draw_input_field('http_server'); ?></div></td>
<td><div class="rpad"><?php echo tep_draw_input_field('https_server'); ?></div></td>
<td><?php echo tep_draw_checkbox_field('ssl'); ?></td>
</tr>
<tr class="dataTableHeadingRow">
<th><?php echo TABLE_HEADING_MULTI_WS_PATH; ?></th>
<th><?php echo TABLE_HEADING_MULTI_FS_PATH; ?></th>
<th></th>
<th></th>
</tr>
<tr>
<td><div class="rpad"><?php echo tep_draw_input_field('ws_path'); ?></div></td>
<td><div class="rpad"><?php echo tep_draw_input_field('fs_path'); ?></div></td>
<td></td>
<td></td>
</tr>
<tr class="dataTableHeadingRow">
<th><?php echo TABLE_HEADING_MULTI_DB_SERVER; ?></th>
<th><?php echo TABLE_HEADING_MULTI_DB_USERNAME; ?></th>
<th><?php echo TABLE_HEADING_MULTI_DB_PASSWORD; ?></th>
<th><?php echo TABLE_HEADING_MULTI_DB_DATABASE; ?></th>
</tr>
<tr>
<td><div class="rpad"><?php echo tep_draw_input_field('db_server'); ?></div></td>
<td><div class="rpad"><?php echo tep_draw_input_field('db_username'); ?></div></td>
<td><div class="rpad"><?php echo tep_draw_input_field('db_password'); ?></div></td>
<td><div class="rpad"><?php echo tep_draw_input_field('db_database'); ?></div></td>
</tr>
</table></fieldset><div class="formButtons"><?php echo implode('', $buttons); ?></div></form></div>
<?php
$sites_array = glob(DIR_FS_MODULES . $multi_prefix . '*.php');
if( count($sites_array) ) {
?>
<div class="comboHeadingTop">
<div><h1><?php echo HEADING_MULTI_SITES_UPDATE; ?></h1></div>
</div>
<div class="comboHeading">
<div><?php echo TEXT_INFO_UPDATE; ?></div>
</div>
<div class="formArea"><?php echo tep_draw_form('seo_types', $g_script, 'action=update', 'post'); ?><table width="100%" cellspacing="0" cellpadding="0">
<?php
$count = 0;
foreach($sites_array as $filename) {
$name = substr(basename($filename), strlen($multi_prefix), -4);
$name = strtolower(tep_create_safe_string($name, '_', $multi_filter));
require($filename);
$count++;
$site_string = tep_draw_checkbox_field('mark['.$name.']', 1, false, 'id="label_site_' . $count . '" title="' . sprintf(TEXT_INFO_MARK, $name) . '"');
$site_string .= '<label style="font-size: 14px;" class="lpad" for="label_site_' . $count . '">' . $count . '. ' . TEXT_SITE . ' ' . $name . '</label>';
$buttons = array(
'<a href="' . tep_href_link($g_script, 'site=' . $name . '&action=restart') . '">' . tep_image(DIR_WS_ICONS . 'icon_restart.png', TEXT_RESTART_USING . ' ' . basename($filename)) . '</a>',
'<a href="' . tep_href_link($g_script, 'site=' . $name . '&action=delete') . '">' . tep_image(DIR_WS_ICONS . 'icon_delete.png', TEXT_DELETE_CONFIG . ' ' . basename($filename)) . '</a>'
);
?>
<tr class="dataTableRow">
<td><fieldset><legend><?php echo $site_string; ?></legend><table class="tabledata">
<tr class="dataTableHeadingRow">
<th><?php echo TABLE_HEADING_MULTI_NAME; ?></th>
<th><?php echo TABLE_HEADING_MULTI_HTTP_SERVER; ?></th>
<th><?php echo TABLE_HEADING_MULTI_HTTPS_SERVER; ?></th>
<th><?php echo TABLE_HEADING_MULTI_SSL; ?></th>
</tr>
<tr>
<td><div class="rpad"><?php echo tep_draw_input_field('config_name[' . $name . ']', $name); ?></div></td>
<td><div class="rpad"><?php echo tep_draw_input_field('http_server[' . $name . ']', $http_server); ?></div></td>
<td><div class="rpad"><?php echo tep_draw_input_field('https_server[' . $name . ']', $https_server); ?></div></td>
<td><?php echo tep_draw_checkbox_field('site_ssl[' . $name . ']', 'on', ($site_ssl=='true')); ?></td>
</tr>
<tr class="dataTableHeadingRow">
<th><?php echo TABLE_HEADING_MULTI_WS_PATH; ?></th>
<th><?php echo TABLE_HEADING_MULTI_FS_PATH; ?></th>
<th></th>
<th></th>
</tr>
<tr>
<td><div class="rpad"><?php echo tep_draw_input_field('ws_path[' . $name . ']', $ws_path); ?></div></td>
<td><div class="rpad"><?php echo tep_draw_input_field('fs_path[' . $name . ']', $fs_path); ?></div></td>
<td></td>
<td></td>
</tr>
<tr class="dataTableHeadingRow">
<th><?php echo TABLE_HEADING_MULTI_DB_SERVER; ?></th>
<th><?php echo TABLE_HEADING_MULTI_DB_USERNAME; ?></th>
<th><?php echo TABLE_HEADING_MULTI_DB_PASSWORD; ?></th>
<th><?php echo TABLE_HEADING_MULTI_DB_DATABASE; ?></th>
</tr>
<tr>
<td><div class="rpad"><?php echo tep_draw_input_field('db_server[' . $name . ']', $db_server); ?></div></td>
<td><div class="rpad"><?php echo tep_draw_input_field('db_username[' . $name . ']', $db_username); ?></div></td>
<td><div class="rpad"><?php echo tep_draw_input_field('db_password[' . $name . ']', $db_password); ?></div></td>
<td><div class="rpad"><?php echo tep_draw_input_field('db_database[' . $name . ']', $db_database); ?></div></td>
</tr>
</table><div class="formButtons tinysep"><?php echo implode('', $buttons); ?></div></fieldset></td>
</tr>
<?php
}
$buttons = array(
tep_image_submit('button_update.gif', IMAGE_UPDATE, 'name="update"'),
tep_image_submit('button_delete.gif', IMAGE_DELETE, 'name="delete_multi"')
);
?>
</table><div class="formButtons"><?php echo implode('', $buttons); ?></div></form></div>
<?php
}
?>
</div>
<?php
}
?>
<?php require(DIR_FS_OBJECTS . 'html_end.php'); ?>
|
gpl-3.0
|
koffeinfrei/fantassh
|
lib/fantassh/application.rb
|
1919
|
require 'slop'
require_relative 'bash_history'
require_relative 'entries'
require_relative 'history'
module Fantassh
class Application
class << self
def run(argv = ARGV)
Slop.parse(argv, help: true) do
on '-v', '--version', 'Print the program version.' do
puts "#{File.basename($0)} v#{Fantassh::VERSION}"
exit
end
# default, runs when called without arguments
run do
Fantassh::Application.list
end
command :last do
banner "Usage: #{File.basename($0)} last"
run do
Fantassh::Application.last
end
end
command :exclude do
banner "Usage: #{File.basename($0)} exclude <ssh command>"
run do |opts, args|
if args.empty?
puts help
exit
end
Fantassh::Application.exclude(args.join(' '))
end
end
end
end
def list
entries.add(bash_history.entries)
selected_entry = `echo '#{entries.all.join("\n")}' | selecta`
# in case selecta receives ctrl+c we don't proceed
unless selected_entry.empty?
history.add(selected_entry)
run_ssh_command(selected_entry)
end
end
def last
last = history.last
if last
run_ssh_command(last)
else
puts "There is no history entry just yet!"
end
end
def exclude(entry)
entries.exclude([entry])
end
def entries
Entries.new
end
def bash_history
BashHistory.new
end
def history
History.new
end
def run_ssh_command(argument)
# indent by whitespace so it doesn't show up in the history
exec " ssh #{argument}"
end
end
end
end
|
gpl-3.0
|
moderntribe/product-taskmaster
|
webpack/module/rules/javascript.js
|
86
|
module.exports = {
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader',
};
|
gpl-3.0
|
ernestbuffington/PHP-Nuke-Titanium
|
includes/blocks/discord/language/lang-english.php
|
1276
|
<?php
/************************************************************************/
/* Discord Block */
/* ============================== */
/* */
/* Copyright (c) 2003 - 2018 coRpSE */
/* http://www.headshotdomain.net */
/* */
/* This program is free software. You can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 2 of the License. */
/************************************************************************/
define('_DISCORD_VOICE','Discord Voice Channels');
define('_DISCORD_JOIN','Join Server');
define('_DISCORD_ADM','ADM');
define('_DISCORD_BOT','BOT');
define('_DISCORD_ONLINE', 'Online:');
define('_DISCORD_INVOICE', 'In Voice:');
define('_DISCORD_INGAME', 'In-Game:');
define('_DISCORD_INGAME','In-Game');
define('_DISCORD_GAME','Game:');
define('_DISCORD_NOBODY', 'There\'s nobody');
define('_DISCORD_ON_SERVER', 'on our server.');
?>
|
gpl-3.0
|
smart-facility/petajakarta-web
|
banjir/vendor/js/Chart.js
|
312401
|
/*!
* Chart.js
* http://chartjs.org/
* Version: 2.1.6
*
* Copyright 2016 Nick Downie
* Released under the MIT license
* https://github.com/chartjs/Chart.js/blob/master/LICENSE.md
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Chart = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
},{}],2:[function(require,module,exports){
/* MIT license */
var colorNames = require(6);
module.exports = {
getRgba: getRgba,
getHsla: getHsla,
getRgb: getRgb,
getHsl: getHsl,
getHwb: getHwb,
getAlpha: getAlpha,
hexString: hexString,
rgbString: rgbString,
rgbaString: rgbaString,
percentString: percentString,
percentaString: percentaString,
hslString: hslString,
hslaString: hslaString,
hwbString: hwbString,
keyword: keyword
}
function getRgba(string) {
if (!string) {
return;
}
var abbr = /^#([a-fA-F0-9]{3})$/,
hex = /^#([a-fA-F0-9]{6})$/,
rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/,
per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/,
keyword = /(\w+)/;
var rgb = [0, 0, 0],
a = 1,
match = string.match(abbr);
if (match) {
match = match[1];
for (var i = 0; i < rgb.length; i++) {
rgb[i] = parseInt(match[i] + match[i], 16);
}
}
else if (match = string.match(hex)) {
match = match[1];
for (var i = 0; i < rgb.length; i++) {
rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
}
}
else if (match = string.match(rgba)) {
for (var i = 0; i < rgb.length; i++) {
rgb[i] = parseInt(match[i + 1]);
}
a = parseFloat(match[4]);
}
else if (match = string.match(per)) {
for (var i = 0; i < rgb.length; i++) {
rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
}
a = parseFloat(match[4]);
}
else if (match = string.match(keyword)) {
if (match[1] == "transparent") {
return [0, 0, 0, 0];
}
rgb = colorNames[match[1]];
if (!rgb) {
return;
}
}
for (var i = 0; i < rgb.length; i++) {
rgb[i] = scale(rgb[i], 0, 255);
}
if (!a && a != 0) {
a = 1;
}
else {
a = scale(a, 0, 1);
}
rgb[3] = a;
return rgb;
}
function getHsla(string) {
if (!string) {
return;
}
var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
var match = string.match(hsl);
if (match) {
var alpha = parseFloat(match[4]);
var h = scale(parseInt(match[1]), 0, 360),
s = scale(parseFloat(match[2]), 0, 100),
l = scale(parseFloat(match[3]), 0, 100),
a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
return [h, s, l, a];
}
}
function getHwb(string) {
if (!string) {
return;
}
var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
var match = string.match(hwb);
if (match) {
var alpha = parseFloat(match[4]);
var h = scale(parseInt(match[1]), 0, 360),
w = scale(parseFloat(match[2]), 0, 100),
b = scale(parseFloat(match[3]), 0, 100),
a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
return [h, w, b, a];
}
}
function getRgb(string) {
var rgba = getRgba(string);
return rgba && rgba.slice(0, 3);
}
function getHsl(string) {
var hsla = getHsla(string);
return hsla && hsla.slice(0, 3);
}
function getAlpha(string) {
var vals = getRgba(string);
if (vals) {
return vals[3];
}
else if (vals = getHsla(string)) {
return vals[3];
}
else if (vals = getHwb(string)) {
return vals[3];
}
}
// generators
function hexString(rgb) {
return "#" + hexDouble(rgb[0]) + hexDouble(rgb[1])
+ hexDouble(rgb[2]);
}
function rgbString(rgba, alpha) {
if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
return rgbaString(rgba, alpha);
}
return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
}
function rgbaString(rgba, alpha) {
if (alpha === undefined) {
alpha = (rgba[3] !== undefined ? rgba[3] : 1);
}
return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
+ ", " + alpha + ")";
}
function percentString(rgba, alpha) {
if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
return percentaString(rgba, alpha);
}
var r = Math.round(rgba[0]/255 * 100),
g = Math.round(rgba[1]/255 * 100),
b = Math.round(rgba[2]/255 * 100);
return "rgb(" + r + "%, " + g + "%, " + b + "%)";
}
function percentaString(rgba, alpha) {
var r = Math.round(rgba[0]/255 * 100),
g = Math.round(rgba[1]/255 * 100),
b = Math.round(rgba[2]/255 * 100);
return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
}
function hslString(hsla, alpha) {
if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
return hslaString(hsla, alpha);
}
return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
}
function hslaString(hsla, alpha) {
if (alpha === undefined) {
alpha = (hsla[3] !== undefined ? hsla[3] : 1);
}
return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
+ alpha + ")";
}
// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
// (hwb have alpha optional & 1 is default value)
function hwbString(hwb, alpha) {
if (alpha === undefined) {
alpha = (hwb[3] !== undefined ? hwb[3] : 1);
}
return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
+ (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
}
function keyword(rgb) {
return reverseNames[rgb.slice(0, 3)];
}
// helpers
function scale(num, min, max) {
return Math.min(Math.max(min, num), max);
}
function hexDouble(num) {
var str = num.toString(16).toUpperCase();
return (str.length < 2) ? "0" + str : str;
}
//create a list of reverse color names
var reverseNames = {};
for (var name in colorNames) {
reverseNames[colorNames[name]] = name;
}
},{"6":6}],3:[function(require,module,exports){
/* MIT license */
var convert = require(5);
var string = require(2);
var Color = function (obj) {
if (obj instanceof Color) {
return obj;
}
if (!(this instanceof Color)) {
return new Color(obj);
}
this.values = {
rgb: [0, 0, 0],
hsl: [0, 0, 0],
hsv: [0, 0, 0],
hwb: [0, 0, 0],
cmyk: [0, 0, 0, 0],
alpha: 1
};
// parse Color() argument
var vals;
if (typeof obj === 'string') {
vals = string.getRgba(obj);
if (vals) {
this.setValues('rgb', vals);
} else if (vals = string.getHsla(obj)) {
this.setValues('hsl', vals);
} else if (vals = string.getHwb(obj)) {
this.setValues('hwb', vals);
} else {
throw new Error('Unable to parse color from string "' + obj + '"');
}
} else if (typeof obj === 'object') {
vals = obj;
if (vals.r !== undefined || vals.red !== undefined) {
this.setValues('rgb', vals);
} else if (vals.l !== undefined || vals.lightness !== undefined) {
this.setValues('hsl', vals);
} else if (vals.v !== undefined || vals.value !== undefined) {
this.setValues('hsv', vals);
} else if (vals.w !== undefined || vals.whiteness !== undefined) {
this.setValues('hwb', vals);
} else if (vals.c !== undefined || vals.cyan !== undefined) {
this.setValues('cmyk', vals);
} else {
throw new Error('Unable to parse color from object ' + JSON.stringify(obj));
}
}
};
Color.prototype = {
rgb: function () {
return this.setSpace('rgb', arguments);
},
hsl: function () {
return this.setSpace('hsl', arguments);
},
hsv: function () {
return this.setSpace('hsv', arguments);
},
hwb: function () {
return this.setSpace('hwb', arguments);
},
cmyk: function () {
return this.setSpace('cmyk', arguments);
},
rgbArray: function () {
return this.values.rgb;
},
hslArray: function () {
return this.values.hsl;
},
hsvArray: function () {
return this.values.hsv;
},
hwbArray: function () {
var values = this.values;
if (values.alpha !== 1) {
return values.hwb.concat([values.alpha]);
}
return values.hwb;
},
cmykArray: function () {
return this.values.cmyk;
},
rgbaArray: function () {
var values = this.values;
return values.rgb.concat([values.alpha]);
},
hslaArray: function () {
var values = this.values;
return values.hsl.concat([values.alpha]);
},
alpha: function (val) {
if (val === undefined) {
return this.values.alpha;
}
this.setValues('alpha', val);
return this;
},
red: function (val) {
return this.setChannel('rgb', 0, val);
},
green: function (val) {
return this.setChannel('rgb', 1, val);
},
blue: function (val) {
return this.setChannel('rgb', 2, val);
},
hue: function (val) {
if (val) {
val %= 360;
val = val < 0 ? 360 + val : val;
}
return this.setChannel('hsl', 0, val);
},
saturation: function (val) {
return this.setChannel('hsl', 1, val);
},
lightness: function (val) {
return this.setChannel('hsl', 2, val);
},
saturationv: function (val) {
return this.setChannel('hsv', 1, val);
},
whiteness: function (val) {
return this.setChannel('hwb', 1, val);
},
blackness: function (val) {
return this.setChannel('hwb', 2, val);
},
value: function (val) {
return this.setChannel('hsv', 2, val);
},
cyan: function (val) {
return this.setChannel('cmyk', 0, val);
},
magenta: function (val) {
return this.setChannel('cmyk', 1, val);
},
yellow: function (val) {
return this.setChannel('cmyk', 2, val);
},
black: function (val) {
return this.setChannel('cmyk', 3, val);
},
hexString: function () {
return string.hexString(this.values.rgb);
},
rgbString: function () {
return string.rgbString(this.values.rgb, this.values.alpha);
},
rgbaString: function () {
return string.rgbaString(this.values.rgb, this.values.alpha);
},
percentString: function () {
return string.percentString(this.values.rgb, this.values.alpha);
},
hslString: function () {
return string.hslString(this.values.hsl, this.values.alpha);
},
hslaString: function () {
return string.hslaString(this.values.hsl, this.values.alpha);
},
hwbString: function () {
return string.hwbString(this.values.hwb, this.values.alpha);
},
keyword: function () {
return string.keyword(this.values.rgb, this.values.alpha);
},
rgbNumber: function () {
var rgb = this.values.rgb;
return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
},
luminosity: function () {
// http://www.w3.org/TR/WCAG20/#relativeluminancedef
var rgb = this.values.rgb;
var lum = [];
for (var i = 0; i < rgb.length; i++) {
var chan = rgb[i] / 255;
lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
}
return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
},
contrast: function (color2) {
// http://www.w3.org/TR/WCAG20/#contrast-ratiodef
var lum1 = this.luminosity();
var lum2 = color2.luminosity();
if (lum1 > lum2) {
return (lum1 + 0.05) / (lum2 + 0.05);
}
return (lum2 + 0.05) / (lum1 + 0.05);
},
level: function (color2) {
var contrastRatio = this.contrast(color2);
if (contrastRatio >= 7.1) {
return 'AAA';
}
return (contrastRatio >= 4.5) ? 'AA' : '';
},
dark: function () {
// YIQ equation from http://24ways.org/2010/calculating-color-contrast
var rgb = this.values.rgb;
var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
return yiq < 128;
},
light: function () {
return !this.dark();
},
negate: function () {
var rgb = [];
for (var i = 0; i < 3; i++) {
rgb[i] = 255 - this.values.rgb[i];
}
this.setValues('rgb', rgb);
return this;
},
lighten: function (ratio) {
var hsl = this.values.hsl;
hsl[2] += hsl[2] * ratio;
this.setValues('hsl', hsl);
return this;
},
darken: function (ratio) {
var hsl = this.values.hsl;
hsl[2] -= hsl[2] * ratio;
this.setValues('hsl', hsl);
return this;
},
saturate: function (ratio) {
var hsl = this.values.hsl;
hsl[1] += hsl[1] * ratio;
this.setValues('hsl', hsl);
return this;
},
desaturate: function (ratio) {
var hsl = this.values.hsl;
hsl[1] -= hsl[1] * ratio;
this.setValues('hsl', hsl);
return this;
},
whiten: function (ratio) {
var hwb = this.values.hwb;
hwb[1] += hwb[1] * ratio;
this.setValues('hwb', hwb);
return this;
},
blacken: function (ratio) {
var hwb = this.values.hwb;
hwb[2] += hwb[2] * ratio;
this.setValues('hwb', hwb);
return this;
},
greyscale: function () {
var rgb = this.values.rgb;
// http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
this.setValues('rgb', [val, val, val]);
return this;
},
clearer: function (ratio) {
var alpha = this.values.alpha;
this.setValues('alpha', alpha - (alpha * ratio));
return this;
},
opaquer: function (ratio) {
var alpha = this.values.alpha;
this.setValues('alpha', alpha + (alpha * ratio));
return this;
},
rotate: function (degrees) {
var hsl = this.values.hsl;
var hue = (hsl[0] + degrees) % 360;
hsl[0] = hue < 0 ? 360 + hue : hue;
this.setValues('hsl', hsl);
return this;
},
/**
* Ported from sass implementation in C
* https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
*/
mix: function (mixinColor, weight) {
var color1 = this;
var color2 = mixinColor;
var p = weight === undefined ? 0.5 : weight;
var w = 2 * p - 1;
var a = color1.alpha() - color2.alpha();
var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
var w2 = 1 - w1;
return this
.rgb(
w1 * color1.red() + w2 * color2.red(),
w1 * color1.green() + w2 * color2.green(),
w1 * color1.blue() + w2 * color2.blue()
)
.alpha(color1.alpha() * p + color2.alpha() * (1 - p));
},
toJSON: function () {
return this.rgb();
},
clone: function () {
// NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
// making the final build way to big to embed in Chart.js. So let's do it manually,
// assuming that values to clone are 1 dimension arrays containing only numbers,
// except 'alpha' which is a number.
var result = new Color();
var source = this.values;
var target = result.values;
var value, type;
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
value = source[prop];
type = ({}).toString.call(value);
if (type === '[object Array]') {
target[prop] = value.slice(0);
} else if (type === '[object Number]') {
target[prop] = value;
} else {
console.error('unexpected color value:', value);
}
}
}
return result;
}
};
Color.prototype.spaces = {
rgb: ['red', 'green', 'blue'],
hsl: ['hue', 'saturation', 'lightness'],
hsv: ['hue', 'saturation', 'value'],
hwb: ['hue', 'whiteness', 'blackness'],
cmyk: ['cyan', 'magenta', 'yellow', 'black']
};
Color.prototype.maxes = {
rgb: [255, 255, 255],
hsl: [360, 100, 100],
hsv: [360, 100, 100],
hwb: [360, 100, 100],
cmyk: [100, 100, 100, 100]
};
Color.prototype.getValues = function (space) {
var values = this.values;
var vals = {};
for (var i = 0; i < space.length; i++) {
vals[space.charAt(i)] = values[space][i];
}
if (values.alpha !== 1) {
vals.a = values.alpha;
}
// {r: 255, g: 255, b: 255, a: 0.4}
return vals;
};
Color.prototype.setValues = function (space, vals) {
var values = this.values;
var spaces = this.spaces;
var maxes = this.maxes;
var alpha = 1;
var i;
if (space === 'alpha') {
alpha = vals;
} else if (vals.length) {
// [10, 10, 10]
values[space] = vals.slice(0, space.length);
alpha = vals[space.length];
} else if (vals[space.charAt(0)] !== undefined) {
// {r: 10, g: 10, b: 10}
for (i = 0; i < space.length; i++) {
values[space][i] = vals[space.charAt(i)];
}
alpha = vals.a;
} else if (vals[spaces[space][0]] !== undefined) {
// {red: 10, green: 10, blue: 10}
var chans = spaces[space];
for (i = 0; i < space.length; i++) {
values[space][i] = vals[chans[i]];
}
alpha = vals.alpha;
}
values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
if (space === 'alpha') {
return false;
}
var capped;
// cap values of the space prior converting all values
for (i = 0; i < space.length; i++) {
capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
values[space][i] = Math.round(capped);
}
// convert to all the other color spaces
for (var sname in spaces) {
if (sname !== space) {
values[sname] = convert[space][sname](values[space]);
}
}
return true;
};
Color.prototype.setSpace = function (space, args) {
var vals = args[0];
if (vals === undefined) {
// color.rgb()
return this.getValues(space);
}
// color.rgb(10, 10, 10)
if (typeof vals === 'number') {
vals = Array.prototype.slice.call(args);
}
this.setValues(space, vals);
return this;
};
Color.prototype.setChannel = function (space, index, val) {
var svalues = this.values[space];
if (val === undefined) {
// color.red()
return svalues[index];
} else if (val === svalues[index]) {
// color.red(color.red())
return this;
}
// color.red(100)
svalues[index] = val;
this.setValues(space, svalues);
return this;
};
if (typeof window !== 'undefined') {
window.Color = Color;
}
module.exports = Color;
},{"2":2,"5":5}],4:[function(require,module,exports){
/* MIT license */
module.exports = {
rgb2hsl: rgb2hsl,
rgb2hsv: rgb2hsv,
rgb2hwb: rgb2hwb,
rgb2cmyk: rgb2cmyk,
rgb2keyword: rgb2keyword,
rgb2xyz: rgb2xyz,
rgb2lab: rgb2lab,
rgb2lch: rgb2lch,
hsl2rgb: hsl2rgb,
hsl2hsv: hsl2hsv,
hsl2hwb: hsl2hwb,
hsl2cmyk: hsl2cmyk,
hsl2keyword: hsl2keyword,
hsv2rgb: hsv2rgb,
hsv2hsl: hsv2hsl,
hsv2hwb: hsv2hwb,
hsv2cmyk: hsv2cmyk,
hsv2keyword: hsv2keyword,
hwb2rgb: hwb2rgb,
hwb2hsl: hwb2hsl,
hwb2hsv: hwb2hsv,
hwb2cmyk: hwb2cmyk,
hwb2keyword: hwb2keyword,
cmyk2rgb: cmyk2rgb,
cmyk2hsl: cmyk2hsl,
cmyk2hsv: cmyk2hsv,
cmyk2hwb: cmyk2hwb,
cmyk2keyword: cmyk2keyword,
keyword2rgb: keyword2rgb,
keyword2hsl: keyword2hsl,
keyword2hsv: keyword2hsv,
keyword2hwb: keyword2hwb,
keyword2cmyk: keyword2cmyk,
keyword2lab: keyword2lab,
keyword2xyz: keyword2xyz,
xyz2rgb: xyz2rgb,
xyz2lab: xyz2lab,
xyz2lch: xyz2lch,
lab2xyz: lab2xyz,
lab2rgb: lab2rgb,
lab2lch: lab2lch,
lch2lab: lch2lab,
lch2xyz: lch2xyz,
lch2rgb: lch2rgb
}
function rgb2hsl(rgb) {
var r = rgb[0]/255,
g = rgb[1]/255,
b = rgb[2]/255,
min = Math.min(r, g, b),
max = Math.max(r, g, b),
delta = max - min,
h, s, l;
if (max == min)
h = 0;
else if (r == max)
h = (g - b) / delta;
else if (g == max)
h = 2 + (b - r) / delta;
else if (b == max)
h = 4 + (r - g)/ delta;
h = Math.min(h * 60, 360);
if (h < 0)
h += 360;
l = (min + max) / 2;
if (max == min)
s = 0;
else if (l <= 0.5)
s = delta / (max + min);
else
s = delta / (2 - max - min);
return [h, s * 100, l * 100];
}
function rgb2hsv(rgb) {
var r = rgb[0],
g = rgb[1],
b = rgb[2],
min = Math.min(r, g, b),
max = Math.max(r, g, b),
delta = max - min,
h, s, v;
if (max == 0)
s = 0;
else
s = (delta/max * 1000)/10;
if (max == min)
h = 0;
else if (r == max)
h = (g - b) / delta;
else if (g == max)
h = 2 + (b - r) / delta;
else if (b == max)
h = 4 + (r - g) / delta;
h = Math.min(h * 60, 360);
if (h < 0)
h += 360;
v = ((max / 255) * 1000) / 10;
return [h, s, v];
}
function rgb2hwb(rgb) {
var r = rgb[0],
g = rgb[1],
b = rgb[2],
h = rgb2hsl(rgb)[0],
w = 1/255 * Math.min(r, Math.min(g, b)),
b = 1 - 1/255 * Math.max(r, Math.max(g, b));
return [h, w * 100, b * 100];
}
function rgb2cmyk(rgb) {
var r = rgb[0] / 255,
g = rgb[1] / 255,
b = rgb[2] / 255,
c, m, y, k;
k = Math.min(1 - r, 1 - g, 1 - b);
c = (1 - r - k) / (1 - k) || 0;
m = (1 - g - k) / (1 - k) || 0;
y = (1 - b - k) / (1 - k) || 0;
return [c * 100, m * 100, y * 100, k * 100];
}
function rgb2keyword(rgb) {
return reverseKeywords[JSON.stringify(rgb)];
}
function rgb2xyz(rgb) {
var r = rgb[0] / 255,
g = rgb[1] / 255,
b = rgb[2] / 255;
// assume sRGB
r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
return [x * 100, y *100, z * 100];
}
function rgb2lab(rgb) {
var xyz = rgb2xyz(rgb),
x = xyz[0],
y = xyz[1],
z = xyz[2],
l, a, b;
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
l = (116 * y) - 16;
a = 500 * (x - y);
b = 200 * (y - z);
return [l, a, b];
}
function rgb2lch(args) {
return lab2lch(rgb2lab(args));
}
function hsl2rgb(hsl) {
var h = hsl[0] / 360,
s = hsl[1] / 100,
l = hsl[2] / 100,
t1, t2, t3, rgb, val;
if (s == 0) {
val = l * 255;
return [val, val, val];
}
if (l < 0.5)
t2 = l * (1 + s);
else
t2 = l + s - l * s;
t1 = 2 * l - t2;
rgb = [0, 0, 0];
for (var i = 0; i < 3; i++) {
t3 = h + 1 / 3 * - (i - 1);
t3 < 0 && t3++;
t3 > 1 && t3--;
if (6 * t3 < 1)
val = t1 + (t2 - t1) * 6 * t3;
else if (2 * t3 < 1)
val = t2;
else if (3 * t3 < 2)
val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
else
val = t1;
rgb[i] = val * 255;
}
return rgb;
}
function hsl2hsv(hsl) {
var h = hsl[0],
s = hsl[1] / 100,
l = hsl[2] / 100,
sv, v;
if(l === 0) {
// no need to do calc on black
// also avoids divide by 0 error
return [0, 0, 0];
}
l *= 2;
s *= (l <= 1) ? l : 2 - l;
v = (l + s) / 2;
sv = (2 * s) / (l + s);
return [h, sv * 100, v * 100];
}
function hsl2hwb(args) {
return rgb2hwb(hsl2rgb(args));
}
function hsl2cmyk(args) {
return rgb2cmyk(hsl2rgb(args));
}
function hsl2keyword(args) {
return rgb2keyword(hsl2rgb(args));
}
function hsv2rgb(hsv) {
var h = hsv[0] / 60,
s = hsv[1] / 100,
v = hsv[2] / 100,
hi = Math.floor(h) % 6;
var f = h - Math.floor(h),
p = 255 * v * (1 - s),
q = 255 * v * (1 - (s * f)),
t = 255 * v * (1 - (s * (1 - f))),
v = 255 * v;
switch(hi) {
case 0:
return [v, t, p];
case 1:
return [q, v, p];
case 2:
return [p, v, t];
case 3:
return [p, q, v];
case 4:
return [t, p, v];
case 5:
return [v, p, q];
}
}
function hsv2hsl(hsv) {
var h = hsv[0],
s = hsv[1] / 100,
v = hsv[2] / 100,
sl, l;
l = (2 - s) * v;
sl = s * v;
sl /= (l <= 1) ? l : 2 - l;
sl = sl || 0;
l /= 2;
return [h, sl * 100, l * 100];
}
function hsv2hwb(args) {
return rgb2hwb(hsv2rgb(args))
}
function hsv2cmyk(args) {
return rgb2cmyk(hsv2rgb(args));
}
function hsv2keyword(args) {
return rgb2keyword(hsv2rgb(args));
}
// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
function hwb2rgb(hwb) {
var h = hwb[0] / 360,
wh = hwb[1] / 100,
bl = hwb[2] / 100,
ratio = wh + bl,
i, v, f, n;
// wh + bl cant be > 1
if (ratio > 1) {
wh /= ratio;
bl /= ratio;
}
i = Math.floor(6 * h);
v = 1 - bl;
f = 6 * h - i;
if ((i & 0x01) != 0) {
f = 1 - f;
}
n = wh + f * (v - wh); // linear interpolation
switch (i) {
default:
case 6:
case 0: r = v; g = n; b = wh; break;
case 1: r = n; g = v; b = wh; break;
case 2: r = wh; g = v; b = n; break;
case 3: r = wh; g = n; b = v; break;
case 4: r = n; g = wh; b = v; break;
case 5: r = v; g = wh; b = n; break;
}
return [r * 255, g * 255, b * 255];
}
function hwb2hsl(args) {
return rgb2hsl(hwb2rgb(args));
}
function hwb2hsv(args) {
return rgb2hsv(hwb2rgb(args));
}
function hwb2cmyk(args) {
return rgb2cmyk(hwb2rgb(args));
}
function hwb2keyword(args) {
return rgb2keyword(hwb2rgb(args));
}
function cmyk2rgb(cmyk) {
var c = cmyk[0] / 100,
m = cmyk[1] / 100,
y = cmyk[2] / 100,
k = cmyk[3] / 100,
r, g, b;
r = 1 - Math.min(1, c * (1 - k) + k);
g = 1 - Math.min(1, m * (1 - k) + k);
b = 1 - Math.min(1, y * (1 - k) + k);
return [r * 255, g * 255, b * 255];
}
function cmyk2hsl(args) {
return rgb2hsl(cmyk2rgb(args));
}
function cmyk2hsv(args) {
return rgb2hsv(cmyk2rgb(args));
}
function cmyk2hwb(args) {
return rgb2hwb(cmyk2rgb(args));
}
function cmyk2keyword(args) {
return rgb2keyword(cmyk2rgb(args));
}
function xyz2rgb(xyz) {
var x = xyz[0] / 100,
y = xyz[1] / 100,
z = xyz[2] / 100,
r, g, b;
r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
// assume sRGB
r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
: r = (r * 12.92);
g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
: g = (g * 12.92);
b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
: b = (b * 12.92);
r = Math.min(Math.max(0, r), 1);
g = Math.min(Math.max(0, g), 1);
b = Math.min(Math.max(0, b), 1);
return [r * 255, g * 255, b * 255];
}
function xyz2lab(xyz) {
var x = xyz[0],
y = xyz[1],
z = xyz[2],
l, a, b;
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
l = (116 * y) - 16;
a = 500 * (x - y);
b = 200 * (y - z);
return [l, a, b];
}
function xyz2lch(args) {
return lab2lch(xyz2lab(args));
}
function lab2xyz(lab) {
var l = lab[0],
a = lab[1],
b = lab[2],
x, y, z, y2;
if (l <= 8) {
y = (l * 100) / 903.3;
y2 = (7.787 * (y / 100)) + (16 / 116);
} else {
y = 100 * Math.pow((l + 16) / 116, 3);
y2 = Math.pow(y / 100, 1/3);
}
x = x / 95.047 <= 0.008856 ? x = (95.047 * ((a / 500) + y2 - (16 / 116))) / 7.787 : 95.047 * Math.pow((a / 500) + y2, 3);
z = z / 108.883 <= 0.008859 ? z = (108.883 * (y2 - (b / 200) - (16 / 116))) / 7.787 : 108.883 * Math.pow(y2 - (b / 200), 3);
return [x, y, z];
}
function lab2lch(lab) {
var l = lab[0],
a = lab[1],
b = lab[2],
hr, h, c;
hr = Math.atan2(b, a);
h = hr * 360 / 2 / Math.PI;
if (h < 0) {
h += 360;
}
c = Math.sqrt(a * a + b * b);
return [l, c, h];
}
function lab2rgb(args) {
return xyz2rgb(lab2xyz(args));
}
function lch2lab(lch) {
var l = lch[0],
c = lch[1],
h = lch[2],
a, b, hr;
hr = h / 360 * 2 * Math.PI;
a = c * Math.cos(hr);
b = c * Math.sin(hr);
return [l, a, b];
}
function lch2xyz(args) {
return lab2xyz(lch2lab(args));
}
function lch2rgb(args) {
return lab2rgb(lch2lab(args));
}
function keyword2rgb(keyword) {
return cssKeywords[keyword];
}
function keyword2hsl(args) {
return rgb2hsl(keyword2rgb(args));
}
function keyword2hsv(args) {
return rgb2hsv(keyword2rgb(args));
}
function keyword2hwb(args) {
return rgb2hwb(keyword2rgb(args));
}
function keyword2cmyk(args) {
return rgb2cmyk(keyword2rgb(args));
}
function keyword2lab(args) {
return rgb2lab(keyword2rgb(args));
}
function keyword2xyz(args) {
return rgb2xyz(keyword2rgb(args));
}
var cssKeywords = {
aliceblue: [240,248,255],
antiquewhite: [250,235,215],
aqua: [0,255,255],
aquamarine: [127,255,212],
azure: [240,255,255],
beige: [245,245,220],
bisque: [255,228,196],
black: [0,0,0],
blanchedalmond: [255,235,205],
blue: [0,0,255],
blueviolet: [138,43,226],
brown: [165,42,42],
burlywood: [222,184,135],
cadetblue: [95,158,160],
chartreuse: [127,255,0],
chocolate: [210,105,30],
coral: [255,127,80],
cornflowerblue: [100,149,237],
cornsilk: [255,248,220],
crimson: [220,20,60],
cyan: [0,255,255],
darkblue: [0,0,139],
darkcyan: [0,139,139],
darkgoldenrod: [184,134,11],
darkgray: [169,169,169],
darkgreen: [0,100,0],
darkgrey: [169,169,169],
darkkhaki: [189,183,107],
darkmagenta: [139,0,139],
darkolivegreen: [85,107,47],
darkorange: [255,140,0],
darkorchid: [153,50,204],
darkred: [139,0,0],
darksalmon: [233,150,122],
darkseagreen: [143,188,143],
darkslateblue: [72,61,139],
darkslategray: [47,79,79],
darkslategrey: [47,79,79],
darkturquoise: [0,206,209],
darkviolet: [148,0,211],
deeppink: [255,20,147],
deepskyblue: [0,191,255],
dimgray: [105,105,105],
dimgrey: [105,105,105],
dodgerblue: [30,144,255],
firebrick: [178,34,34],
floralwhite: [255,250,240],
forestgreen: [34,139,34],
fuchsia: [255,0,255],
gainsboro: [220,220,220],
ghostwhite: [248,248,255],
gold: [255,215,0],
goldenrod: [218,165,32],
gray: [128,128,128],
green: [0,128,0],
greenyellow: [173,255,47],
grey: [128,128,128],
honeydew: [240,255,240],
hotpink: [255,105,180],
indianred: [205,92,92],
indigo: [75,0,130],
ivory: [255,255,240],
khaki: [240,230,140],
lavender: [230,230,250],
lavenderblush: [255,240,245],
lawngreen: [124,252,0],
lemonchiffon: [255,250,205],
lightblue: [173,216,230],
lightcoral: [240,128,128],
lightcyan: [224,255,255],
lightgoldenrodyellow: [250,250,210],
lightgray: [211,211,211],
lightgreen: [144,238,144],
lightgrey: [211,211,211],
lightpink: [255,182,193],
lightsalmon: [255,160,122],
lightseagreen: [32,178,170],
lightskyblue: [135,206,250],
lightslategray: [119,136,153],
lightslategrey: [119,136,153],
lightsteelblue: [176,196,222],
lightyellow: [255,255,224],
lime: [0,255,0],
limegreen: [50,205,50],
linen: [250,240,230],
magenta: [255,0,255],
maroon: [128,0,0],
mediumaquamarine: [102,205,170],
mediumblue: [0,0,205],
mediumorchid: [186,85,211],
mediumpurple: [147,112,219],
mediumseagreen: [60,179,113],
mediumslateblue: [123,104,238],
mediumspringgreen: [0,250,154],
mediumturquoise: [72,209,204],
mediumvioletred: [199,21,133],
midnightblue: [25,25,112],
mintcream: [245,255,250],
mistyrose: [255,228,225],
moccasin: [255,228,181],
navajowhite: [255,222,173],
navy: [0,0,128],
oldlace: [253,245,230],
olive: [128,128,0],
olivedrab: [107,142,35],
orange: [255,165,0],
orangered: [255,69,0],
orchid: [218,112,214],
palegoldenrod: [238,232,170],
palegreen: [152,251,152],
paleturquoise: [175,238,238],
palevioletred: [219,112,147],
papayawhip: [255,239,213],
peachpuff: [255,218,185],
peru: [205,133,63],
pink: [255,192,203],
plum: [221,160,221],
powderblue: [176,224,230],
purple: [128,0,128],
rebeccapurple: [102, 51, 153],
red: [255,0,0],
rosybrown: [188,143,143],
royalblue: [65,105,225],
saddlebrown: [139,69,19],
salmon: [250,128,114],
sandybrown: [244,164,96],
seagreen: [46,139,87],
seashell: [255,245,238],
sienna: [160,82,45],
silver: [192,192,192],
skyblue: [135,206,235],
slateblue: [106,90,205],
slategray: [112,128,144],
slategrey: [112,128,144],
snow: [255,250,250],
springgreen: [0,255,127],
steelblue: [70,130,180],
tan: [210,180,140],
teal: [0,128,128],
thistle: [216,191,216],
tomato: [255,99,71],
turquoise: [64,224,208],
violet: [238,130,238],
wheat: [245,222,179],
white: [255,255,255],
whitesmoke: [245,245,245],
yellow: [255,255,0],
yellowgreen: [154,205,50]
};
var reverseKeywords = {};
for (var key in cssKeywords) {
reverseKeywords[JSON.stringify(cssKeywords[key])] = key;
}
},{}],5:[function(require,module,exports){
var conversions = require(4);
var convert = function() {
return new Converter();
}
for (var func in conversions) {
// export Raw versions
convert[func + "Raw"] = (function(func) {
// accept array or plain args
return function(arg) {
if (typeof arg == "number")
arg = Array.prototype.slice.call(arguments);
return conversions[func](arg);
}
})(func);
var pair = /(\w+)2(\w+)/.exec(func),
from = pair[1],
to = pair[2];
// export rgb2hsl and ["rgb"]["hsl"]
convert[from] = convert[from] || {};
convert[from][to] = convert[func] = (function(func) {
return function(arg) {
if (typeof arg == "number")
arg = Array.prototype.slice.call(arguments);
var val = conversions[func](arg);
if (typeof val == "string" || val === undefined)
return val; // keyword
for (var i = 0; i < val.length; i++)
val[i] = Math.round(val[i]);
return val;
}
})(func);
}
/* Converter does lazy conversion and caching */
var Converter = function() {
this.convs = {};
};
/* Either get the values for a space or
set the values for a space, depending on args */
Converter.prototype.routeSpace = function(space, args) {
var values = args[0];
if (values === undefined) {
// color.rgb()
return this.getValues(space);
}
// color.rgb(10, 10, 10)
if (typeof values == "number") {
values = Array.prototype.slice.call(args);
}
return this.setValues(space, values);
};
/* Set the values for a space, invalidating cache */
Converter.prototype.setValues = function(space, values) {
this.space = space;
this.convs = {};
this.convs[space] = values;
return this;
};
/* Get the values for a space. If there's already
a conversion for the space, fetch it, otherwise
compute it */
Converter.prototype.getValues = function(space) {
var vals = this.convs[space];
if (!vals) {
var fspace = this.space,
from = this.convs[fspace];
vals = convert[fspace][space](from);
this.convs[space] = vals;
}
return vals;
};
["rgb", "hsl", "hsv", "cmyk", "keyword"].forEach(function(space) {
Converter.prototype[space] = function(vals) {
return this.routeSpace(space, arguments);
}
});
module.exports = convert;
},{"4":4}],6:[function(require,module,exports){
module.exports = {
"aliceblue": [240, 248, 255],
"antiquewhite": [250, 235, 215],
"aqua": [0, 255, 255],
"aquamarine": [127, 255, 212],
"azure": [240, 255, 255],
"beige": [245, 245, 220],
"bisque": [255, 228, 196],
"black": [0, 0, 0],
"blanchedalmond": [255, 235, 205],
"blue": [0, 0, 255],
"blueviolet": [138, 43, 226],
"brown": [165, 42, 42],
"burlywood": [222, 184, 135],
"cadetblue": [95, 158, 160],
"chartreuse": [127, 255, 0],
"chocolate": [210, 105, 30],
"coral": [255, 127, 80],
"cornflowerblue": [100, 149, 237],
"cornsilk": [255, 248, 220],
"crimson": [220, 20, 60],
"cyan": [0, 255, 255],
"darkblue": [0, 0, 139],
"darkcyan": [0, 139, 139],
"darkgoldenrod": [184, 134, 11],
"darkgray": [169, 169, 169],
"darkgreen": [0, 100, 0],
"darkgrey": [169, 169, 169],
"darkkhaki": [189, 183, 107],
"darkmagenta": [139, 0, 139],
"darkolivegreen": [85, 107, 47],
"darkorange": [255, 140, 0],
"darkorchid": [153, 50, 204],
"darkred": [139, 0, 0],
"darksalmon": [233, 150, 122],
"darkseagreen": [143, 188, 143],
"darkslateblue": [72, 61, 139],
"darkslategray": [47, 79, 79],
"darkslategrey": [47, 79, 79],
"darkturquoise": [0, 206, 209],
"darkviolet": [148, 0, 211],
"deeppink": [255, 20, 147],
"deepskyblue": [0, 191, 255],
"dimgray": [105, 105, 105],
"dimgrey": [105, 105, 105],
"dodgerblue": [30, 144, 255],
"firebrick": [178, 34, 34],
"floralwhite": [255, 250, 240],
"forestgreen": [34, 139, 34],
"fuchsia": [255, 0, 255],
"gainsboro": [220, 220, 220],
"ghostwhite": [248, 248, 255],
"gold": [255, 215, 0],
"goldenrod": [218, 165, 32],
"gray": [128, 128, 128],
"green": [0, 128, 0],
"greenyellow": [173, 255, 47],
"grey": [128, 128, 128],
"honeydew": [240, 255, 240],
"hotpink": [255, 105, 180],
"indianred": [205, 92, 92],
"indigo": [75, 0, 130],
"ivory": [255, 255, 240],
"khaki": [240, 230, 140],
"lavender": [230, 230, 250],
"lavenderblush": [255, 240, 245],
"lawngreen": [124, 252, 0],
"lemonchiffon": [255, 250, 205],
"lightblue": [173, 216, 230],
"lightcoral": [240, 128, 128],
"lightcyan": [224, 255, 255],
"lightgoldenrodyellow": [250, 250, 210],
"lightgray": [211, 211, 211],
"lightgreen": [144, 238, 144],
"lightgrey": [211, 211, 211],
"lightpink": [255, 182, 193],
"lightsalmon": [255, 160, 122],
"lightseagreen": [32, 178, 170],
"lightskyblue": [135, 206, 250],
"lightslategray": [119, 136, 153],
"lightslategrey": [119, 136, 153],
"lightsteelblue": [176, 196, 222],
"lightyellow": [255, 255, 224],
"lime": [0, 255, 0],
"limegreen": [50, 205, 50],
"linen": [250, 240, 230],
"magenta": [255, 0, 255],
"maroon": [128, 0, 0],
"mediumaquamarine": [102, 205, 170],
"mediumblue": [0, 0, 205],
"mediumorchid": [186, 85, 211],
"mediumpurple": [147, 112, 219],
"mediumseagreen": [60, 179, 113],
"mediumslateblue": [123, 104, 238],
"mediumspringgreen": [0, 250, 154],
"mediumturquoise": [72, 209, 204],
"mediumvioletred": [199, 21, 133],
"midnightblue": [25, 25, 112],
"mintcream": [245, 255, 250],
"mistyrose": [255, 228, 225],
"moccasin": [255, 228, 181],
"navajowhite": [255, 222, 173],
"navy": [0, 0, 128],
"oldlace": [253, 245, 230],
"olive": [128, 128, 0],
"olivedrab": [107, 142, 35],
"orange": [255, 165, 0],
"orangered": [255, 69, 0],
"orchid": [218, 112, 214],
"palegoldenrod": [238, 232, 170],
"palegreen": [152, 251, 152],
"paleturquoise": [175, 238, 238],
"palevioletred": [219, 112, 147],
"papayawhip": [255, 239, 213],
"peachpuff": [255, 218, 185],
"peru": [205, 133, 63],
"pink": [255, 192, 203],
"plum": [221, 160, 221],
"powderblue": [176, 224, 230],
"purple": [128, 0, 128],
"rebeccapurple": [102, 51, 153],
"red": [255, 0, 0],
"rosybrown": [188, 143, 143],
"royalblue": [65, 105, 225],
"saddlebrown": [139, 69, 19],
"salmon": [250, 128, 114],
"sandybrown": [244, 164, 96],
"seagreen": [46, 139, 87],
"seashell": [255, 245, 238],
"sienna": [160, 82, 45],
"silver": [192, 192, 192],
"skyblue": [135, 206, 235],
"slateblue": [106, 90, 205],
"slategray": [112, 128, 144],
"slategrey": [112, 128, 144],
"snow": [255, 250, 250],
"springgreen": [0, 255, 127],
"steelblue": [70, 130, 180],
"tan": [210, 180, 140],
"teal": [0, 128, 128],
"thistle": [216, 191, 216],
"tomato": [255, 99, 71],
"turquoise": [64, 224, 208],
"violet": [238, 130, 238],
"wheat": [245, 222, 179],
"white": [255, 255, 255],
"whitesmoke": [245, 245, 245],
"yellow": [255, 255, 0],
"yellowgreen": [154, 205, 50]
};
},{}],7:[function(require,module,exports){
/**
* @namespace Chart
*/
var Chart = require(26)();
require(25)(Chart);
require(24)(Chart);
require(21)(Chart);
require(22)(Chart);
require(23)(Chart);
require(27)(Chart);
require(31)(Chart);
require(29)(Chart);
require(30)(Chart);
require(32)(Chart);
require(28)(Chart);
require(33)(Chart);
require(34)(Chart);
require(35)(Chart);
require(36)(Chart);
require(37)(Chart);
require(40)(Chart);
require(38)(Chart);
require(39)(Chart);
require(41)(Chart);
require(42)(Chart);
require(43)(Chart);
// Controllers must be loaded after elements
// See Chart.core.datasetController.dataElementType
require(15)(Chart);
require(16)(Chart);
require(17)(Chart);
require(18)(Chart);
require(19)(Chart);
require(20)(Chart);
require(8)(Chart);
require(9)(Chart);
require(10)(Chart);
require(11)(Chart);
require(12)(Chart);
require(13)(Chart);
require(14)(Chart);
window.Chart = module.exports = Chart;
},{"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"17":17,"18":18,"19":19,"20":20,"21":21,"22":22,"23":23,"24":24,"25":25,"26":26,"27":27,"28":28,"29":29,"30":30,"31":31,"32":32,"33":33,"34":34,"35":35,"36":36,"37":37,"38":38,"39":39,"40":40,"41":41,"42":42,"43":43,"8":8,"9":9}],8:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
Chart.Bar = function(context, config) {
config.type = 'bar';
return new Chart(context, config);
};
};
},{}],9:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
Chart.Bubble = function(context, config) {
config.type = 'bubble';
return new Chart(context, config);
};
};
},{}],10:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
Chart.Doughnut = function(context, config) {
config.type = 'doughnut';
return new Chart(context, config);
};
};
},{}],11:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
Chart.Line = function(context, config) {
config.type = 'line';
return new Chart(context, config);
};
};
},{}],12:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
Chart.PolarArea = function(context, config) {
config.type = 'polarArea';
return new Chart(context, config);
};
};
},{}],13:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
Chart.Radar = function(context, config) {
config.options = Chart.helpers.configMerge({ aspectRatio: 1 }, config.options);
config.type = 'radar';
return new Chart(context, config);
};
};
},{}],14:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var defaultConfig = {
hover: {
mode: 'single'
},
scales: {
xAxes: [{
type: "linear", // scatter should not use a category axis
position: "bottom",
id: "x-axis-1" // need an ID so datasets can reference the scale
}],
yAxes: [{
type: "linear",
position: "left",
id: "y-axis-1"
}]
},
tooltips: {
callbacks: {
title: function(tooltipItems, data) {
// Title doesn't make sense for scatter since we format the data as a point
return '';
},
label: function(tooltipItem, data) {
return '(' + tooltipItem.xLabel + ', ' + tooltipItem.yLabel + ')';
}
}
}
};
// Register the default config for this type
Chart.defaults.scatter = defaultConfig;
// Scatter charts use line controllers
Chart.controllers.scatter = Chart.controllers.line;
Chart.Scatter = function(context, config) {
config.type = 'scatter';
return new Chart(context, config);
};
};
},{}],15:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
Chart.defaults.bar = {
hover: {
mode: "label"
},
scales: {
xAxes: [{
type: "category",
// Specific to Bar Controller
categoryPercentage: 0.8,
barPercentage: 0.9,
// grid line settings
gridLines: {
offsetGridLines: true
}
}],
yAxes: [{
type: "linear"
}]
}
};
Chart.controllers.bar = Chart.DatasetController.extend({
dataElementType: Chart.elements.Rectangle,
initialize: function(chart, datasetIndex) {
Chart.DatasetController.prototype.initialize.call(this, chart, datasetIndex);
// Use this to indicate that this is a bar dataset.
this.getMeta().bar = true;
},
// Get the number of datasets that display bars. We use this to correctly calculate the bar width
getBarCount: function getBarCount() {
var me = this;
var barCount = 0;
helpers.each(me.chart.data.datasets, function(dataset, datasetIndex) {
var meta = me.chart.getDatasetMeta(datasetIndex);
if (meta.bar && me.chart.isDatasetVisible(datasetIndex)) {
++barCount;
}
}, me);
return barCount;
},
update: function update(reset) {
var me = this;
helpers.each(me.getMeta().data, function(rectangle, index) {
me.updateElement(rectangle, index, reset);
}, me);
},
updateElement: function updateElement(rectangle, index, reset) {
var me = this;
var meta = me.getMeta();
var xScale = me.getScaleForId(meta.xAxisID);
var yScale = me.getScaleForId(meta.yAxisID);
var scaleBase = yScale.getBasePixel();
var rectangleElementOptions = me.chart.options.elements.rectangle;
var custom = rectangle.custom || {};
var dataset = me.getDataset();
helpers.extend(rectangle, {
// Utility
_xScale: xScale,
_yScale: yScale,
_datasetIndex: me.index,
_index: index,
// Desired view properties
_model: {
x: me.calculateBarX(index, me.index),
y: reset ? scaleBase : me.calculateBarY(index, me.index),
// Tooltip
label: me.chart.data.labels[index],
datasetLabel: dataset.label,
// Appearance
base: reset ? scaleBase : me.calculateBarBase(me.index, index),
width: me.calculateBarWidth(index),
backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.backgroundColor, index, rectangleElementOptions.backgroundColor),
borderSkipped: custom.borderSkipped ? custom.borderSkipped : rectangleElementOptions.borderSkipped,
borderColor: custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.borderColor, index, rectangleElementOptions.borderColor),
borderWidth: custom.borderWidth ? custom.borderWidth : helpers.getValueAtIndexOrDefault(dataset.borderWidth, index, rectangleElementOptions.borderWidth)
}
});
rectangle.pivot();
},
calculateBarBase: function(datasetIndex, index) {
var me = this;
var meta = me.getMeta();
var yScale = me.getScaleForId(meta.yAxisID);
var base = 0;
if (yScale.options.stacked) {
var chart = me.chart;
var datasets = chart.data.datasets;
var value = datasets[datasetIndex].data[index];
if (value < 0) {
for (var i = 0; i < datasetIndex; i++) {
var negDS = datasets[i];
var negDSMeta = chart.getDatasetMeta(i);
if (negDSMeta.bar && negDSMeta.yAxisID === yScale.id && chart.isDatasetVisible(i)) {
base += negDS.data[index] < 0 ? negDS.data[index] : 0;
}
}
} else {
for (var j = 0; j < datasetIndex; j++) {
var posDS = datasets[j];
var posDSMeta = chart.getDatasetMeta(j);
if (posDSMeta.bar && posDSMeta.yAxisID === yScale.id && chart.isDatasetVisible(j)) {
base += posDS.data[index] > 0 ? posDS.data[index] : 0;
}
}
}
return yScale.getPixelForValue(base);
}
return yScale.getBasePixel();
},
getRuler: function(index) {
var me = this;
var meta = me.getMeta();
var xScale = me.getScaleForId(meta.xAxisID);
var datasetCount = me.getBarCount();
var tickWidth;
if (xScale.options.type === 'category') {
tickWidth = xScale.getPixelForTick(index + 1) - xScale.getPixelForTick(index);
} else {
// Average width
tickWidth = xScale.width / xScale.ticks.length;
}
var categoryWidth = tickWidth * xScale.options.categoryPercentage;
var categorySpacing = (tickWidth - (tickWidth * xScale.options.categoryPercentage)) / 2;
var fullBarWidth = categoryWidth / datasetCount;
if (xScale.ticks.length !== me.chart.data.labels.length) {
var perc = xScale.ticks.length / me.chart.data.labels.length;
fullBarWidth = fullBarWidth * perc;
}
var barWidth = fullBarWidth * xScale.options.barPercentage;
var barSpacing = fullBarWidth - (fullBarWidth * xScale.options.barPercentage);
return {
datasetCount: datasetCount,
tickWidth: tickWidth,
categoryWidth: categoryWidth,
categorySpacing: categorySpacing,
fullBarWidth: fullBarWidth,
barWidth: barWidth,
barSpacing: barSpacing
};
},
calculateBarWidth: function(index) {
var xScale = this.getScaleForId(this.getMeta().xAxisID);
var ruler = this.getRuler(index);
return xScale.options.stacked ? ruler.categoryWidth : ruler.barWidth;
},
// Get bar index from the given dataset index accounting for the fact that not all bars are visible
getBarIndex: function(datasetIndex) {
var barIndex = 0;
var meta, j;
for (j = 0; j < datasetIndex; ++j) {
meta = this.chart.getDatasetMeta(j);
if (meta.bar && this.chart.isDatasetVisible(j)) {
++barIndex;
}
}
return barIndex;
},
calculateBarX: function(index, datasetIndex) {
var me = this;
var meta = me.getMeta();
var xScale = me.getScaleForId(meta.xAxisID);
var barIndex = me.getBarIndex(datasetIndex);
var ruler = me.getRuler(index);
var leftTick = xScale.getPixelForValue(null, index, datasetIndex, me.chart.isCombo);
leftTick -= me.chart.isCombo ? (ruler.tickWidth / 2) : 0;
if (xScale.options.stacked) {
return leftTick + (ruler.categoryWidth / 2) + ruler.categorySpacing;
}
return leftTick +
(ruler.barWidth / 2) +
ruler.categorySpacing +
(ruler.barWidth * barIndex) +
(ruler.barSpacing / 2) +
(ruler.barSpacing * barIndex);
},
calculateBarY: function(index, datasetIndex) {
var me = this;
var meta = me.getMeta();
var yScale = me.getScaleForId(meta.yAxisID);
var value = me.getDataset().data[index];
if (yScale.options.stacked) {
var sumPos = 0,
sumNeg = 0;
for (var i = 0; i < datasetIndex; i++) {
var ds = me.chart.data.datasets[i];
var dsMeta = me.chart.getDatasetMeta(i);
if (dsMeta.bar && dsMeta.yAxisID === yScale.id && me.chart.isDatasetVisible(i)) {
if (ds.data[index] < 0) {
sumNeg += ds.data[index] || 0;
} else {
sumPos += ds.data[index] || 0;
}
}
}
if (value < 0) {
return yScale.getPixelForValue(sumNeg + value);
} else {
return yScale.getPixelForValue(sumPos + value);
}
}
return yScale.getPixelForValue(value);
},
draw: function(ease) {
var me = this;
var easingDecimal = ease || 1;
helpers.each(me.getMeta().data, function(rectangle, index) {
var d = me.getDataset().data[index];
if (d !== null && d !== undefined && !isNaN(d)) {
rectangle.transition(easingDecimal).draw();
}
}, me);
},
setHoverStyle: function(rectangle) {
var dataset = this.chart.data.datasets[rectangle._datasetIndex];
var index = rectangle._index;
var custom = rectangle.custom || {};
var model = rectangle._model;
model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.getValueAtIndexOrDefault(dataset.hoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.getValueAtIndexOrDefault(dataset.hoverBorderColor, index, helpers.getHoverColor(model.borderColor));
model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.getValueAtIndexOrDefault(dataset.hoverBorderWidth, index, model.borderWidth);
},
removeHoverStyle: function(rectangle) {
var dataset = this.chart.data.datasets[rectangle._datasetIndex];
var index = rectangle._index;
var custom = rectangle.custom || {};
var model = rectangle._model;
var rectangleElementOptions = this.chart.options.elements.rectangle;
model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.backgroundColor, index, rectangleElementOptions.backgroundColor);
model.borderColor = custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.borderColor, index, rectangleElementOptions.borderColor);
model.borderWidth = custom.borderWidth ? custom.borderWidth : helpers.getValueAtIndexOrDefault(dataset.borderWidth, index, rectangleElementOptions.borderWidth);
}
});
// including horizontalBar in the bar file, instead of a file of its own
// it extends bar (like pie extends doughnut)
Chart.defaults.horizontalBar = {
hover: {
mode: "label"
},
scales: {
xAxes: [{
type: "linear",
position: "bottom"
}],
yAxes: [{
position: "left",
type: "category",
// Specific to Horizontal Bar Controller
categoryPercentage: 0.8,
barPercentage: 0.9,
// grid line settings
gridLines: {
offsetGridLines: true
}
}]
},
elements: {
rectangle: {
borderSkipped: 'left'
}
},
tooltips: {
callbacks: {
title: function(tooltipItems, data) {
// Pick first xLabel for now
var title = '';
if (tooltipItems.length > 0) {
if (tooltipItems[0].yLabel) {
title = tooltipItems[0].yLabel;
} else if (data.labels.length > 0 && tooltipItems[0].index < data.labels.length) {
title = data.labels[tooltipItems[0].index];
}
}
return title;
},
label: function(tooltipItem, data) {
var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || '';
return datasetLabel + ': ' + tooltipItem.xLabel;
}
}
}
};
Chart.controllers.horizontalBar = Chart.controllers.bar.extend({
updateElement: function updateElement(rectangle, index, reset, numBars) {
var me = this;
var meta = me.getMeta();
var xScale = me.getScaleForId(meta.xAxisID);
var yScale = me.getScaleForId(meta.yAxisID);
var scaleBase = xScale.getBasePixel();
var custom = rectangle.custom || {};
var dataset = me.getDataset();
var rectangleElementOptions = me.chart.options.elements.rectangle;
helpers.extend(rectangle, {
// Utility
_xScale: xScale,
_yScale: yScale,
_datasetIndex: me.index,
_index: index,
// Desired view properties
_model: {
x: reset ? scaleBase : me.calculateBarX(index, me.index),
y: me.calculateBarY(index, me.index),
// Tooltip
label: me.chart.data.labels[index],
datasetLabel: dataset.label,
// Appearance
base: reset ? scaleBase : me.calculateBarBase(me.index, index),
height: me.calculateBarHeight(index),
backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.backgroundColor, index, rectangleElementOptions.backgroundColor),
borderSkipped: custom.borderSkipped ? custom.borderSkipped : rectangleElementOptions.borderSkipped,
borderColor: custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.borderColor, index, rectangleElementOptions.borderColor),
borderWidth: custom.borderWidth ? custom.borderWidth : helpers.getValueAtIndexOrDefault(dataset.borderWidth, index, rectangleElementOptions.borderWidth)
},
draw: function () {
var ctx = this._chart.ctx;
var vm = this._view;
var halfHeight = vm.height / 2,
topY = vm.y - halfHeight,
bottomY = vm.y + halfHeight,
right = vm.base - (vm.base - vm.x),
halfStroke = vm.borderWidth / 2;
// Canvas doesn't allow us to stroke inside the width so we can
// adjust the sizes to fit if we're setting a stroke on the line
if (vm.borderWidth) {
topY += halfStroke;
bottomY -= halfStroke;
right += halfStroke;
}
ctx.beginPath();
ctx.fillStyle = vm.backgroundColor;
ctx.strokeStyle = vm.borderColor;
ctx.lineWidth = vm.borderWidth;
// Corner points, from bottom-left to bottom-right clockwise
// | 1 2 |
// | 0 3 |
var corners = [
[vm.base, bottomY],
[vm.base, topY],
[right, topY],
[right, bottomY]
];
// Find first (starting) corner with fallback to 'bottom'
var borders = ['bottom', 'left', 'top', 'right'];
var startCorner = borders.indexOf(vm.borderSkipped, 0);
if (startCorner === -1)
startCorner = 0;
function cornerAt(index) {
return corners[(startCorner + index) % 4];
}
// Draw rectangle from 'startCorner'
ctx.moveTo.apply(ctx, cornerAt(0));
for (var i = 1; i < 4; i++)
ctx.lineTo.apply(ctx, cornerAt(i));
ctx.fill();
if (vm.borderWidth) {
ctx.stroke();
}
},
inRange: function (mouseX, mouseY) {
var vm = this._view;
var inRange = false;
if (vm) {
if (vm.x < vm.base) {
inRange = (mouseY >= vm.y - vm.height / 2 && mouseY <= vm.y + vm.height / 2) && (mouseX >= vm.x && mouseX <= vm.base);
} else {
inRange = (mouseY >= vm.y - vm.height / 2 && mouseY <= vm.y + vm.height / 2) && (mouseX >= vm.base && mouseX <= vm.x);
}
}
return inRange;
}
});
rectangle.pivot();
},
calculateBarBase: function (datasetIndex, index) {
var me = this;
var meta = me.getMeta();
var xScale = me.getScaleForId(meta.xAxisID);
var base = 0;
if (xScale.options.stacked) {
var value = me.chart.data.datasets[datasetIndex].data[index];
if (value < 0) {
for (var i = 0; i < datasetIndex; i++) {
var negDS = me.chart.data.datasets[i];
var negDSMeta = me.chart.getDatasetMeta(i);
if (negDSMeta.bar && negDSMeta.xAxisID === xScale.id && me.chart.isDatasetVisible(i)) {
base += negDS.data[index] < 0 ? negDS.data[index] : 0;
}
}
} else {
for (var j = 0; j < datasetIndex; j++) {
var posDS = me.chart.data.datasets[j];
var posDSMeta = me.chart.getDatasetMeta(j);
if (posDSMeta.bar && posDSMeta.xAxisID === xScale.id && me.chart.isDatasetVisible(j)) {
base += posDS.data[index] > 0 ? posDS.data[index] : 0;
}
}
}
return xScale.getPixelForValue(base);
}
return xScale.getBasePixel();
},
getRuler: function (index) {
var me = this;
var meta = me.getMeta();
var yScale = me.getScaleForId(meta.yAxisID);
var datasetCount = me.getBarCount();
var tickHeight;
if (yScale.options.type === 'category') {
tickHeight = yScale.getPixelForTick(index + 1) - yScale.getPixelForTick(index);
} else {
// Average width
tickHeight = yScale.width / yScale.ticks.length;
}
var categoryHeight = tickHeight * yScale.options.categoryPercentage;
var categorySpacing = (tickHeight - (tickHeight * yScale.options.categoryPercentage)) / 2;
var fullBarHeight = categoryHeight / datasetCount;
if (yScale.ticks.length !== me.chart.data.labels.length) {
var perc = yScale.ticks.length / me.chart.data.labels.length;
fullBarHeight = fullBarHeight * perc;
}
var barHeight = fullBarHeight * yScale.options.barPercentage;
var barSpacing = fullBarHeight - (fullBarHeight * yScale.options.barPercentage);
return {
datasetCount: datasetCount,
tickHeight: tickHeight,
categoryHeight: categoryHeight,
categorySpacing: categorySpacing,
fullBarHeight: fullBarHeight,
barHeight: barHeight,
barSpacing: barSpacing,
};
},
calculateBarHeight: function (index) {
var me = this;
var yScale = me.getScaleForId(me.getMeta().yAxisID);
var ruler = me.getRuler(index);
return yScale.options.stacked ? ruler.categoryHeight : ruler.barHeight;
},
calculateBarX: function (index, datasetIndex) {
var me = this;
var meta = me.getMeta();
var xScale = me.getScaleForId(meta.xAxisID);
var value = me.getDataset().data[index];
if (xScale.options.stacked) {
var sumPos = 0,
sumNeg = 0;
for (var i = 0; i < datasetIndex; i++) {
var ds = me.chart.data.datasets[i];
var dsMeta = me.chart.getDatasetMeta(i);
if (dsMeta.bar && dsMeta.xAxisID === xScale.id && me.chart.isDatasetVisible(i)) {
if (ds.data[index] < 0) {
sumNeg += ds.data[index] || 0;
} else {
sumPos += ds.data[index] || 0;
}
}
}
if (value < 0) {
return xScale.getPixelForValue(sumNeg + value);
} else {
return xScale.getPixelForValue(sumPos + value);
}
}
return xScale.getPixelForValue(value);
},
calculateBarY: function (index, datasetIndex) {
var me = this;
var meta = me.getMeta();
var yScale = me.getScaleForId(meta.yAxisID);
var barIndex = me.getBarIndex(datasetIndex);
var ruler = me.getRuler(index);
var topTick = yScale.getPixelForValue(null, index, datasetIndex, me.chart.isCombo);
topTick -= me.chart.isCombo ? (ruler.tickHeight / 2) : 0;
if (yScale.options.stacked) {
return topTick + (ruler.categoryHeight / 2) + ruler.categorySpacing;
}
return topTick +
(ruler.barHeight / 2) +
ruler.categorySpacing +
(ruler.barHeight * barIndex) +
(ruler.barSpacing / 2) +
(ruler.barSpacing * barIndex);
}
});
};
},{}],16:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
Chart.defaults.bubble = {
hover: {
mode: "single"
},
scales: {
xAxes: [{
type: "linear", // bubble should probably use a linear scale by default
position: "bottom",
id: "x-axis-0" // need an ID so datasets can reference the scale
}],
yAxes: [{
type: "linear",
position: "left",
id: "y-axis-0"
}]
},
tooltips: {
callbacks: {
title: function(tooltipItems, data) {
// Title doesn't make sense for scatter since we format the data as a point
return '';
},
label: function(tooltipItem, data) {
var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || '';
var dataPoint = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
return datasetLabel + ': (' + dataPoint.x + ', ' + dataPoint.y + ', ' + dataPoint.r + ')';
}
}
}
};
Chart.controllers.bubble = Chart.DatasetController.extend({
dataElementType: Chart.elements.Point,
update: function update(reset) {
var me = this;
var meta = me.getMeta();
var points = meta.data;
// Update Points
helpers.each(points, function(point, index) {
me.updateElement(point, index, reset);
});
},
updateElement: function(point, index, reset) {
var me = this;
var meta = me.getMeta();
var xScale = me.getScaleForId(meta.xAxisID);
var yScale = me.getScaleForId(meta.yAxisID);
var custom = point.custom || {};
var dataset = me.getDataset();
var data = dataset.data[index];
var pointElementOptions = me.chart.options.elements.point;
var dsIndex = me.index;
helpers.extend(point, {
// Utility
_xScale: xScale,
_yScale: yScale,
_datasetIndex: dsIndex,
_index: index,
// Desired view properties
_model: {
x: reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(data, index, dsIndex, me.chart.isCombo),
y: reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex),
// Appearance
radius: reset ? 0 : custom.radius ? custom.radius : me.getRadius(data),
// Tooltip
hitRadius: custom.hitRadius ? custom.hitRadius : helpers.getValueAtIndexOrDefault(dataset.hitRadius, index, pointElementOptions.hitRadius)
}
});
// Trick to reset the styles of the point
Chart.DatasetController.prototype.removeHoverStyle.call(me, point, pointElementOptions);
var model = point._model;
model.skip = custom.skip ? custom.skip : (isNaN(model.x) || isNaN(model.y));
point.pivot();
},
getRadius: function(value) {
return value.r || this.chart.options.elements.point.radius;
},
setHoverStyle: function(point) {
var me = this;
Chart.DatasetController.prototype.setHoverStyle.call(me, point);
// Radius
var dataset = me.chart.data.datasets[point._datasetIndex];
var index = point._index;
var custom = point.custom || {};
var model = point._model;
model.radius = custom.hoverRadius ? custom.hoverRadius : (helpers.getValueAtIndexOrDefault(dataset.hoverRadius, index, me.chart.options.elements.point.hoverRadius)) + me.getRadius(dataset.data[index]);
},
removeHoverStyle: function(point) {
var me = this;
Chart.DatasetController.prototype.removeHoverStyle.call(me, point, me.chart.options.elements.point);
var dataVal = me.chart.data.datasets[point._datasetIndex].data[point._index];
var custom = point.custom || {};
var model = point._model;
model.radius = custom.radius ? custom.radius : me.getRadius(dataVal);
}
});
};
},{}],17:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers,
defaults = Chart.defaults;
defaults.doughnut = {
animation: {
//Boolean - Whether we animate the rotation of the Doughnut
animateRotate: true,
//Boolean - Whether we animate scaling the Doughnut from the centre
animateScale: false
},
aspectRatio: 1,
hover: {
mode: 'single'
},
legendCallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend">');
var data = chart.data;
var datasets = data.datasets;
var labels = data.labels;
if (datasets.length) {
for (var i = 0; i < datasets[0].data.length; ++i) {
text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
if (labels[i]) {
text.push(labels[i]);
}
text.push('</li>');
}
}
text.push('</ul>');
return text.join("");
},
legend: {
labels: {
generateLabels: function(chart) {
var data = chart.data;
if (data.labels.length && data.datasets.length) {
return data.labels.map(function(label, i) {
var meta = chart.getDatasetMeta(0);
var ds = data.datasets[0];
var arc = meta.data[i];
var custom = arc.custom || {};
var getValueAtIndexOrDefault = helpers.getValueAtIndexOrDefault;
var arcOpts = chart.options.elements.arc;
var fill = custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
var stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
var bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
return {
text: label,
fillStyle: fill,
strokeStyle: stroke,
lineWidth: bw,
hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
// Extra data used for toggling the correct item
index: i
};
});
} else {
return [];
}
}
},
onClick: function(e, legendItem) {
var index = legendItem.index;
var chart = this.chart;
var i, ilen, meta;
for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
meta = chart.getDatasetMeta(i);
meta.data[index].hidden = !meta.data[index].hidden;
}
chart.update();
}
},
//The percentage of the chart that we cut out of the middle.
cutoutPercentage: 50,
//The rotation of the chart, where the first data arc begins.
rotation: Math.PI * -0.5,
//The total circumference of the chart.
circumference: Math.PI * 2.0,
// Need to override these to give a nice default
tooltips: {
callbacks: {
title: function() {
return '';
},
label: function(tooltipItem, data) {
return data.labels[tooltipItem.index] + ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
}
}
}
};
defaults.pie = helpers.clone(defaults.doughnut);
helpers.extend(defaults.pie, {
cutoutPercentage: 0
});
Chart.controllers.doughnut = Chart.controllers.pie = Chart.DatasetController.extend({
dataElementType: Chart.elements.Arc,
linkScales: helpers.noop,
// Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
getRingIndex: function getRingIndex(datasetIndex) {
var ringIndex = 0;
for (var j = 0; j < datasetIndex; ++j) {
if (this.chart.isDatasetVisible(j)) {
++ringIndex;
}
}
return ringIndex;
},
update: function update(reset) {
var me = this;
var chart = me.chart,
chartArea = chart.chartArea,
opts = chart.options,
arcOpts = opts.elements.arc,
availableWidth = chartArea.right - chartArea.left - arcOpts.borderWidth,
availableHeight = chartArea.bottom - chartArea.top - arcOpts.borderWidth,
minSize = Math.min(availableWidth, availableHeight),
offset = {
x: 0,
y: 0
},
meta = me.getMeta(),
cutoutPercentage = opts.cutoutPercentage,
circumference = opts.circumference;
// If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc
if (circumference < Math.PI * 2.0) {
var startAngle = opts.rotation % (Math.PI * 2.0);
startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0);
var endAngle = startAngle + circumference;
var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)};
var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)};
var contains0 = (startAngle <= 0 && 0 <= endAngle) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle);
var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle);
var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle);
var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle);
var cutout = cutoutPercentage / 100.0;
var min = {x: contains180 ? -1 : Math.min(start.x * (start.x < 0 ? 1 : cutout), end.x * (end.x < 0 ? 1 : cutout)), y: contains270 ? -1 : Math.min(start.y * (start.y < 0 ? 1 : cutout), end.y * (end.y < 0 ? 1 : cutout))};
var max = {x: contains0 ? 1 : Math.max(start.x * (start.x > 0 ? 1 : cutout), end.x * (end.x > 0 ? 1 : cutout)), y: contains90 ? 1 : Math.max(start.y * (start.y > 0 ? 1 : cutout), end.y * (end.y > 0 ? 1 : cutout))};
var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5};
minSize = Math.min(availableWidth / size.width, availableHeight / size.height);
offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5};
}
chart.outerRadius = Math.max(minSize / 2, 0);
chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 1, 0);
chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
chart.offsetX = offset.x * chart.outerRadius;
chart.offsetY = offset.y * chart.outerRadius;
meta.total = me.calculateTotal();
me.outerRadius = chart.outerRadius - (chart.radiusLength * me.getRingIndex(me.index));
me.innerRadius = me.outerRadius - chart.radiusLength;
helpers.each(meta.data, function(arc, index) {
me.updateElement(arc, index, reset);
});
},
updateElement: function(arc, index, reset) {
var me = this;
var chart = me.chart,
chartArea = chart.chartArea,
opts = chart.options,
animationOpts = opts.animation,
arcOpts = opts.elements.arc,
centerX = (chartArea.left + chartArea.right) / 2,
centerY = (chartArea.top + chartArea.bottom) / 2,
startAngle = opts.rotation, // non reset case handled later
endAngle = opts.rotation, // non reset case handled later
dataset = me.getDataset(),
circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI)),
innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius,
outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius,
custom = arc.custom || {},
valueAtIndexOrDefault = helpers.getValueAtIndexOrDefault;
helpers.extend(arc, {
// Utility
_datasetIndex: me.index,
_index: index,
// Desired view properties
_model: {
x: centerX + chart.offsetX,
y: centerY + chart.offsetY,
startAngle: startAngle,
endAngle: endAngle,
circumference: circumference,
outerRadius: outerRadius,
innerRadius: innerRadius,
label: valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
}
});
var model = arc._model;
// Resets the visual styles
this.removeHoverStyle(arc);
// Set correct angles if not resetting
if (!reset || !animationOpts.animateRotate) {
if (index === 0) {
model.startAngle = opts.rotation;
} else {
model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
}
model.endAngle = model.startAngle + model.circumference;
}
arc.pivot();
},
removeHoverStyle: function(arc) {
Chart.DatasetController.prototype.removeHoverStyle.call(this, arc, this.chart.options.elements.arc);
},
calculateTotal: function() {
var dataset = this.getDataset();
var meta = this.getMeta();
var total = 0;
var value;
helpers.each(meta.data, function(element, index) {
value = dataset.data[index];
if (!isNaN(value) && !element.hidden) {
total += Math.abs(value);
}
});
return total;
},
calculateCircumference: function(value) {
var total = this.getMeta().total;
if (total > 0 && !isNaN(value)) {
return (Math.PI * 2.0) * (value / total);
} else {
return 0;
}
}
});
};
},{}],18:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
Chart.defaults.line = {
showLines: true,
hover: {
mode: "label"
},
scales: {
xAxes: [{
type: "category",
id: 'x-axis-0'
}],
yAxes: [{
type: "linear",
id: 'y-axis-0'
}]
}
};
function lineEnabled(dataset, options) {
return helpers.getValueOrDefault(dataset.showLine, options.showLines);
}
Chart.controllers.line = Chart.DatasetController.extend({
datasetElementType: Chart.elements.Line,
dataElementType: Chart.elements.Point,
addElementAndReset: function(index) {
var me = this;
var options = me.chart.options;
var meta = me.getMeta();
Chart.DatasetController.prototype.addElementAndReset.call(me, index);
// Make sure bezier control points are updated
if (lineEnabled(me.getDataset(), options) && meta.dataset._model.tension !== 0) {
me.updateBezierControlPoints();
}
},
update: function update(reset) {
var me = this;
var meta = me.getMeta();
var line = meta.dataset;
var points = meta.data || [];
var options = me.chart.options;
var lineElementOptions = options.elements.line;
var scale = me.getScaleForId(meta.yAxisID);
var i, ilen, custom;
var dataset = me.getDataset();
var showLine = lineEnabled(dataset, options);
// Update Line
if (showLine) {
custom = line.custom || {};
// Compatibility: If the properties are defined with only the old name, use those values
if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
dataset.lineTension = dataset.tension;
}
// Utility
line._scale = scale;
line._datasetIndex = me.index;
// Data
line._children = points;
// Model
line._model = {
// Appearance
// The default behavior of lines is to break at null values, according
// to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
// This option gives linse the ability to span gaps
spanGaps: dataset.spanGaps ? dataset.spanGaps : false,
tension: custom.tension ? custom.tension : helpers.getValueOrDefault(dataset.lineTension, lineElementOptions.tension),
backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor),
borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth),
borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor),
borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle),
borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash),
borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset),
borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle),
fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill),
// Scale
scaleTop: scale.top,
scaleBottom: scale.bottom,
scaleZero: scale.getBasePixel()
};
line.pivot();
}
// Update Points
for (i=0, ilen=points.length; i<ilen; ++i) {
me.updateElement(points[i], i, reset);
}
if (showLine && line._model.tension !== 0) {
me.updateBezierControlPoints();
}
// Now pivot the point for animation
for (i=0, ilen=points.length; i<ilen; ++i) {
points[i].pivot();
}
},
getPointBackgroundColor: function(point, index) {
var backgroundColor = this.chart.options.elements.point.backgroundColor;
var dataset = this.getDataset();
var custom = point.custom || {};
if (custom.backgroundColor) {
backgroundColor = custom.backgroundColor;
} else if (dataset.pointBackgroundColor) {
backgroundColor = helpers.getValueAtIndexOrDefault(dataset.pointBackgroundColor, index, backgroundColor);
} else if (dataset.backgroundColor) {
backgroundColor = dataset.backgroundColor;
}
return backgroundColor;
},
getPointBorderColor: function(point, index) {
var borderColor = this.chart.options.elements.point.borderColor;
var dataset = this.getDataset();
var custom = point.custom || {};
if (custom.borderColor) {
borderColor = custom.borderColor;
} else if (dataset.pointBorderColor) {
borderColor = helpers.getValueAtIndexOrDefault(dataset.pointBorderColor, index, borderColor);
} else if (dataset.borderColor) {
borderColor = dataset.borderColor;
}
return borderColor;
},
getPointBorderWidth: function(point, index) {
var borderWidth = this.chart.options.elements.point.borderWidth;
var dataset = this.getDataset();
var custom = point.custom || {};
if (custom.borderWidth) {
borderWidth = custom.borderWidth;
} else if (dataset.pointBorderWidth) {
borderWidth = helpers.getValueAtIndexOrDefault(dataset.pointBorderWidth, index, borderWidth);
} else if (dataset.borderWidth) {
borderWidth = dataset.borderWidth;
}
return borderWidth;
},
updateElement: function(point, index, reset) {
var me = this;
var meta = me.getMeta();
var custom = point.custom || {};
var dataset = me.getDataset();
var datasetIndex = me.index;
var value = dataset.data[index];
var yScale = me.getScaleForId(meta.yAxisID);
var xScale = me.getScaleForId(meta.xAxisID);
var pointOptions = me.chart.options.elements.point;
var x, y;
// Compatibility: If the properties are defined with only the old name, use those values
if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
dataset.pointRadius = dataset.radius;
}
if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) {
dataset.pointHitRadius = dataset.hitRadius;
}
x = xScale.getPixelForValue(value, index, datasetIndex, me.chart.isCombo);
y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex, me.chart.isCombo);
// Utility
point._xScale = xScale;
point._yScale = yScale;
point._datasetIndex = datasetIndex;
point._index = index;
// Desired view properties
point._model = {
x: x,
y: y,
skip: custom.skip || isNaN(x) || isNaN(y),
// Appearance
radius: custom.radius || helpers.getValueAtIndexOrDefault(dataset.pointRadius, index, pointOptions.radius),
pointStyle: custom.pointStyle || helpers.getValueAtIndexOrDefault(dataset.pointStyle, index, pointOptions.pointStyle),
backgroundColor: me.getPointBackgroundColor(point, index),
borderColor: me.getPointBorderColor(point, index),
borderWidth: me.getPointBorderWidth(point, index),
tension: meta.dataset._model ? meta.dataset._model.tension : 0,
// Tooltip
hitRadius: custom.hitRadius || helpers.getValueAtIndexOrDefault(dataset.pointHitRadius, index, pointOptions.hitRadius)
};
},
calculatePointY: function(value, index, datasetIndex, isCombo) {
var me = this;
var chart = me.chart;
var meta = me.getMeta();
var yScale = me.getScaleForId(meta.yAxisID);
var sumPos = 0;
var sumNeg = 0;
var i, ds, dsMeta;
if (yScale.options.stacked) {
for (i = 0; i < datasetIndex; i++) {
ds = chart.data.datasets[i];
dsMeta = chart.getDatasetMeta(i);
if (dsMeta.type === 'line' && chart.isDatasetVisible(i)) {
if (ds.data[index] < 0) {
sumNeg += ds.data[index] || 0;
} else {
sumPos += ds.data[index] || 0;
}
}
}
if (value < 0) {
return yScale.getPixelForValue(sumNeg + value);
} else {
return yScale.getPixelForValue(sumPos + value);
}
}
return yScale.getPixelForValue(value);
},
updateBezierControlPoints: function() {
var meta = this.getMeta();
var area = this.chart.chartArea;
var points = meta.data || [];
var i, ilen, point, model, controlPoints;
for (i=0, ilen=points.length; i<ilen; ++i) {
point = points[i];
model = point._model;
controlPoints = helpers.splineCurve(
helpers.previousItem(points, i)._model,
model,
helpers.nextItem(points, i)._model,
meta.dataset._model.tension
);
model.controlPointPreviousX = controlPoints.previous.x;
model.controlPointPreviousY = controlPoints.previous.y;
model.controlPointNextX = controlPoints.next.x;
model.controlPointNextY = controlPoints.next.y;
}
},
draw: function(ease) {
var me = this;
var meta = me.getMeta();
var points = meta.data || [];
var easingDecimal = ease || 1;
var i, ilen;
// Transition Point Locations
for (i=0, ilen=points.length; i<ilen; ++i) {
points[i].transition(easingDecimal);
}
// Transition and Draw the line
if (lineEnabled(me.getDataset(), me.chart.options)) {
meta.dataset.transition(easingDecimal).draw();
}
// Draw the points
for (i=0, ilen=points.length; i<ilen; ++i) {
points[i].draw();
}
},
setHoverStyle: function(point) {
// Point
var dataset = this.chart.data.datasets[point._datasetIndex];
var index = point._index;
var custom = point.custom || {};
var model = point._model;
model.radius = custom.hoverRadius || helpers.getValueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius);
model.backgroundColor = custom.hoverBackgroundColor || helpers.getValueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
model.borderColor = custom.hoverBorderColor || helpers.getValueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor));
model.borderWidth = custom.hoverBorderWidth || helpers.getValueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth);
},
removeHoverStyle: function(point) {
var me = this;
var dataset = me.chart.data.datasets[point._datasetIndex];
var index = point._index;
var custom = point.custom || {};
var model = point._model;
// Compatibility: If the properties are defined with only the old name, use those values
if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
dataset.pointRadius = dataset.radius;
}
model.radius = custom.radius || helpers.getValueAtIndexOrDefault(dataset.pointRadius, index, me.chart.options.elements.point.radius);
model.backgroundColor = me.getPointBackgroundColor(point, index);
model.borderColor = me.getPointBorderColor(point, index);
model.borderWidth = me.getPointBorderWidth(point, index);
}
});
};
},{}],19:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
Chart.defaults.polarArea = {
scale: {
type: "radialLinear",
lineArc: true // so that lines are circular
},
//Boolean - Whether to animate the rotation of the chart
animation: {
animateRotate: true,
animateScale: true
},
aspectRatio: 1,
legendCallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend">');
var data = chart.data;
var datasets = data.datasets;
var labels = data.labels;
if (datasets.length) {
for (var i = 0; i < datasets[0].data.length; ++i) {
text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '">');
if (labels[i]) {
text.push(labels[i]);
}
text.push('</span></li>');
}
}
text.push('</ul>');
return text.join("");
},
legend: {
labels: {
generateLabels: function(chart) {
var data = chart.data;
if (data.labels.length && data.datasets.length) {
return data.labels.map(function(label, i) {
var meta = chart.getDatasetMeta(0);
var ds = data.datasets[0];
var arc = meta.data[i];
var custom = arc.custom || {};
var getValueAtIndexOrDefault = helpers.getValueAtIndexOrDefault;
var arcOpts = chart.options.elements.arc;
var fill = custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
var stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
var bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
return {
text: label,
fillStyle: fill,
strokeStyle: stroke,
lineWidth: bw,
hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
// Extra data used for toggling the correct item
index: i
};
});
} else {
return [];
}
}
},
onClick: function(e, legendItem) {
var index = legendItem.index;
var chart = this.chart;
var i, ilen, meta;
for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
meta = chart.getDatasetMeta(i);
meta.data[index].hidden = !meta.data[index].hidden;
}
chart.update();
}
},
// Need to override these to give a nice default
tooltips: {
callbacks: {
title: function() {
return '';
},
label: function(tooltipItem, data) {
return data.labels[tooltipItem.index] + ': ' + tooltipItem.yLabel;
}
}
}
};
Chart.controllers.polarArea = Chart.DatasetController.extend({
dataElementType: Chart.elements.Arc,
linkScales: helpers.noop,
update: function update(reset) {
var me = this;
var chart = me.chart;
var chartArea = chart.chartArea;
var meta = me.getMeta();
var opts = chart.options;
var arcOpts = opts.elements.arc;
var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
chart.outerRadius = Math.max((minSize - arcOpts.borderWidth / 2) / 2, 0);
chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
me.innerRadius = me.outerRadius - chart.radiusLength;
meta.count = me.countVisibleElements();
helpers.each(meta.data, function(arc, index) {
me.updateElement(arc, index, reset);
});
},
updateElement: function(arc, index, reset) {
var me = this;
var chart = me.chart;
var chartArea = chart.chartArea;
var dataset = me.getDataset();
var opts = chart.options;
var animationOpts = opts.animation;
var arcOpts = opts.elements.arc;
var custom = arc.custom || {};
var scale = chart.scale;
var getValueAtIndexOrDefault = helpers.getValueAtIndexOrDefault;
var labels = chart.data.labels;
var circumference = me.calculateCircumference(dataset.data[index]);
var centerX = (chartArea.left + chartArea.right) / 2;
var centerY = (chartArea.top + chartArea.bottom) / 2;
// If there is NaN data before us, we need to calculate the starting angle correctly.
// We could be way more efficient here, but its unlikely that the polar area chart will have a lot of data
var visibleCount = 0;
var meta = me.getMeta();
for (var i = 0; i < index; ++i) {
if (!isNaN(dataset.data[i]) && !meta.data[i].hidden) {
++visibleCount;
}
}
var negHalfPI = -0.5 * Math.PI;
var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
var startAngle = (negHalfPI) + (circumference * visibleCount);
var endAngle = startAngle + (arc.hidden ? 0 : circumference);
var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
helpers.extend(arc, {
// Utility
_datasetIndex: me.index,
_index: index,
_scale: scale,
// Desired view properties
_model: {
x: centerX,
y: centerY,
innerRadius: 0,
outerRadius: reset ? resetRadius : distance,
startAngle: reset && animationOpts.animateRotate ? negHalfPI : startAngle,
endAngle: reset && animationOpts.animateRotate ? negHalfPI : endAngle,
label: getValueAtIndexOrDefault(labels, index, labels[index])
}
});
// Apply border and fill style
me.removeHoverStyle(arc);
arc.pivot();
},
removeHoverStyle: function(arc) {
Chart.DatasetController.prototype.removeHoverStyle.call(this, arc, this.chart.options.elements.arc);
},
countVisibleElements: function() {
var dataset = this.getDataset();
var meta = this.getMeta();
var count = 0;
helpers.each(meta.data, function(element, index) {
if (!isNaN(dataset.data[index]) && !element.hidden) {
count++;
}
});
return count;
},
calculateCircumference: function(value) {
var count = this.getMeta().count;
if (count > 0 && !isNaN(value)) {
return (2 * Math.PI) / count;
} else {
return 0;
}
}
});
};
},{}],20:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
Chart.defaults.radar = {
scale: {
type: "radialLinear"
},
elements: {
line: {
tension: 0 // no bezier in radar
}
}
};
Chart.controllers.radar = Chart.DatasetController.extend({
datasetElementType: Chart.elements.Line,
dataElementType: Chart.elements.Point,
linkScales: helpers.noop,
addElementAndReset: function(index) {
Chart.DatasetController.prototype.addElementAndReset.call(this, index);
// Make sure bezier control points are updated
this.updateBezierControlPoints();
},
update: function update(reset) {
var me = this;
var meta = me.getMeta();
var line = meta.dataset;
var points = meta.data;
var custom = line.custom || {};
var dataset = me.getDataset();
var lineElementOptions = me.chart.options.elements.line;
var scale = me.chart.scale;
// Compatibility: If the properties are defined with only the old name, use those values
if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
dataset.lineTension = dataset.tension;
}
helpers.extend(meta.dataset, {
// Utility
_datasetIndex: me.index,
// Data
_children: points,
_loop: true,
// Model
_model: {
// Appearance
tension: custom.tension ? custom.tension : helpers.getValueOrDefault(dataset.lineTension, lineElementOptions.tension),
backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor),
borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth),
borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor),
fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill),
borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle),
borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash),
borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset),
borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle),
// Scale
scaleTop: scale.top,
scaleBottom: scale.bottom,
scaleZero: scale.getBasePosition()
}
});
meta.dataset.pivot();
// Update Points
helpers.each(points, function(point, index) {
me.updateElement(point, index, reset);
}, me);
// Update bezier control points
me.updateBezierControlPoints();
},
updateElement: function(point, index, reset) {
var me = this;
var custom = point.custom || {};
var dataset = me.getDataset();
var scale = me.chart.scale;
var pointElementOptions = me.chart.options.elements.point;
var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
helpers.extend(point, {
// Utility
_datasetIndex: me.index,
_index: index,
_scale: scale,
// Desired view properties
_model: {
x: reset ? scale.xCenter : pointPosition.x, // value not used in dataset scale, but we want a consistent API between scales
y: reset ? scale.yCenter : pointPosition.y,
// Appearance
tension: custom.tension ? custom.tension : helpers.getValueOrDefault(dataset.tension, me.chart.options.elements.line.tension),
radius: custom.radius ? custom.radius : helpers.getValueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius),
backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor),
borderColor: custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor),
borderWidth: custom.borderWidth ? custom.borderWidth : helpers.getValueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth),
pointStyle: custom.pointStyle ? custom.pointStyle : helpers.getValueAtIndexOrDefault(dataset.pointStyle, index, pointElementOptions.pointStyle),
// Tooltip
hitRadius: custom.hitRadius ? custom.hitRadius : helpers.getValueAtIndexOrDefault(dataset.hitRadius, index, pointElementOptions.hitRadius)
}
});
point._model.skip = custom.skip ? custom.skip : (isNaN(point._model.x) || isNaN(point._model.y));
},
updateBezierControlPoints: function() {
var chartArea = this.chart.chartArea;
var meta = this.getMeta();
helpers.each(meta.data, function(point, index) {
var model = point._model;
var controlPoints = helpers.splineCurve(
helpers.previousItem(meta.data, index, true)._model,
model,
helpers.nextItem(meta.data, index, true)._model,
model.tension
);
// Prevent the bezier going outside of the bounds of the graph
model.controlPointPreviousX = Math.max(Math.min(controlPoints.previous.x, chartArea.right), chartArea.left);
model.controlPointPreviousY = Math.max(Math.min(controlPoints.previous.y, chartArea.bottom), chartArea.top);
model.controlPointNextX = Math.max(Math.min(controlPoints.next.x, chartArea.right), chartArea.left);
model.controlPointNextY = Math.max(Math.min(controlPoints.next.y, chartArea.bottom), chartArea.top);
// Now pivot the point for animation
point.pivot();
});
},
draw: function(ease) {
var meta = this.getMeta();
var easingDecimal = ease || 1;
// Transition Point Locations
helpers.each(meta.data, function(point, index) {
point.transition(easingDecimal);
});
// Transition and Draw the line
meta.dataset.transition(easingDecimal).draw();
// Draw the points
helpers.each(meta.data, function(point) {
point.draw();
});
},
setHoverStyle: function(point) {
// Point
var dataset = this.chart.data.datasets[point._datasetIndex];
var custom = point.custom || {};
var index = point._index;
var model = point._model;
model.radius = custom.hoverRadius ? custom.hoverRadius : helpers.getValueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius);
model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.getValueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.getValueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor));
model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.getValueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth);
},
removeHoverStyle: function(point) {
var dataset = this.chart.data.datasets[point._datasetIndex];
var custom = point.custom || {};
var index = point._index;
var model = point._model;
var pointElementOptions = this.chart.options.elements.point;
model.radius = custom.radius ? custom.radius : helpers.getValueAtIndexOrDefault(dataset.radius, index, pointElementOptions.radius);
model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor);
model.borderColor = custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor);
model.borderWidth = custom.borderWidth ? custom.borderWidth : helpers.getValueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth);
}
});
};
},{}],21:[function(require,module,exports){
/*global window: false */
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
Chart.defaults.global.animation = {
duration: 1000,
easing: "easeOutQuart",
onProgress: helpers.noop,
onComplete: helpers.noop
};
Chart.Animation = Chart.Element.extend({
currentStep: null, // the current animation step
numSteps: 60, // default number of steps
easing: "", // the easing to use for this animation
render: null, // render function used by the animation service
onAnimationProgress: null, // user specified callback to fire on each step of the animation
onAnimationComplete: null // user specified callback to fire when the animation finishes
});
Chart.animationService = {
frameDuration: 17,
animations: [],
dropFrames: 0,
request: null,
addAnimation: function(chartInstance, animationObject, duration, lazy) {
var me = this;
if (!lazy) {
chartInstance.animating = true;
}
for (var index = 0; index < me.animations.length; ++index) {
if (me.animations[index].chartInstance === chartInstance) {
// replacing an in progress animation
me.animations[index].animationObject = animationObject;
return;
}
}
me.animations.push({
chartInstance: chartInstance,
animationObject: animationObject
});
// If there are no animations queued, manually kickstart a digest, for lack of a better word
if (me.animations.length === 1) {
me.requestAnimationFrame();
}
},
// Cancel the animation for a given chart instance
cancelAnimation: function(chartInstance) {
var index = helpers.findIndex(this.animations, function(animationWrapper) {
return animationWrapper.chartInstance === chartInstance;
});
if (index !== -1) {
this.animations.splice(index, 1);
chartInstance.animating = false;
}
},
requestAnimationFrame: function() {
var me = this;
if (me.request === null) {
// Skip animation frame requests until the active one is executed.
// This can happen when processing mouse events, e.g. 'mousemove'
// and 'mouseout' events will trigger multiple renders.
me.request = helpers.requestAnimFrame.call(window, function() {
me.request = null;
me.startDigest();
});
}
},
startDigest: function() {
var me = this;
var startTime = Date.now();
var framesToDrop = 0;
if (me.dropFrames > 1) {
framesToDrop = Math.floor(me.dropFrames);
me.dropFrames = me.dropFrames % 1;
}
var i = 0;
while (i < me.animations.length) {
if (me.animations[i].animationObject.currentStep === null) {
me.animations[i].animationObject.currentStep = 0;
}
me.animations[i].animationObject.currentStep += 1 + framesToDrop;
if (me.animations[i].animationObject.currentStep > me.animations[i].animationObject.numSteps) {
me.animations[i].animationObject.currentStep = me.animations[i].animationObject.numSteps;
}
me.animations[i].animationObject.render(me.animations[i].chartInstance, me.animations[i].animationObject);
if (me.animations[i].animationObject.onAnimationProgress && me.animations[i].animationObject.onAnimationProgress.call) {
me.animations[i].animationObject.onAnimationProgress.call(me.animations[i].chartInstance, me.animations[i]);
}
if (me.animations[i].animationObject.currentStep === me.animations[i].animationObject.numSteps) {
if (me.animations[i].animationObject.onAnimationComplete && me.animations[i].animationObject.onAnimationComplete.call) {
me.animations[i].animationObject.onAnimationComplete.call(me.animations[i].chartInstance, me.animations[i]);
}
// executed the last frame. Remove the animation.
me.animations[i].chartInstance.animating = false;
me.animations.splice(i, 1);
} else {
++i;
}
}
var endTime = Date.now();
var dropFrames = (endTime - startTime) / me.frameDuration;
me.dropFrames += dropFrames;
// Do we have more stuff to animate?
if (me.animations.length > 0) {
me.requestAnimationFrame();
}
}
};
};
},{}],22:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
//Create a dictionary of chart types, to allow for extension of existing types
Chart.types = {};
//Store a reference to each instance - allowing us to globally resize chart instances on window resize.
//Destroy method on the chart will remove the instance of the chart from this reference.
Chart.instances = {};
// Controllers available for dataset visualization eg. bar, line, slice, etc.
Chart.controllers = {};
/**
* @class Chart.Controller
* The main controller of a chart.
*/
Chart.Controller = function(instance) {
this.chart = instance;
this.config = instance.config;
this.options = this.config.options = helpers.configMerge(Chart.defaults.global, Chart.defaults[this.config.type], this.config.options || {});
this.id = helpers.uid();
Object.defineProperty(this, 'data', {
get: function() {
return this.config.data;
}
});
//Add the chart instance to the global namespace
Chart.instances[this.id] = this;
if (this.options.responsive) {
// Silent resize before chart draws
this.resize(true);
}
this.initialize();
return this;
};
helpers.extend(Chart.Controller.prototype, /** @lends Chart.Controller */ {
initialize: function initialize() {
var me = this;
// Before init plugin notification
Chart.plugins.notify('beforeInit', [me]);
me.bindEvents();
// Make sure controllers are built first so that each dataset is bound to an axis before the scales
// are built
me.ensureScalesHaveIDs();
me.buildOrUpdateControllers();
me.buildScales();
me.updateLayout();
me.resetElements();
me.initToolTip();
me.update();
// After init plugin notification
Chart.plugins.notify('afterInit', [me]);
return me;
},
clear: function clear() {
helpers.clear(this.chart);
return this;
},
stop: function stop() {
// Stops any current animation loop occuring
Chart.animationService.cancelAnimation(this);
return this;
},
resize: function resize(silent) {
var me = this;
var chart = me.chart;
var canvas = chart.canvas;
var newWidth = helpers.getMaximumWidth(canvas);
var aspectRatio = chart.aspectRatio;
var newHeight = (me.options.maintainAspectRatio && isNaN(aspectRatio) === false && isFinite(aspectRatio) && aspectRatio !== 0) ? newWidth / aspectRatio : helpers.getMaximumHeight(canvas);
var sizeChanged = chart.width !== newWidth || chart.height !== newHeight;
if (!sizeChanged) {
return me;
}
canvas.width = chart.width = newWidth;
canvas.height = chart.height = newHeight;
helpers.retinaScale(chart);
// Notify any plugins about the resize
var newSize = { width: newWidth, height: newHeight };
Chart.plugins.notify('resize', [me, newSize]);
// Notify of resize
if (me.options.onResize) {
me.options.onResize(me, newSize);
}
if (!silent) {
me.stop();
me.update(me.options.responsiveAnimationDuration);
}
return me;
},
ensureScalesHaveIDs: function ensureScalesHaveIDs() {
var options = this.options;
var scalesOptions = options.scales || {};
var scaleOptions = options.scale;
helpers.each(scalesOptions.xAxes, function(xAxisOptions, index) {
xAxisOptions.id = xAxisOptions.id || ('x-axis-' + index);
});
helpers.each(scalesOptions.yAxes, function(yAxisOptions, index) {
yAxisOptions.id = yAxisOptions.id || ('y-axis-' + index);
});
if (scaleOptions) {
scaleOptions.id = scaleOptions.id || 'scale';
}
},
/**
* Builds a map of scale ID to scale object for future lookup.
*/
buildScales: function buildScales() {
var me = this;
var options = me.options;
var scales = me.scales = {};
var items = [];
if (options.scales) {
items = items.concat(
(options.scales.xAxes || []).map(function(xAxisOptions) {
return { options: xAxisOptions, dtype: 'category' }; }),
(options.scales.yAxes || []).map(function(yAxisOptions) {
return { options: yAxisOptions, dtype: 'linear' }; }));
}
if (options.scale) {
items.push({ options: options.scale, dtype: 'radialLinear', isDefault: true });
}
helpers.each(items, function(item, index) {
var scaleOptions = item.options;
var scaleType = helpers.getValueOrDefault(scaleOptions.type, item.dtype);
var scaleClass = Chart.scaleService.getScaleConstructor(scaleType);
if (!scaleClass) {
return;
}
var scale = new scaleClass({
id: scaleOptions.id,
options: scaleOptions,
ctx: me.chart.ctx,
chart: me
});
scales[scale.id] = scale;
// TODO(SB): I think we should be able to remove this custom case (options.scale)
// and consider it as a regular scale part of the "scales"" map only! This would
// make the logic easier and remove some useless? custom code.
if (item.isDefault) {
me.scale = scale;
}
});
Chart.scaleService.addScalesToLayout(this);
},
updateLayout: function() {
Chart.layoutService.update(this, this.chart.width, this.chart.height);
},
buildOrUpdateControllers: function buildOrUpdateControllers() {
var me = this;
var types = [];
var newControllers = [];
helpers.each(me.data.datasets, function(dataset, datasetIndex) {
var meta = me.getDatasetMeta(datasetIndex);
if (!meta.type) {
meta.type = dataset.type || me.config.type;
}
types.push(meta.type);
if (meta.controller) {
meta.controller.updateIndex(datasetIndex);
} else {
meta.controller = new Chart.controllers[meta.type](me, datasetIndex);
newControllers.push(meta.controller);
}
}, me);
if (types.length > 1) {
for (var i = 1; i < types.length; i++) {
if (types[i] !== types[i - 1]) {
me.isCombo = true;
break;
}
}
}
return newControllers;
},
resetElements: function resetElements() {
var me = this;
helpers.each(me.data.datasets, function(dataset, datasetIndex) {
me.getDatasetMeta(datasetIndex).controller.reset();
}, me);
},
update: function update(animationDuration, lazy) {
var me = this;
Chart.plugins.notify('beforeUpdate', [me]);
// In case the entire data object changed
me.tooltip._data = me.data;
// Make sure dataset controllers are updated and new controllers are reset
var newControllers = me.buildOrUpdateControllers();
// Make sure all dataset controllers have correct meta data counts
helpers.each(me.data.datasets, function(dataset, datasetIndex) {
me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements();
}, me);
Chart.layoutService.update(me, me.chart.width, me.chart.height);
// Apply changes to the dataets that require the scales to have been calculated i.e BorderColor chages
Chart.plugins.notify('afterScaleUpdate', [me]);
// Can only reset the new controllers after the scales have been updated
helpers.each(newControllers, function(controller) {
controller.reset();
});
me.updateDatasets();
// Do this before render so that any plugins that need final scale updates can use it
Chart.plugins.notify('afterUpdate', [me]);
me.render(animationDuration, lazy);
},
/**
* @method beforeDatasetsUpdate
* @description Called before all datasets are updated. If a plugin returns false,
* the datasets update will be cancelled until another chart update is triggered.
* @param {Object} instance the chart instance being updated.
* @returns {Boolean} false to cancel the datasets update.
* @memberof Chart.PluginBase
* @since version 2.1.5
* @instance
*/
/**
* @method afterDatasetsUpdate
* @description Called after all datasets have been updated. Note that this
* extension will not be called if the datasets update has been cancelled.
* @param {Object} instance the chart instance being updated.
* @memberof Chart.PluginBase
* @since version 2.1.5
* @instance
*/
/**
* Updates all datasets unless a plugin returns false to the beforeDatasetsUpdate
* extension, in which case no datasets will be updated and the afterDatasetsUpdate
* notification will be skipped.
* @protected
* @instance
*/
updateDatasets: function() {
var me = this;
var i, ilen;
if (Chart.plugins.notify('beforeDatasetsUpdate', [ me ])) {
for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
me.getDatasetMeta(i).controller.update();
}
Chart.plugins.notify('afterDatasetsUpdate', [ me ]);
}
},
render: function render(duration, lazy) {
var me = this;
Chart.plugins.notify('beforeRender', [me]);
var animationOptions = me.options.animation;
if (animationOptions && ((typeof duration !== 'undefined' && duration !== 0) || (typeof duration === 'undefined' && animationOptions.duration !== 0))) {
var animation = new Chart.Animation();
animation.numSteps = (duration || animationOptions.duration) / 16.66; //60 fps
animation.easing = animationOptions.easing;
// render function
animation.render = function(chartInstance, animationObject) {
var easingFunction = helpers.easingEffects[animationObject.easing];
var stepDecimal = animationObject.currentStep / animationObject.numSteps;
var easeDecimal = easingFunction(stepDecimal);
chartInstance.draw(easeDecimal, stepDecimal, animationObject.currentStep);
};
// user events
animation.onAnimationProgress = animationOptions.onProgress;
animation.onAnimationComplete = animationOptions.onComplete;
Chart.animationService.addAnimation(me, animation, duration, lazy);
} else {
me.draw();
if (animationOptions && animationOptions.onComplete && animationOptions.onComplete.call) {
animationOptions.onComplete.call(me);
}
}
return me;
},
draw: function(ease) {
var me = this;
var easingDecimal = ease || 1;
me.clear();
Chart.plugins.notify('beforeDraw', [me, easingDecimal]);
// Draw all the scales
helpers.each(me.boxes, function(box) {
box.draw(me.chartArea);
}, me);
if (me.scale) {
me.scale.draw();
}
Chart.plugins.notify('beforeDatasetsDraw', [me, easingDecimal]);
// Draw each dataset via its respective controller (reversed to support proper line stacking)
helpers.each(me.data.datasets, function(dataset, datasetIndex) {
if (me.isDatasetVisible(datasetIndex)) {
me.getDatasetMeta(datasetIndex).controller.draw(ease);
}
}, me, true);
Chart.plugins.notify('afterDatasetsDraw', [me, easingDecimal]);
// Finally draw the tooltip
me.tooltip.transition(easingDecimal).draw();
Chart.plugins.notify('afterDraw', [me, easingDecimal]);
},
// Get the single element that was clicked on
// @return : An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
getElementAtEvent: function(e) {
var me = this;
var eventPosition = helpers.getRelativePosition(e, me.chart);
var elementsArray = [];
helpers.each(me.data.datasets, function(dataset, datasetIndex) {
if (me.isDatasetVisible(datasetIndex)) {
var meta = me.getDatasetMeta(datasetIndex);
helpers.each(meta.data, function(element, index) {
if (element.inRange(eventPosition.x, eventPosition.y)) {
elementsArray.push(element);
return elementsArray;
}
});
}
});
return elementsArray;
},
getElementsAtEvent: function(e) {
var me = this;
var eventPosition = helpers.getRelativePosition(e, me.chart);
var elementsArray = [];
var found = (function() {
if (me.data.datasets) {
for (var i = 0; i < me.data.datasets.length; i++) {
var meta = me.getDatasetMeta(i);
if (me.isDatasetVisible(i)) {
for (var j = 0; j < meta.data.length; j++) {
if (meta.data[j].inRange(eventPosition.x, eventPosition.y)) {
return meta.data[j];
}
}
}
}
}
}).call(me);
if (!found) {
return elementsArray;
}
helpers.each(me.data.datasets, function(dataset, datasetIndex) {
if (me.isDatasetVisible(datasetIndex)) {
var meta = me.getDatasetMeta(datasetIndex);
elementsArray.push(meta.data[found._index]);
}
}, me);
return elementsArray;
},
getElementsAtEventForMode: function(e, mode) {
var me = this;
switch (mode) {
case 'single':
return me.getElementAtEvent(e);
case 'label':
return me.getElementsAtEvent(e);
case 'dataset':
return me.getDatasetAtEvent(e);
default:
return e;
}
},
getDatasetAtEvent: function(e) {
var elementsArray = this.getElementAtEvent(e);
if (elementsArray.length > 0) {
elementsArray = this.getDatasetMeta(elementsArray[0]._datasetIndex).data;
}
return elementsArray;
},
getDatasetMeta: function(datasetIndex) {
var me = this;
var dataset = me.data.datasets[datasetIndex];
if (!dataset._meta) {
dataset._meta = {};
}
var meta = dataset._meta[me.id];
if (!meta) {
meta = dataset._meta[me.id] = {
type: null,
data: [],
dataset: null,
controller: null,
hidden: null, // See isDatasetVisible() comment
xAxisID: null,
yAxisID: null
};
}
return meta;
},
getVisibleDatasetCount: function() {
var count = 0;
for (var i = 0, ilen = this.data.datasets.length; i<ilen; ++i) {
if (this.isDatasetVisible(i)) {
count++;
}
}
return count;
},
isDatasetVisible: function(datasetIndex) {
var meta = this.getDatasetMeta(datasetIndex);
// meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
// the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
return typeof meta.hidden === 'boolean'? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
},
generateLegend: function generateLegend() {
return this.options.legendCallback(this);
},
destroy: function destroy() {
var me = this;
me.stop();
me.clear();
helpers.unbindEvents(me, me.events);
helpers.removeResizeListener(me.chart.canvas.parentNode);
// Reset canvas height/width attributes
var canvas = me.chart.canvas;
canvas.width = me.chart.width;
canvas.height = me.chart.height;
// if we scaled the canvas in response to a devicePixelRatio !== 1, we need to undo that transform here
if (me.chart.originalDevicePixelRatio !== undefined) {
me.chart.ctx.scale(1 / me.chart.originalDevicePixelRatio, 1 / me.chart.originalDevicePixelRatio);
}
// Reset to the old style since it may have been changed by the device pixel ratio changes
canvas.style.width = me.chart.originalCanvasStyleWidth;
canvas.style.height = me.chart.originalCanvasStyleHeight;
Chart.plugins.notify('destroy', [me]);
delete Chart.instances[me.id];
},
toBase64Image: function toBase64Image() {
return this.chart.canvas.toDataURL.apply(this.chart.canvas, arguments);
},
initToolTip: function initToolTip() {
var me = this;
me.tooltip = new Chart.Tooltip({
_chart: me.chart,
_chartInstance: me,
_data: me.data,
_options: me.options.tooltips
}, me);
},
bindEvents: function bindEvents() {
var me = this;
helpers.bindEvents(me, me.options.events, function(evt) {
me.eventHandler(evt);
});
},
updateHoverStyle: function(elements, mode, enabled) {
var method = enabled? 'setHoverStyle' : 'removeHoverStyle';
var element, i, ilen;
switch (mode) {
case 'single':
elements = [ elements[0] ];
break;
case 'label':
case 'dataset':
// elements = elements;
break;
default:
// unsupported mode
return;
}
for (i=0, ilen=elements.length; i<ilen; ++i) {
element = elements[i];
if (element) {
this.getDatasetMeta(element._datasetIndex).controller[method](element);
}
}
},
eventHandler: function eventHandler(e) {
var me = this;
var tooltip = me.tooltip;
var options = me.options || {};
var hoverOptions = options.hover;
var tooltipsOptions = options.tooltips;
me.lastActive = me.lastActive || [];
me.lastTooltipActive = me.lastTooltipActive || [];
// Find Active Elements for hover and tooltips
if (e.type === 'mouseout') {
me.active = [];
me.tooltipActive = [];
} else {
me.active = me.getElementsAtEventForMode(e, hoverOptions.mode);
me.tooltipActive = me.getElementsAtEventForMode(e, tooltipsOptions.mode);
}
// On Hover hook
if (hoverOptions.onHover) {
hoverOptions.onHover.call(me, me.active);
}
if (e.type === 'mouseup' || e.type === 'click') {
if (options.onClick) {
options.onClick.call(me, e, me.active);
}
if (me.legend && me.legend.handleEvent) {
me.legend.handleEvent(e);
}
}
// Remove styling for last active (even if it may still be active)
if (me.lastActive.length) {
me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
}
// Built in hover styling
if (me.active.length && hoverOptions.mode) {
me.updateHoverStyle(me.active, hoverOptions.mode, true);
}
// Built in Tooltips
if (tooltipsOptions.enabled || tooltipsOptions.custom) {
tooltip.initialize();
tooltip._active = me.tooltipActive;
tooltip.update(true);
}
// Hover animations
tooltip.pivot();
if (!me.animating) {
// If entering, leaving, or changing elements, animate the change via pivot
if (!helpers.arrayEquals(me.active, me.lastActive) ||
!helpers.arrayEquals(me.tooltipActive, me.lastTooltipActive)) {
me.stop();
if (tooltipsOptions.enabled || tooltipsOptions.custom) {
tooltip.update(true);
}
// We only need to render at this point. Updating will cause scales to be
// recomputed generating flicker & using more memory than necessary.
me.render(hoverOptions.animationDuration, true);
}
}
// Remember Last Actives
me.lastActive = me.active;
me.lastTooltipActive = me.tooltipActive;
return me;
}
});
};
},{}],23:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
var noop = helpers.noop;
// Base class for all dataset controllers (line, bar, etc)
Chart.DatasetController = function(chart, datasetIndex) {
this.initialize.call(this, chart, datasetIndex);
};
helpers.extend(Chart.DatasetController.prototype, {
/**
* Element type used to generate a meta dataset (e.g. Chart.element.Line).
* @type {Chart.core.element}
*/
datasetElementType: null,
/**
* Element type used to generate a meta data (e.g. Chart.element.Point).
* @type {Chart.core.element}
*/
dataElementType: null,
initialize: function(chart, datasetIndex) {
var me = this;
me.chart = chart;
me.index = datasetIndex;
me.linkScales();
me.addElements();
},
updateIndex: function(datasetIndex) {
this.index = datasetIndex;
},
linkScales: function() {
var me = this;
var meta = me.getMeta();
var dataset = me.getDataset();
if (meta.xAxisID === null) {
meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id;
}
if (meta.yAxisID === null) {
meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id;
}
},
getDataset: function() {
return this.chart.data.datasets[this.index];
},
getMeta: function() {
return this.chart.getDatasetMeta(this.index);
},
getScaleForId: function(scaleID) {
return this.chart.scales[scaleID];
},
reset: function() {
this.update(true);
},
createMetaDataset: function() {
var me = this;
var type = me.datasetElementType;
return type && new type({
_chart: me.chart.chart,
_datasetIndex: me.index
});
},
createMetaData: function(index) {
var me = this;
var type = me.dataElementType;
return type && new type({
_chart: me.chart.chart,
_datasetIndex: me.index,
_index: index
});
},
addElements: function() {
var me = this;
var meta = me.getMeta();
var data = me.getDataset().data || [];
var metaData = meta.data;
var i, ilen;
for (i=0, ilen=data.length; i<ilen; ++i) {
metaData[i] = metaData[i] || me.createMetaData(meta, i);
}
meta.dataset = meta.dataset || me.createMetaDataset();
},
addElementAndReset: function(index) {
var me = this;
var element = me.createMetaData(index);
me.getMeta().data.splice(index, 0, element);
me.updateElement(element, index, true);
},
buildOrUpdateElements: function buildOrUpdateElements() {
// Handle the number of data points changing
var meta = this.getMeta(),
md = meta.data,
numData = this.getDataset().data.length,
numMetaData = md.length;
// Make sure that we handle number of datapoints changing
if (numData < numMetaData) {
// Remove excess bars for data points that have been removed
md.splice(numData, numMetaData - numData);
} else if (numData > numMetaData) {
// Add new elements
for (var index = numMetaData; index < numData; ++index) {
this.addElementAndReset(index);
}
}
},
update: noop,
draw: function(ease) {
var easingDecimal = ease || 1;
helpers.each(this.getMeta().data, function(element, index) {
element.transition(easingDecimal).draw();
});
},
removeHoverStyle: function(element, elementOpts) {
var dataset = this.chart.data.datasets[element._datasetIndex],
index = element._index,
custom = element.custom || {},
valueOrDefault = helpers.getValueAtIndexOrDefault,
color = helpers.color,
model = element._model;
model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : valueOrDefault(dataset.backgroundColor, index, elementOpts.backgroundColor);
model.borderColor = custom.borderColor ? custom.borderColor : valueOrDefault(dataset.borderColor, index, elementOpts.borderColor);
model.borderWidth = custom.borderWidth ? custom.borderWidth : valueOrDefault(dataset.borderWidth, index, elementOpts.borderWidth);
},
setHoverStyle: function(element) {
var dataset = this.chart.data.datasets[element._datasetIndex],
index = element._index,
custom = element.custom || {},
valueOrDefault = helpers.getValueAtIndexOrDefault,
color = helpers.color,
getHoverColor = helpers.getHoverColor,
model = element._model;
model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : valueOrDefault(dataset.hoverBackgroundColor, index, getHoverColor(model.backgroundColor));
model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : valueOrDefault(dataset.hoverBorderColor, index, getHoverColor(model.borderColor));
model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : valueOrDefault(dataset.hoverBorderWidth, index, model.borderWidth);
}
});
Chart.DatasetController.extend = helpers.inherits;
};
},{}],24:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
Chart.elements = {};
Chart.Element = function(configuration) {
helpers.extend(this, configuration);
this.initialize.apply(this, arguments);
};
helpers.extend(Chart.Element.prototype, {
initialize: function() {
this.hidden = false;
},
pivot: function() {
var me = this;
if (!me._view) {
me._view = helpers.clone(me._model);
}
me._start = helpers.clone(me._view);
return me;
},
transition: function(ease) {
var me = this;
if (!me._view) {
me._view = helpers.clone(me._model);
}
// No animation -> No Transition
if (ease === 1) {
me._view = me._model;
me._start = null;
return me;
}
if (!me._start) {
me.pivot();
}
helpers.each(me._model, function(value, key) {
if (key[0] === '_') {
// Only non-underscored properties
}
// Init if doesn't exist
else if (!me._view.hasOwnProperty(key)) {
if (typeof value === 'number' && !isNaN(me._view[key])) {
me._view[key] = value * ease;
} else {
me._view[key] = value;
}
}
// No unnecessary computations
else if (value === me._view[key]) {
// It's the same! Woohoo!
}
// Color transitions if possible
else if (typeof value === 'string') {
try {
var color = helpers.color(me._model[key]).mix(helpers.color(me._start[key]), ease);
me._view[key] = color.rgbString();
} catch (err) {
me._view[key] = value;
}
}
// Number transitions
else if (typeof value === 'number') {
var startVal = me._start[key] !== undefined && isNaN(me._start[key]) === false ? me._start[key] : 0;
me._view[key] = ((me._model[key] - startVal) * ease) + startVal;
}
// Everything else
else {
me._view[key] = value;
}
}, me);
return me;
},
tooltipPosition: function() {
return {
x: this._model.x,
y: this._model.y
};
},
hasValue: function() {
return helpers.isNumber(this._model.x) && helpers.isNumber(this._model.y);
}
});
Chart.Element.extend = helpers.inherits;
};
},{}],25:[function(require,module,exports){
/*global window: false */
/*global document: false */
"use strict";
var color = require(3);
module.exports = function(Chart) {
//Global Chart helpers object for utility methods and classes
var helpers = Chart.helpers = {};
//-- Basic js utility methods
helpers.each = function(loopable, callback, self, reverse) {
// Check to see if null or undefined firstly.
var i, len;
if (helpers.isArray(loopable)) {
len = loopable.length;
if (reverse) {
for (i = len - 1; i >= 0; i--) {
callback.call(self, loopable[i], i);
}
} else {
for (i = 0; i < len; i++) {
callback.call(self, loopable[i], i);
}
}
} else if (typeof loopable === 'object') {
var keys = Object.keys(loopable);
len = keys.length;
for (i = 0; i < len; i++) {
callback.call(self, loopable[keys[i]], keys[i]);
}
}
};
helpers.clone = function(obj) {
var objClone = {};
helpers.each(obj, function(value, key) {
if (helpers.isArray(value)) {
objClone[key] = value.slice(0);
} else if (typeof value === 'object' && value !== null) {
objClone[key] = helpers.clone(value);
} else {
objClone[key] = value;
}
});
return objClone;
};
helpers.extend = function(base) {
var setFn = function(value, key) { base[key] = value; };
for (var i = 1, ilen = arguments.length; i < ilen; i++) {
helpers.each(arguments[i], setFn);
}
return base;
};
// Need a special merge function to chart configs since they are now grouped
helpers.configMerge = function(_base) {
var base = helpers.clone(_base);
helpers.each(Array.prototype.slice.call(arguments, 1), function(extension) {
helpers.each(extension, function(value, key) {
if (key === 'scales') {
// Scale config merging is complex. Add out own function here for that
base[key] = helpers.scaleMerge(base.hasOwnProperty(key) ? base[key] : {}, value);
} else if (key === 'scale') {
// Used in polar area & radar charts since there is only one scale
base[key] = helpers.configMerge(base.hasOwnProperty(key) ? base[key] : {}, Chart.scaleService.getScaleDefaults(value.type), value);
} else if (base.hasOwnProperty(key) && helpers.isArray(base[key]) && helpers.isArray(value)) {
// In this case we have an array of objects replacing another array. Rather than doing a strict replace,
// merge. This allows easy scale option merging
var baseArray = base[key];
helpers.each(value, function(valueObj, index) {
if (index < baseArray.length) {
if (typeof baseArray[index] === 'object' && baseArray[index] !== null && typeof valueObj === 'object' && valueObj !== null) {
// Two objects are coming together. Do a merge of them.
baseArray[index] = helpers.configMerge(baseArray[index], valueObj);
} else {
// Just overwrite in this case since there is nothing to merge
baseArray[index] = valueObj;
}
} else {
baseArray.push(valueObj); // nothing to merge
}
});
} else if (base.hasOwnProperty(key) && typeof base[key] === "object" && base[key] !== null && typeof value === "object") {
// If we are overwriting an object with an object, do a merge of the properties.
base[key] = helpers.configMerge(base[key], value);
} else {
// can just overwrite the value in this case
base[key] = value;
}
});
});
return base;
};
helpers.scaleMerge = function(_base, extension) {
var base = helpers.clone(_base);
helpers.each(extension, function(value, key) {
if (key === 'xAxes' || key === 'yAxes') {
// These properties are arrays of items
if (base.hasOwnProperty(key)) {
helpers.each(value, function(valueObj, index) {
var axisType = helpers.getValueOrDefault(valueObj.type, key === 'xAxes' ? 'category' : 'linear');
var axisDefaults = Chart.scaleService.getScaleDefaults(axisType);
if (index >= base[key].length || !base[key][index].type) {
base[key].push(helpers.configMerge(axisDefaults, valueObj));
} else if (valueObj.type && valueObj.type !== base[key][index].type) {
// Type changed. Bring in the new defaults before we bring in valueObj so that valueObj can override the correct scale defaults
base[key][index] = helpers.configMerge(base[key][index], axisDefaults, valueObj);
} else {
// Type is the same
base[key][index] = helpers.configMerge(base[key][index], valueObj);
}
});
} else {
base[key] = [];
helpers.each(value, function(valueObj) {
var axisType = helpers.getValueOrDefault(valueObj.type, key === 'xAxes' ? 'category' : 'linear');
base[key].push(helpers.configMerge(Chart.scaleService.getScaleDefaults(axisType), valueObj));
});
}
} else if (base.hasOwnProperty(key) && typeof base[key] === "object" && base[key] !== null && typeof value === "object") {
// If we are overwriting an object with an object, do a merge of the properties.
base[key] = helpers.configMerge(base[key], value);
} else {
// can just overwrite the value in this case
base[key] = value;
}
});
return base;
};
helpers.getValueAtIndexOrDefault = function(value, index, defaultValue) {
if (value === undefined || value === null) {
return defaultValue;
}
if (helpers.isArray(value)) {
return index < value.length ? value[index] : defaultValue;
}
return value;
};
helpers.getValueOrDefault = function(value, defaultValue) {
return value === undefined ? defaultValue : value;
};
helpers.indexOf = Array.prototype.indexOf?
function(array, item) { return array.indexOf(item); } :
function(array, item) {
for (var i = 0, ilen = array.length; i < ilen; ++i) {
if (array[i] === item) {
return i;
}
}
return -1;
};
helpers.where = function(collection, filterCallback) {
if (helpers.isArray(collection) && Array.prototype.filter) {
return collection.filter(filterCallback);
} else {
var filtered = [];
helpers.each(collection, function(item) {
if (filterCallback(item)) {
filtered.push(item);
}
});
return filtered;
}
};
helpers.findIndex = Array.prototype.findIndex?
function(array, callback, scope) { return array.findIndex(callback, scope); } :
function(array, callback, scope) {
scope = scope === undefined? array : scope;
for (var i = 0, ilen = array.length; i < ilen; ++i) {
if (callback.call(scope, array[i], i, array)) {
return i;
}
}
return -1;
};
helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
// Default to start of the array
if (startIndex === undefined || startIndex === null) {
startIndex = -1;
}
for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
var currentItem = arrayToSearch[i];
if (filterCallback(currentItem)) {
return currentItem;
}
}
};
helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
// Default to end of the array
if (startIndex === undefined || startIndex === null) {
startIndex = arrayToSearch.length;
}
for (var i = startIndex - 1; i >= 0; i--) {
var currentItem = arrayToSearch[i];
if (filterCallback(currentItem)) {
return currentItem;
}
}
};
helpers.inherits = function(extensions) {
//Basic javascript inheritance based on the model created in Backbone.js
var parent = this;
var ChartElement = (extensions && extensions.hasOwnProperty("constructor")) ? extensions.constructor : function() {
return parent.apply(this, arguments);
};
var Surrogate = function() {
this.constructor = ChartElement;
};
Surrogate.prototype = parent.prototype;
ChartElement.prototype = new Surrogate();
ChartElement.extend = helpers.inherits;
if (extensions) {
helpers.extend(ChartElement.prototype, extensions);
}
ChartElement.__super__ = parent.prototype;
return ChartElement;
};
helpers.noop = function() {};
helpers.uid = (function() {
var id = 0;
return function() {
return id++;
};
})();
//-- Math methods
helpers.isNumber = function(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
helpers.almostEquals = function(x, y, epsilon) {
return Math.abs(x - y) < epsilon;
};
helpers.max = function(array) {
return array.reduce(function(max, value) {
if (!isNaN(value)) {
return Math.max(max, value);
} else {
return max;
}
}, Number.NEGATIVE_INFINITY);
};
helpers.min = function(array) {
return array.reduce(function(min, value) {
if (!isNaN(value)) {
return Math.min(min, value);
} else {
return min;
}
}, Number.POSITIVE_INFINITY);
};
helpers.sign = Math.sign?
function(x) { return Math.sign(x); } :
function(x) {
x = +x; // convert to a number
if (x === 0 || isNaN(x)) {
return x;
}
return x > 0 ? 1 : -1;
};
helpers.log10 = Math.log10?
function(x) { return Math.log10(x); } :
function(x) {
return Math.log(x) / Math.LN10;
};
helpers.toRadians = function(degrees) {
return degrees * (Math.PI / 180);
};
helpers.toDegrees = function(radians) {
return radians * (180 / Math.PI);
};
// Gets the angle from vertical upright to the point about a centre.
helpers.getAngleFromPoint = function(centrePoint, anglePoint) {
var distanceFromXCenter = anglePoint.x - centrePoint.x,
distanceFromYCenter = anglePoint.y - centrePoint.y,
radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
if (angle < (-0.5 * Math.PI)) {
angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
}
return {
angle: angle,
distance: radialDistanceFromCenter
};
};
helpers.aliasPixel = function(pixelWidth) {
return (pixelWidth % 2 === 0) ? 0 : 0.5;
};
helpers.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
//Props to Rob Spencer at scaled innovation for his post on splining between points
//http://scaledinnovation.com/analytics/splines/aboutSplines.html
// This function must also respect "skipped" points
var previous = firstPoint.skip ? middlePoint : firstPoint,
current = middlePoint,
next = afterPoint.skip ? middlePoint : afterPoint;
var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
var s01 = d01 / (d01 + d12);
var s12 = d12 / (d01 + d12);
// If all points are the same, s01 & s02 will be inf
s01 = isNaN(s01) ? 0 : s01;
s12 = isNaN(s12) ? 0 : s12;
var fa = t * s01; // scaling factor for triangle Ta
var fb = t * s12;
return {
previous: {
x: current.x - fa * (next.x - previous.x),
y: current.y - fa * (next.y - previous.y)
},
next: {
x: current.x + fb * (next.x - previous.x),
y: current.y + fb * (next.y - previous.y)
}
};
};
helpers.nextItem = function(collection, index, loop) {
if (loop) {
return index >= collection.length - 1 ? collection[0] : collection[index + 1];
}
return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
};
helpers.previousItem = function(collection, index, loop) {
if (loop) {
return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
}
return index <= 0 ? collection[0] : collection[index - 1];
};
// Implementation of the nice number algorithm used in determining where axis labels will go
helpers.niceNum = function(range, round) {
var exponent = Math.floor(helpers.log10(range));
var fraction = range / Math.pow(10, exponent);
var niceFraction;
if (round) {
if (fraction < 1.5) {
niceFraction = 1;
} else if (fraction < 3) {
niceFraction = 2;
} else if (fraction < 7) {
niceFraction = 5;
} else {
niceFraction = 10;
}
} else {
if (fraction <= 1.0) {
niceFraction = 1;
} else if (fraction <= 2) {
niceFraction = 2;
} else if (fraction <= 5) {
niceFraction = 5;
} else {
niceFraction = 10;
}
}
return niceFraction * Math.pow(10, exponent);
};
//Easing functions adapted from Robert Penner's easing equations
//http://www.robertpenner.com/easing/
var easingEffects = helpers.easingEffects = {
linear: function(t) {
return t;
},
easeInQuad: function(t) {
return t * t;
},
easeOutQuad: function(t) {
return -1 * t * (t - 2);
},
easeInOutQuad: function(t) {
if ((t /= 1 / 2) < 1) {
return 1 / 2 * t * t;
}
return -1 / 2 * ((--t) * (t - 2) - 1);
},
easeInCubic: function(t) {
return t * t * t;
},
easeOutCubic: function(t) {
return 1 * ((t = t / 1 - 1) * t * t + 1);
},
easeInOutCubic: function(t) {
if ((t /= 1 / 2) < 1) {
return 1 / 2 * t * t * t;
}
return 1 / 2 * ((t -= 2) * t * t + 2);
},
easeInQuart: function(t) {
return t * t * t * t;
},
easeOutQuart: function(t) {
return -1 * ((t = t / 1 - 1) * t * t * t - 1);
},
easeInOutQuart: function(t) {
if ((t /= 1 / 2) < 1) {
return 1 / 2 * t * t * t * t;
}
return -1 / 2 * ((t -= 2) * t * t * t - 2);
},
easeInQuint: function(t) {
return 1 * (t /= 1) * t * t * t * t;
},
easeOutQuint: function(t) {
return 1 * ((t = t / 1 - 1) * t * t * t * t + 1);
},
easeInOutQuint: function(t) {
if ((t /= 1 / 2) < 1) {
return 1 / 2 * t * t * t * t * t;
}
return 1 / 2 * ((t -= 2) * t * t * t * t + 2);
},
easeInSine: function(t) {
return -1 * Math.cos(t / 1 * (Math.PI / 2)) + 1;
},
easeOutSine: function(t) {
return 1 * Math.sin(t / 1 * (Math.PI / 2));
},
easeInOutSine: function(t) {
return -1 / 2 * (Math.cos(Math.PI * t / 1) - 1);
},
easeInExpo: function(t) {
return (t === 0) ? 1 : 1 * Math.pow(2, 10 * (t / 1 - 1));
},
easeOutExpo: function(t) {
return (t === 1) ? 1 : 1 * (-Math.pow(2, -10 * t / 1) + 1);
},
easeInOutExpo: function(t) {
if (t === 0) {
return 0;
}
if (t === 1) {
return 1;
}
if ((t /= 1 / 2) < 1) {
return 1 / 2 * Math.pow(2, 10 * (t - 1));
}
return 1 / 2 * (-Math.pow(2, -10 * --t) + 2);
},
easeInCirc: function(t) {
if (t >= 1) {
return t;
}
return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1);
},
easeOutCirc: function(t) {
return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t);
},
easeInOutCirc: function(t) {
if ((t /= 1 / 2) < 1) {
return -1 / 2 * (Math.sqrt(1 - t * t) - 1);
}
return 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1);
},
easeInElastic: function(t) {
var s = 1.70158;
var p = 0;
var a = 1;
if (t === 0) {
return 0;
}
if ((t /= 1) === 1) {
return 1;
}
if (!p) {
p = 1 * 0.3;
}
if (a < Math.abs(1)) {
a = 1;
s = p / 4;
} else {
s = p / (2 * Math.PI) * Math.asin(1 / a);
}
return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
},
easeOutElastic: function(t) {
var s = 1.70158;
var p = 0;
var a = 1;
if (t === 0) {
return 0;
}
if ((t /= 1) === 1) {
return 1;
}
if (!p) {
p = 1 * 0.3;
}
if (a < Math.abs(1)) {
a = 1;
s = p / 4;
} else {
s = p / (2 * Math.PI) * Math.asin(1 / a);
}
return a * Math.pow(2, -10 * t) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) + 1;
},
easeInOutElastic: function(t) {
var s = 1.70158;
var p = 0;
var a = 1;
if (t === 0) {
return 0;
}
if ((t /= 1 / 2) === 2) {
return 1;
}
if (!p) {
p = 1 * (0.3 * 1.5);
}
if (a < Math.abs(1)) {
a = 1;
s = p / 4;
} else {
s = p / (2 * Math.PI) * Math.asin(1 / a);
}
if (t < 1) {
return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
}
return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) * 0.5 + 1;
},
easeInBack: function(t) {
var s = 1.70158;
return 1 * (t /= 1) * t * ((s + 1) * t - s);
},
easeOutBack: function(t) {
var s = 1.70158;
return 1 * ((t = t / 1 - 1) * t * ((s + 1) * t + s) + 1);
},
easeInOutBack: function(t) {
var s = 1.70158;
if ((t /= 1 / 2) < 1) {
return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s));
}
return 1 / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
},
easeInBounce: function(t) {
return 1 - easingEffects.easeOutBounce(1 - t);
},
easeOutBounce: function(t) {
if ((t /= 1) < (1 / 2.75)) {
return 1 * (7.5625 * t * t);
} else if (t < (2 / 2.75)) {
return 1 * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75);
} else if (t < (2.5 / 2.75)) {
return 1 * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375);
} else {
return 1 * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375);
}
},
easeInOutBounce: function(t) {
if (t < 1 / 2) {
return easingEffects.easeInBounce(t * 2) * 0.5;
}
return easingEffects.easeOutBounce(t * 2 - 1) * 0.5 + 1 * 0.5;
}
};
//Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
helpers.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
return window.setTimeout(callback, 1000 / 60);
};
})();
helpers.cancelAnimFrame = (function() {
return window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
window.oCancelAnimationFrame ||
window.msCancelAnimationFrame ||
function(callback) {
return window.clearTimeout(callback, 1000 / 60);
};
})();
//-- DOM methods
helpers.getRelativePosition = function(evt, chart) {
var mouseX, mouseY;
var e = evt.originalEvent || evt,
canvas = evt.currentTarget || evt.srcElement,
boundingRect = canvas.getBoundingClientRect();
var touches = e.touches;
if (touches && touches.length > 0) {
mouseX = touches[0].clientX;
mouseY = touches[0].clientY;
} else {
mouseX = e.clientX;
mouseY = e.clientY;
}
// Scale mouse coordinates into canvas coordinates
// by following the pattern laid out by 'jerryj' in the comments of
// http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
var paddingLeft = parseFloat(helpers.getStyle(canvas, 'padding-left'));
var paddingTop = parseFloat(helpers.getStyle(canvas, 'padding-top'));
var paddingRight = parseFloat(helpers.getStyle(canvas, 'padding-right'));
var paddingBottom = parseFloat(helpers.getStyle(canvas, 'padding-bottom'));
var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
// We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
// the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
return {
x: mouseX,
y: mouseY
};
};
helpers.addEvent = function(node, eventType, method) {
if (node.addEventListener) {
node.addEventListener(eventType, method);
} else if (node.attachEvent) {
node.attachEvent("on" + eventType, method);
} else {
node["on" + eventType] = method;
}
};
helpers.removeEvent = function(node, eventType, handler) {
if (node.removeEventListener) {
node.removeEventListener(eventType, handler, false);
} else if (node.detachEvent) {
node.detachEvent("on" + eventType, handler);
} else {
node["on" + eventType] = helpers.noop;
}
};
helpers.bindEvents = function(chartInstance, arrayOfEvents, handler) {
// Create the events object if it's not already present
var events = chartInstance.events = chartInstance.events || {};
helpers.each(arrayOfEvents, function(eventName) {
events[eventName] = function() {
handler.apply(chartInstance, arguments);
};
helpers.addEvent(chartInstance.chart.canvas, eventName, events[eventName]);
});
};
helpers.unbindEvents = function(chartInstance, arrayOfEvents) {
var canvas = chartInstance.chart.canvas;
helpers.each(arrayOfEvents, function(handler, eventName) {
helpers.removeEvent(canvas, eventName, handler);
});
};
// Private helper function to convert max-width/max-height values that may be percentages into a number
function parseMaxStyle(styleValue, node, parentProperty) {
var valueInPixels;
if (typeof(styleValue) === 'string') {
valueInPixels = parseInt(styleValue, 10);
if (styleValue.indexOf('%') != -1) {
// percentage * size in dimension
valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
}
} else {
valueInPixels = styleValue;
}
return valueInPixels;
}
/**
* Returns if the given value contains an effective constraint.
* @private
*/
function isConstrainedValue(value) {
return value !== undefined && value !== null && value !== 'none';
}
// Private helper to get a constraint dimension
// @param domNode : the node to check the constraint on
// @param maxStyle : the style that defines the maximum for the direction we are using (maxWidth / maxHeight)
// @param percentageProperty : property of parent to use when calculating width as a percentage
// @see http://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser
function getConstraintDimension(domNode, maxStyle, percentageProperty) {
var view = document.defaultView;
var parentNode = domNode.parentNode;
var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
var hasCNode = isConstrainedValue(constrainedNode);
var hasCContainer = isConstrainedValue(constrainedContainer);
var infinity = Number.POSITIVE_INFINITY;
if (hasCNode || hasCContainer) {
return Math.min(
hasCNode? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
hasCContainer? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
}
return 'none';
}
// returns Number or undefined if no constraint
helpers.getConstraintWidth = function(domNode) {
return getConstraintDimension(domNode, 'max-width', 'clientWidth');
};
// returns Number or undefined if no constraint
helpers.getConstraintHeight = function(domNode) {
return getConstraintDimension(domNode, 'max-height', 'clientHeight');
};
helpers.getMaximumWidth = function(domNode) {
var container = domNode.parentNode;
var padding = parseInt(helpers.getStyle(container, 'padding-left')) + parseInt(helpers.getStyle(container, 'padding-right'));
var w = container.clientWidth - padding;
var cw = helpers.getConstraintWidth(domNode);
return isNaN(cw)? w : Math.min(w, cw);
};
helpers.getMaximumHeight = function(domNode) {
var container = domNode.parentNode;
var padding = parseInt(helpers.getStyle(container, 'padding-top')) + parseInt(helpers.getStyle(container, 'padding-bottom'));
var h = container.clientHeight - padding;
var ch = helpers.getConstraintHeight(domNode);
return isNaN(ch)? h : Math.min(h, ch);
};
helpers.getStyle = function(el, property) {
return el.currentStyle ?
el.currentStyle[property] :
document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
};
helpers.retinaScale = function(chart) {
var ctx = chart.ctx;
var canvas = chart.canvas;
var width = canvas.width;
var height = canvas.height;
var pixelRatio = chart.currentDevicePixelRatio = window.devicePixelRatio || 1;
if (pixelRatio !== 1) {
canvas.height = height * pixelRatio;
canvas.width = width * pixelRatio;
ctx.scale(pixelRatio, pixelRatio);
// Store the device pixel ratio so that we can go backwards in `destroy`.
// The devicePixelRatio changes with zoom, so there are no guarantees that it is the same
// when destroy is called
chart.originalDevicePixelRatio = chart.originalDevicePixelRatio || pixelRatio;
}
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
};
//-- Canvas methods
helpers.clear = function(chart) {
chart.ctx.clearRect(0, 0, chart.width, chart.height);
};
helpers.fontString = function(pixelSize, fontStyle, fontFamily) {
return fontStyle + " " + pixelSize + "px " + fontFamily;
};
helpers.longestText = function(ctx, font, arrayOfThings, cache) {
cache = cache || {};
var data = cache.data = cache.data || {};
var gc = cache.garbageCollect = cache.garbageCollect || [];
if (cache.font !== font) {
data = cache.data = {};
gc = cache.garbageCollect = [];
cache.font = font;
}
ctx.font = font;
var longest = 0;
helpers.each(arrayOfThings, function(thing) {
// Undefined strings and arrays should not be measured
if (thing !== undefined && thing !== null && helpers.isArray(thing) !== true) {
longest = helpers.measureText(ctx, data, gc, longest, thing);
} else if (helpers.isArray(thing)) {
// if it is an array lets measure each element
// to do maybe simplify this function a bit so we can do this more recursively?
helpers.each(thing, function(nestedThing) {
// Undefined strings and arrays should not be measured
if (nestedThing !== undefined && nestedThing !== null && !helpers.isArray(nestedThing)) {
longest = helpers.measureText(ctx, data, gc, longest, nestedThing);
}
});
}
});
var gcLen = gc.length / 2;
if (gcLen > arrayOfThings.length) {
for (var i = 0; i < gcLen; i++) {
delete data[gc[i]];
}
gc.splice(0, gcLen);
}
return longest;
};
helpers.measureText = function (ctx, data, gc, longest, string) {
var textWidth = data[string];
if (!textWidth) {
textWidth = data[string] = ctx.measureText(string).width;
gc.push(string);
}
if (textWidth > longest) {
longest = textWidth;
}
return longest;
};
helpers.numberOfLabelLines = function(arrayOfThings) {
var numberOfLines = 1;
helpers.each(arrayOfThings, function(thing) {
if (helpers.isArray(thing)) {
if (thing.length > numberOfLines) {
numberOfLines = thing.length;
}
}
});
return numberOfLines;
};
helpers.drawRoundedRectangle = function(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
};
helpers.color = function(c) {
if (!color) {
console.log('Color.js not found!');
return c;
}
/* global CanvasGradient */
if (c instanceof CanvasGradient) {
return color(Chart.defaults.global.defaultColor);
}
return color(c);
};
helpers.addResizeListener = function(node, callback) {
// Hide an iframe before the node
var hiddenIframe = document.createElement('iframe');
var hiddenIframeClass = 'chartjs-hidden-iframe';
if (hiddenIframe.classlist) {
// can use classlist
hiddenIframe.classlist.add(hiddenIframeClass);
} else {
hiddenIframe.setAttribute('class', hiddenIframeClass);
}
// Set the style
var style = hiddenIframe.style;
style.width = '100%';
style.display = 'block';
style.border = 0;
style.height = 0;
style.margin = 0;
style.position = 'absolute';
style.left = 0;
style.right = 0;
style.top = 0;
style.bottom = 0;
// Insert the iframe so that contentWindow is available
node.insertBefore(hiddenIframe, node.firstChild);
(hiddenIframe.contentWindow || hiddenIframe).onresize = function() {
if (callback) {
callback();
}
};
};
helpers.removeResizeListener = function(node) {
var hiddenIframe = node.querySelector('.chartjs-hidden-iframe');
// Remove the resize detect iframe
if (hiddenIframe) {
hiddenIframe.parentNode.removeChild(hiddenIframe);
}
};
helpers.isArray = Array.isArray?
function(obj) { return Array.isArray(obj); } :
function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
//! @see http://stackoverflow.com/a/14853974
helpers.arrayEquals = function(a0, a1) {
var i, ilen, v0, v1;
if (!a0 || !a1 || a0.length != a1.length) {
return false;
}
for (i = 0, ilen=a0.length; i < ilen; ++i) {
v0 = a0[i];
v1 = a1[i];
if (v0 instanceof Array && v1 instanceof Array) {
if (!helpers.arrayEquals(v0, v1)) {
return false;
}
} else if (v0 != v1) {
// NOTE: two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
};
helpers.callCallback = function(fn, args, _tArg) {
if (fn && typeof fn.call === 'function') {
fn.apply(_tArg, args);
}
};
helpers.getHoverColor = function(color) {
/* global CanvasPattern */
return (color instanceof CanvasPattern) ?
color :
helpers.color(color).saturate(0.5).darken(0.1).rgbString();
};
};
},{"3":3}],26:[function(require,module,exports){
"use strict";
module.exports = function() {
//Occupy the global variable of Chart, and create a simple base class
var Chart = function(context, config) {
var me = this;
var helpers = Chart.helpers;
me.config = config;
// Support a jQuery'd canvas element
if (context.length && context[0].getContext) {
context = context[0];
}
// Support a canvas domnode
if (context.getContext) {
context = context.getContext("2d");
}
me.ctx = context;
me.canvas = context.canvas;
context.canvas.style.display = context.canvas.style.display || 'block';
// Figure out what the size of the chart will be.
// If the canvas has a specified width and height, we use those else
// we look to see if the canvas node has a CSS width and height.
// If there is still no height, fill the parent container
me.width = context.canvas.width || parseInt(helpers.getStyle(context.canvas, 'width'), 10) || helpers.getMaximumWidth(context.canvas);
me.height = context.canvas.height || parseInt(helpers.getStyle(context.canvas, 'height'), 10) || helpers.getMaximumHeight(context.canvas);
me.aspectRatio = me.width / me.height;
if (isNaN(me.aspectRatio) || isFinite(me.aspectRatio) === false) {
// If the canvas has no size, try and figure out what the aspect ratio will be.
// Some charts prefer square canvases (pie, radar, etc). If that is specified, use that
// else use the canvas default ratio of 2
me.aspectRatio = config.aspectRatio !== undefined ? config.aspectRatio : 2;
}
// Store the original style of the element so we can set it back
me.originalCanvasStyleWidth = context.canvas.style.width;
me.originalCanvasStyleHeight = context.canvas.style.height;
// High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
helpers.retinaScale(me);
if (config) {
me.controller = new Chart.Controller(me);
}
// Always bind this so that if the responsive state changes we still work
helpers.addResizeListener(context.canvas.parentNode, function() {
if (me.controller && me.controller.config.options.responsive) {
me.controller.resize();
}
});
return me.controller ? me.controller : me;
};
//Globally expose the defaults to allow for user updating/changing
Chart.defaults = {
global: {
responsive: true,
responsiveAnimationDuration: 0,
maintainAspectRatio: true,
events: ["mousemove", "mouseout", "click", "touchstart", "touchmove"],
hover: {
onHover: null,
mode: 'single',
animationDuration: 400
},
onClick: null,
defaultColor: 'rgba(0,0,0,0.1)',
defaultFontColor: '#666',
defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
defaultFontSize: 12,
defaultFontStyle: 'normal',
showLines: true,
// Element defaults defined in element extensions
elements: {},
// Legend callback string
legendCallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend">');
for (var i = 0; i < chart.data.datasets.length; i++) {
text.push('<li><span style="background-color:' + chart.data.datasets[i].backgroundColor + '"></span>');
if (chart.data.datasets[i].label) {
text.push(chart.data.datasets[i].label);
}
text.push('</li>');
}
text.push('</ul>');
return text.join("");
}
}
};
Chart.Chart = Chart;
return Chart;
};
},{}],27:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
// The layout service is very self explanatory. It's responsible for the layout within a chart.
// Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
// It is this service's responsibility of carrying out that layout.
Chart.layoutService = {
defaults: {},
// Register a box to a chartInstance. A box is simply a reference to an object that requires layout. eg. Scales, Legend, Plugins.
addBox: function(chartInstance, box) {
if (!chartInstance.boxes) {
chartInstance.boxes = [];
}
chartInstance.boxes.push(box);
},
removeBox: function(chartInstance, box) {
if (!chartInstance.boxes) {
return;
}
chartInstance.boxes.splice(chartInstance.boxes.indexOf(box), 1);
},
// The most important function
update: function(chartInstance, width, height) {
if (!chartInstance) {
return;
}
var xPadding = 0;
var yPadding = 0;
var leftBoxes = helpers.where(chartInstance.boxes, function(box) {
return box.options.position === "left";
});
var rightBoxes = helpers.where(chartInstance.boxes, function(box) {
return box.options.position === "right";
});
var topBoxes = helpers.where(chartInstance.boxes, function(box) {
return box.options.position === "top";
});
var bottomBoxes = helpers.where(chartInstance.boxes, function(box) {
return box.options.position === "bottom";
});
// Boxes that overlay the chartarea such as the radialLinear scale
var chartAreaBoxes = helpers.where(chartInstance.boxes, function(box) {
return box.options.position === "chartArea";
});
// Ensure that full width boxes are at the very top / bottom
topBoxes.sort(function(a, b) {
return (b.options.fullWidth ? 1 : 0) - (a.options.fullWidth ? 1 : 0);
});
bottomBoxes.sort(function(a, b) {
return (a.options.fullWidth ? 1 : 0) - (b.options.fullWidth ? 1 : 0);
});
// Essentially we now have any number of boxes on each of the 4 sides.
// Our canvas looks like the following.
// The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
// B1 is the bottom axis
// There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
// These locations are single-box locations only, when trying to register a chartArea location that is already taken,
// an error will be thrown.
//
// |----------------------------------------------------|
// | T1 (Full Width) |
// |----------------------------------------------------|
// | | | T2 | |
// | |----|-------------------------------------|----|
// | | | C1 | | C2 | |
// | | |----| |----| |
// | | | | |
// | L1 | L2 | ChartArea (C0) | R1 |
// | | | | |
// | | |----| |----| |
// | | | C3 | | C4 | |
// | |----|-------------------------------------|----|
// | | | B1 | |
// |----------------------------------------------------|
// | B2 (Full Width) |
// |----------------------------------------------------|
//
// What we do to find the best sizing, we do the following
// 1. Determine the minimum size of the chart area.
// 2. Split the remaining width equally between each vertical axis
// 3. Split the remaining height equally between each horizontal axis
// 4. Give each layout the maximum size it can be. The layout will return it's minimum size
// 5. Adjust the sizes of each axis based on it's minimum reported size.
// 6. Refit each axis
// 7. Position each axis in the final location
// 8. Tell the chart the final location of the chart area
// 9. Tell any axes that overlay the chart area the positions of the chart area
// Step 1
var chartWidth = width - (2 * xPadding);
var chartHeight = height - (2 * yPadding);
var chartAreaWidth = chartWidth / 2; // min 50%
var chartAreaHeight = chartHeight / 2; // min 50%
// Step 2
var verticalBoxWidth = (width - chartAreaWidth) / (leftBoxes.length + rightBoxes.length);
// Step 3
var horizontalBoxHeight = (height - chartAreaHeight) / (topBoxes.length + bottomBoxes.length);
// Step 4
var maxChartAreaWidth = chartWidth;
var maxChartAreaHeight = chartHeight;
var minBoxSizes = [];
helpers.each(leftBoxes.concat(rightBoxes, topBoxes, bottomBoxes), getMinimumBoxSize);
function getMinimumBoxSize(box) {
var minSize;
var isHorizontal = box.isHorizontal();
if (isHorizontal) {
minSize = box.update(box.options.fullWidth ? chartWidth : maxChartAreaWidth, horizontalBoxHeight);
maxChartAreaHeight -= minSize.height;
} else {
minSize = box.update(verticalBoxWidth, chartAreaHeight);
maxChartAreaWidth -= minSize.width;
}
minBoxSizes.push({
horizontal: isHorizontal,
minSize: minSize,
box: box
});
}
// At this point, maxChartAreaHeight and maxChartAreaWidth are the size the chart area could
// be if the axes are drawn at their minimum sizes.
// Steps 5 & 6
var totalLeftBoxesWidth = xPadding;
var totalRightBoxesWidth = xPadding;
var totalTopBoxesHeight = yPadding;
var totalBottomBoxesHeight = yPadding;
// Update, and calculate the left and right margins for the horizontal boxes
helpers.each(leftBoxes.concat(rightBoxes), fitBox);
helpers.each(leftBoxes, function(box) {
totalLeftBoxesWidth += box.width;
});
helpers.each(rightBoxes, function(box) {
totalRightBoxesWidth += box.width;
});
// Set the Left and Right margins for the horizontal boxes
helpers.each(topBoxes.concat(bottomBoxes), fitBox);
// Function to fit a box
function fitBox(box) {
var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minBoxSize) {
return minBoxSize.box === box;
});
if (minBoxSize) {
if (box.isHorizontal()) {
var scaleMargin = {
left: totalLeftBoxesWidth,
right: totalRightBoxesWidth,
top: 0,
bottom: 0
};
// Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends
// on the margin. Sometimes they need to increase in size slightly
box.update(box.options.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin);
} else {
box.update(minBoxSize.minSize.width, maxChartAreaHeight);
}
}
}
// Figure out how much margin is on the top and bottom of the vertical boxes
helpers.each(topBoxes, function(box) {
totalTopBoxesHeight += box.height;
});
helpers.each(bottomBoxes, function(box) {
totalBottomBoxesHeight += box.height;
});
// Let the left layout know the final margin
helpers.each(leftBoxes.concat(rightBoxes), finalFitVerticalBox);
function finalFitVerticalBox(box) {
var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minBoxSize) {
return minBoxSize.box === box;
});
var scaleMargin = {
left: 0,
right: 0,
top: totalTopBoxesHeight,
bottom: totalBottomBoxesHeight
};
if (minBoxSize) {
box.update(minBoxSize.minSize.width, maxChartAreaHeight, scaleMargin);
}
}
// Recalculate because the size of each layout might have changed slightly due to the margins (label rotation for instance)
totalLeftBoxesWidth = xPadding;
totalRightBoxesWidth = xPadding;
totalTopBoxesHeight = yPadding;
totalBottomBoxesHeight = yPadding;
helpers.each(leftBoxes, function(box) {
totalLeftBoxesWidth += box.width;
});
helpers.each(rightBoxes, function(box) {
totalRightBoxesWidth += box.width;
});
helpers.each(topBoxes, function(box) {
totalTopBoxesHeight += box.height;
});
helpers.each(bottomBoxes, function(box) {
totalBottomBoxesHeight += box.height;
});
// Figure out if our chart area changed. This would occur if the dataset layout label rotation
// changed due to the application of the margins in step 6. Since we can only get bigger, this is safe to do
// without calling `fit` again
var newMaxChartAreaHeight = height - totalTopBoxesHeight - totalBottomBoxesHeight;
var newMaxChartAreaWidth = width - totalLeftBoxesWidth - totalRightBoxesWidth;
if (newMaxChartAreaWidth !== maxChartAreaWidth || newMaxChartAreaHeight !== maxChartAreaHeight) {
helpers.each(leftBoxes, function(box) {
box.height = newMaxChartAreaHeight;
});
helpers.each(rightBoxes, function(box) {
box.height = newMaxChartAreaHeight;
});
helpers.each(topBoxes, function(box) {
if (!box.options.fullWidth) {
box.width = newMaxChartAreaWidth;
}
});
helpers.each(bottomBoxes, function(box) {
if (!box.options.fullWidth) {
box.width = newMaxChartAreaWidth;
}
});
maxChartAreaHeight = newMaxChartAreaHeight;
maxChartAreaWidth = newMaxChartAreaWidth;
}
// Step 7 - Position the boxes
var left = xPadding;
var top = yPadding;
var right = 0;
var bottom = 0;
helpers.each(leftBoxes.concat(topBoxes), placeBox);
// Account for chart width and height
left += maxChartAreaWidth;
top += maxChartAreaHeight;
helpers.each(rightBoxes, placeBox);
helpers.each(bottomBoxes, placeBox);
function placeBox(box) {
if (box.isHorizontal()) {
box.left = box.options.fullWidth ? xPadding : totalLeftBoxesWidth;
box.right = box.options.fullWidth ? width - xPadding : totalLeftBoxesWidth + maxChartAreaWidth;
box.top = top;
box.bottom = top + box.height;
// Move to next point
top = box.bottom;
} else {
box.left = left;
box.right = left + box.width;
box.top = totalTopBoxesHeight;
box.bottom = totalTopBoxesHeight + maxChartAreaHeight;
// Move to next point
left = box.right;
}
}
// Step 8
chartInstance.chartArea = {
left: totalLeftBoxesWidth,
top: totalTopBoxesHeight,
right: totalLeftBoxesWidth + maxChartAreaWidth,
bottom: totalTopBoxesHeight + maxChartAreaHeight
};
// Step 9
helpers.each(chartAreaBoxes, function(box) {
box.left = chartInstance.chartArea.left;
box.top = chartInstance.chartArea.top;
box.right = chartInstance.chartArea.right;
box.bottom = chartInstance.chartArea.bottom;
box.update(maxChartAreaWidth, maxChartAreaHeight);
});
}
};
};
},{}],28:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
var noop = helpers.noop;
Chart.defaults.global.legend = {
display: true,
position: 'top',
fullWidth: true, // marks that this box should take the full width of the canvas (pushing down other boxes)
reverse: false,
// a callback that will handle
onClick: function(e, legendItem) {
var index = legendItem.datasetIndex;
var ci = this.chart;
var meta = ci.getDatasetMeta(index);
// See controller.isDatasetVisible comment
meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null;
// We hid a dataset ... rerender the chart
ci.update();
},
labels: {
boxWidth: 40,
padding: 10,
// Generates labels shown in the legend
// Valid properties to return:
// text : text to display
// fillStyle : fill of coloured box
// strokeStyle: stroke of coloured box
// hidden : if this legend item refers to a hidden item
// lineCap : cap style for line
// lineDash
// lineDashOffset :
// lineJoin :
// lineWidth :
generateLabels: function(chart) {
var data = chart.data;
return helpers.isArray(data.datasets) ? data.datasets.map(function(dataset, i) {
return {
text: dataset.label,
fillStyle: (!helpers.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]),
hidden: !chart.isDatasetVisible(i),
lineCap: dataset.borderCapStyle,
lineDash: dataset.borderDash,
lineDashOffset: dataset.borderDashOffset,
lineJoin: dataset.borderJoinStyle,
lineWidth: dataset.borderWidth,
strokeStyle: dataset.borderColor,
// Below is extra data used for toggling the datasets
datasetIndex: i
};
}, this) : [];
}
}
};
Chart.Legend = Chart.Element.extend({
initialize: function(config) {
helpers.extend(this, config);
// Contains hit boxes for each dataset (in dataset order)
this.legendHitBoxes = [];
// Are we in doughnut mode which has a different data type
this.doughnutMode = false;
},
// These methods are ordered by lifecyle. Utilities then follow.
// Any function defined here is inherited by all legend types.
// Any function can be extended by the legend type
beforeUpdate: noop,
update: function(maxWidth, maxHeight, margins) {
var me = this;
// Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
me.beforeUpdate();
// Absorb the master measurements
me.maxWidth = maxWidth;
me.maxHeight = maxHeight;
me.margins = margins;
// Dimensions
me.beforeSetDimensions();
me.setDimensions();
me.afterSetDimensions();
// Labels
me.beforeBuildLabels();
me.buildLabels();
me.afterBuildLabels();
// Fit
me.beforeFit();
me.fit();
me.afterFit();
//
me.afterUpdate();
return me.minSize;
},
afterUpdate: noop,
//
beforeSetDimensions: noop,
setDimensions: function() {
var me = this;
// Set the unconstrained dimension before label rotation
if (me.isHorizontal()) {
// Reset position before calculating rotation
me.width = me.maxWidth;
me.left = 0;
me.right = me.width;
} else {
me.height = me.maxHeight;
// Reset position before calculating rotation
me.top = 0;
me.bottom = me.height;
}
// Reset padding
me.paddingLeft = 0;
me.paddingTop = 0;
me.paddingRight = 0;
me.paddingBottom = 0;
// Reset minSize
me.minSize = {
width: 0,
height: 0
};
},
afterSetDimensions: noop,
//
beforeBuildLabels: noop,
buildLabels: function() {
var me = this;
me.legendItems = me.options.labels.generateLabels.call(me, me.chart);
if(me.options.reverse){
me.legendItems.reverse();
}
},
afterBuildLabels: noop,
//
beforeFit: noop,
fit: function() {
var me = this;
var opts = me.options;
var labelOpts = opts.labels;
var display = opts.display;
var ctx = me.ctx;
var globalDefault = Chart.defaults.global,
itemOrDefault = helpers.getValueOrDefault,
fontSize = itemOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize),
fontStyle = itemOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle),
fontFamily = itemOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily),
labelFont = helpers.fontString(fontSize, fontStyle, fontFamily);
// Reset hit boxes
var hitboxes = me.legendHitBoxes = [];
var minSize = me.minSize;
var isHorizontal = me.isHorizontal();
if (isHorizontal) {
minSize.width = me.maxWidth; // fill all the width
minSize.height = display ? 10 : 0;
} else {
minSize.width = display ? 10 : 0;
minSize.height = me.maxHeight; // fill all the height
}
// Increase sizes here
if (display) {
ctx.font = labelFont;
if (isHorizontal) {
// Labels
// Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
var lineWidths = me.lineWidths = [0];
var totalHeight = me.legendItems.length ? fontSize + (labelOpts.padding) : 0;
ctx.textAlign = "left";
ctx.textBaseline = 'top';
helpers.each(me.legendItems, function(legendItem, i) {
var width = labelOpts.boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
if (lineWidths[lineWidths.length - 1] + width + labelOpts.padding >= me.width) {
totalHeight += fontSize + (labelOpts.padding);
lineWidths[lineWidths.length] = me.left;
}
// Store the hitbox width and height here. Final position will be updated in `draw`
hitboxes[i] = {
left: 0,
top: 0,
width: width,
height: fontSize
};
lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
});
minSize.height += totalHeight;
} else {
var vPadding = labelOpts.padding;
var columnWidths = me.columnWidths = [];
var totalWidth = labelOpts.padding;
var currentColWidth = 0;
var currentColHeight = 0;
var itemHeight = fontSize + vPadding;
helpers.each(me.legendItems, function(legendItem, i) {
var itemWidth = labelOpts.boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
// If too tall, go to new column
if (currentColHeight + itemHeight > minSize.height) {
totalWidth += currentColWidth + labelOpts.padding;
columnWidths.push(currentColWidth); // previous column width
currentColWidth = 0;
currentColHeight = 0;
}
// Get max width
currentColWidth = Math.max(currentColWidth, itemWidth);
currentColHeight += itemHeight;
// Store the hitbox width and height here. Final position will be updated in `draw`
hitboxes[i] = {
left: 0,
top: 0,
width: itemWidth,
height: fontSize
};
});
totalWidth += currentColWidth;
columnWidths.push(currentColWidth);
minSize.width += totalWidth;
}
}
me.width = minSize.width;
me.height = minSize.height;
},
afterFit: noop,
// Shared Methods
isHorizontal: function() {
return this.options.position === "top" || this.options.position === "bottom";
},
// Actualy draw the legend on the canvas
draw: function() {
var me = this;
var opts = me.options;
var labelOpts = opts.labels;
var globalDefault = Chart.defaults.global,
lineDefault = globalDefault.elements.line,
legendWidth = me.width,
legendHeight = me.height,
lineWidths = me.lineWidths;
if (opts.display) {
var ctx = me.ctx,
cursor,
itemOrDefault = helpers.getValueOrDefault,
fontColor = itemOrDefault(labelOpts.fontColor, globalDefault.defaultFontColor),
fontSize = itemOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize),
fontStyle = itemOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle),
fontFamily = itemOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily),
labelFont = helpers.fontString(fontSize, fontStyle, fontFamily);
// Canvas setup
ctx.textAlign = "left";
ctx.textBaseline = 'top';
ctx.lineWidth = 0.5;
ctx.strokeStyle = fontColor; // for strikethrough effect
ctx.fillStyle = fontColor; // render in correct colour
ctx.font = labelFont;
var boxWidth = labelOpts.boxWidth,
hitboxes = me.legendHitBoxes;
// current position
var drawLegendBox = function(x, y, legendItem) {
// Set the ctx for the box
ctx.save();
ctx.fillStyle = itemOrDefault(legendItem.fillStyle, globalDefault.defaultColor);
ctx.lineCap = itemOrDefault(legendItem.lineCap, lineDefault.borderCapStyle);
ctx.lineDashOffset = itemOrDefault(legendItem.lineDashOffset, lineDefault.borderDashOffset);
ctx.lineJoin = itemOrDefault(legendItem.lineJoin, lineDefault.borderJoinStyle);
ctx.lineWidth = itemOrDefault(legendItem.lineWidth, lineDefault.borderWidth);
ctx.strokeStyle = itemOrDefault(legendItem.strokeStyle, globalDefault.defaultColor);
if (ctx.setLineDash) {
// IE 9 and 10 do not support line dash
ctx.setLineDash(itemOrDefault(legendItem.lineDash, lineDefault.borderDash));
}
// Draw the box
ctx.strokeRect(x, y, boxWidth, fontSize);
ctx.fillRect(x, y, boxWidth, fontSize);
ctx.restore();
};
var fillText = function(x, y, legendItem, textWidth) {
ctx.fillText(legendItem.text, boxWidth + (fontSize / 2) + x, y);
if (legendItem.hidden) {
// Strikethrough the text if hidden
ctx.beginPath();
ctx.lineWidth = 2;
ctx.moveTo(boxWidth + (fontSize / 2) + x, y + (fontSize / 2));
ctx.lineTo(boxWidth + (fontSize / 2) + x + textWidth, y + (fontSize / 2));
ctx.stroke();
}
};
// Horizontal
var isHorizontal = me.isHorizontal();
if (isHorizontal) {
cursor = {
x: me.left + ((legendWidth - lineWidths[0]) / 2),
y: me.top + labelOpts.padding,
line: 0
};
} else {
cursor = {
x: me.left + labelOpts.padding,
y: me.top,
line: 0
};
}
var itemHeight = fontSize + labelOpts.padding;
helpers.each(me.legendItems, function(legendItem, i) {
var textWidth = ctx.measureText(legendItem.text).width,
width = boxWidth + (fontSize / 2) + textWidth,
x = cursor.x,
y = cursor.y;
if (isHorizontal) {
if (x + width >= legendWidth) {
y = cursor.y += fontSize + (labelOpts.padding);
cursor.line++;
x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2);
}
} else {
if (y + itemHeight > me.bottom) {
x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
y = cursor.y = me.top;
cursor.line++;
}
}
drawLegendBox(x, y, legendItem);
hitboxes[i].left = x;
hitboxes[i].top = y;
// Fill the actual label
fillText(x, y, legendItem, textWidth);
if (isHorizontal) {
cursor.x += width + (labelOpts.padding);
} else {
cursor.y += itemHeight;
}
});
}
},
// Handle an event
handleEvent: function(e) {
var me = this;
var position = helpers.getRelativePosition(e, me.chart.chart),
x = position.x,
y = position.y,
opts = me.options;
if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
// See if we are touching one of the dataset boxes
var lh = me.legendHitBoxes;
for (var i = 0; i < lh.length; ++i) {
var hitBox = lh[i];
if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
// Touching an element
if (opts.onClick) {
opts.onClick.call(me, e, me.legendItems[i]);
}
break;
}
}
}
}
});
// Register the legend plugin
Chart.plugins.register({
beforeInit: function(chartInstance) {
var opts = chartInstance.options;
var legendOpts = opts.legend;
if (legendOpts) {
chartInstance.legend = new Chart.Legend({
ctx: chartInstance.chart.ctx,
options: legendOpts,
chart: chartInstance
});
Chart.layoutService.addBox(chartInstance, chartInstance.legend);
}
}
});
};
},{}],29:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var noop = Chart.helpers.noop;
/**
* The plugin service singleton
* @namespace Chart.plugins
* @since 2.1.0
*/
Chart.plugins = {
_plugins: [],
/**
* Registers the given plugin(s) if not already registered.
* @param {Array|Object} plugins plugin instance(s).
*/
register: function(plugins) {
var p = this._plugins;
([]).concat(plugins).forEach(function(plugin) {
if (p.indexOf(plugin) === -1) {
p.push(plugin);
}
});
},
/**
* Unregisters the given plugin(s) only if registered.
* @param {Array|Object} plugins plugin instance(s).
*/
unregister: function(plugins) {
var p = this._plugins;
([]).concat(plugins).forEach(function(plugin) {
var idx = p.indexOf(plugin);
if (idx !== -1) {
p.splice(idx, 1);
}
});
},
/**
* Remove all registered p^lugins.
* @since 2.1.5
*/
clear: function() {
this._plugins = [];
},
/**
* Returns the number of registered plugins?
* @returns {Number}
* @since 2.1.5
*/
count: function() {
return this._plugins.length;
},
/**
* Returns all registered plugin intances.
* @returns {Array} array of plugin objects.
* @since 2.1.5
*/
getAll: function() {
return this._plugins;
},
/**
* Calls registered plugins on the specified extension, with the given args. This
* method immediately returns as soon as a plugin explicitly returns false. The
* returned value can be used, for instance, to interrupt the current action.
* @param {String} extension the name of the plugin method to call (e.g. 'beforeUpdate').
* @param {Array} [args] extra arguments to apply to the extension call.
* @returns {Boolean} false if any of the plugins return false, else returns true.
*/
notify: function(extension, args) {
var plugins = this._plugins;
var ilen = plugins.length;
var i, plugin;
for (i=0; i<ilen; ++i) {
plugin = plugins[i];
if (typeof plugin[extension] === 'function') {
if (plugin[extension].apply(plugin, args || []) === false) {
return false;
}
}
}
return true;
}
};
/**
* Plugin extension methods.
* @interface Chart.PluginBase
* @since 2.1.0
*/
Chart.PluginBase = Chart.Element.extend({
// Called at start of chart init
beforeInit: noop,
// Called at end of chart init
afterInit: noop,
// Called at start of update
beforeUpdate: noop,
// Called at end of update
afterUpdate: noop,
// Called at start of draw
beforeDraw: noop,
// Called at end of draw
afterDraw: noop,
// Called during destroy
destroy: noop
});
/**
* Provided for backward compatibility, use Chart.plugins instead
* @namespace Chart.pluginService
* @deprecated since version 2.1.5
* @todo remove me at version 3
*/
Chart.pluginService = Chart.plugins;
};
},{}],30:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
Chart.defaults.scale = {
display: true,
position: "left",
// grid line settings
gridLines: {
display: true,
color: "rgba(0, 0, 0, 0.1)",
lineWidth: 1,
drawBorder: true,
drawOnChartArea: true,
drawTicks: true,
tickMarkLength: 10,
zeroLineWidth: 1,
zeroLineColor: "rgba(0,0,0,0.25)",
offsetGridLines: false
},
// scale label
scaleLabel: {
// actual label
labelString: '',
// display property
display: false
},
// label settings
ticks: {
beginAtZero: false,
minRotation: 0,
maxRotation: 50,
mirror: false,
padding: 10,
reverse: false,
display: true,
autoSkip: true,
autoSkipPadding: 0,
labelOffset: 0,
// We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
callback: function(value) {
return helpers.isArray(value) ? value : '' + value;
}
}
};
Chart.Scale = Chart.Element.extend({
// These methods are ordered by lifecyle. Utilities then follow.
// Any function defined here is inherited by all scale types.
// Any function can be extended by the scale type
beforeUpdate: function() {
helpers.callCallback(this.options.beforeUpdate, [this]);
},
update: function(maxWidth, maxHeight, margins) {
var me = this;
// Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
me.beforeUpdate();
// Absorb the master measurements
me.maxWidth = maxWidth;
me.maxHeight = maxHeight;
me.margins = helpers.extend({
left: 0,
right: 0,
top: 0,
bottom: 0
}, margins);
// Dimensions
me.beforeSetDimensions();
me.setDimensions();
me.afterSetDimensions();
// Data min/max
me.beforeDataLimits();
me.determineDataLimits();
me.afterDataLimits();
// Ticks
me.beforeBuildTicks();
me.buildTicks();
me.afterBuildTicks();
me.beforeTickToLabelConversion();
me.convertTicksToLabels();
me.afterTickToLabelConversion();
// Tick Rotation
me.beforeCalculateTickRotation();
me.calculateTickRotation();
me.afterCalculateTickRotation();
// Fit
me.beforeFit();
me.fit();
me.afterFit();
//
me.afterUpdate();
return me.minSize;
},
afterUpdate: function() {
helpers.callCallback(this.options.afterUpdate, [this]);
},
//
beforeSetDimensions: function() {
helpers.callCallback(this.options.beforeSetDimensions, [this]);
},
setDimensions: function() {
var me = this;
// Set the unconstrained dimension before label rotation
if (me.isHorizontal()) {
// Reset position before calculating rotation
me.width = me.maxWidth;
me.left = 0;
me.right = me.width;
} else {
me.height = me.maxHeight;
// Reset position before calculating rotation
me.top = 0;
me.bottom = me.height;
}
// Reset padding
me.paddingLeft = 0;
me.paddingTop = 0;
me.paddingRight = 0;
me.paddingBottom = 0;
},
afterSetDimensions: function() {
helpers.callCallback(this.options.afterSetDimensions, [this]);
},
// Data limits
beforeDataLimits: function() {
helpers.callCallback(this.options.beforeDataLimits, [this]);
},
determineDataLimits: helpers.noop,
afterDataLimits: function() {
helpers.callCallback(this.options.afterDataLimits, [this]);
},
//
beforeBuildTicks: function() {
helpers.callCallback(this.options.beforeBuildTicks, [this]);
},
buildTicks: helpers.noop,
afterBuildTicks: function() {
helpers.callCallback(this.options.afterBuildTicks, [this]);
},
beforeTickToLabelConversion: function() {
helpers.callCallback(this.options.beforeTickToLabelConversion, [this]);
},
convertTicksToLabels: function() {
var me = this;
// Convert ticks to strings
me.ticks = me.ticks.map(function(numericalTick, index, ticks) {
if (me.options.ticks.userCallback) {
return me.options.ticks.userCallback(numericalTick, index, ticks);
}
return me.options.ticks.callback(numericalTick, index, ticks);
},
me);
},
afterTickToLabelConversion: function() {
helpers.callCallback(this.options.afterTickToLabelConversion, [this]);
},
//
beforeCalculateTickRotation: function() {
helpers.callCallback(this.options.beforeCalculateTickRotation, [this]);
},
calculateTickRotation: function() {
var me = this;
var context = me.ctx;
var globalDefaults = Chart.defaults.global;
var optionTicks = me.options.ticks;
//Get the width of each grid by calculating the difference
//between x offsets between 0 and 1.
var tickFontSize = helpers.getValueOrDefault(optionTicks.fontSize, globalDefaults.defaultFontSize);
var tickFontStyle = helpers.getValueOrDefault(optionTicks.fontStyle, globalDefaults.defaultFontStyle);
var tickFontFamily = helpers.getValueOrDefault(optionTicks.fontFamily, globalDefaults.defaultFontFamily);
var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);
context.font = tickLabelFont;
var firstWidth = context.measureText(me.ticks[0]).width;
var lastWidth = context.measureText(me.ticks[me.ticks.length - 1]).width;
var firstRotated;
me.labelRotation = optionTicks.minRotation || 0;
me.paddingRight = 0;
me.paddingLeft = 0;
if (me.options.display) {
if (me.isHorizontal()) {
me.paddingRight = lastWidth / 2 + 3;
me.paddingLeft = firstWidth / 2 + 3;
if (!me.longestTextCache) {
me.longestTextCache = {};
}
var originalLabelWidth = helpers.longestText(context, tickLabelFont, me.ticks, me.longestTextCache);
var labelWidth = originalLabelWidth;
var cosRotation;
var sinRotation;
// Allow 3 pixels x2 padding either side for label readability
// only the index matters for a dataset scale, but we want a consistent interface between scales
var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6;
//Max label rotation can be set or default to 90 - also act as a loop counter
while (labelWidth > tickWidth && me.labelRotation < optionTicks.maxRotation) {
cosRotation = Math.cos(helpers.toRadians(me.labelRotation));
sinRotation = Math.sin(helpers.toRadians(me.labelRotation));
firstRotated = cosRotation * firstWidth;
// We're right aligning the text now.
if (firstRotated + tickFontSize / 2 > me.yLabelWidth) {
me.paddingLeft = firstRotated + tickFontSize / 2;
}
me.paddingRight = tickFontSize / 2;
if (sinRotation * originalLabelWidth > me.maxHeight) {
// go back one step
me.labelRotation--;
break;
}
me.labelRotation++;
labelWidth = cosRotation * originalLabelWidth;
}
}
}
if (me.margins) {
me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0);
me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0);
}
},
afterCalculateTickRotation: function() {
helpers.callCallback(this.options.afterCalculateTickRotation, [this]);
},
//
beforeFit: function() {
helpers.callCallback(this.options.beforeFit, [this]);
},
fit: function() {
var me = this;
// Reset
var minSize = me.minSize = {
width: 0,
height: 0
};
var opts = me.options;
var globalDefaults = Chart.defaults.global;
var tickOpts = opts.ticks;
var scaleLabelOpts = opts.scaleLabel;
var display = opts.display;
var isHorizontal = me.isHorizontal();
var tickFontSize = helpers.getValueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
var tickFontStyle = helpers.getValueOrDefault(tickOpts.fontStyle, globalDefaults.defaultFontStyle);
var tickFontFamily = helpers.getValueOrDefault(tickOpts.fontFamily, globalDefaults.defaultFontFamily);
var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);
var scaleLabelFontSize = helpers.getValueOrDefault(scaleLabelOpts.fontSize, globalDefaults.defaultFontSize);
var scaleLabelFontStyle = helpers.getValueOrDefault(scaleLabelOpts.fontStyle, globalDefaults.defaultFontStyle);
var scaleLabelFontFamily = helpers.getValueOrDefault(scaleLabelOpts.fontFamily, globalDefaults.defaultFontFamily);
var scaleLabelFont = helpers.fontString(scaleLabelFontSize, scaleLabelFontStyle, scaleLabelFontFamily);
var tickMarkLength = opts.gridLines.tickMarkLength;
// Width
if (isHorizontal) {
// subtract the margins to line up with the chartArea if we are a full width scale
minSize.width = me.isFullWidth() ? me.maxWidth - me.margins.left - me.margins.right : me.maxWidth;
} else {
minSize.width = display ? tickMarkLength : 0;
}
// height
if (isHorizontal) {
minSize.height = display ? tickMarkLength : 0;
} else {
minSize.height = me.maxHeight; // fill all the height
}
// Are we showing a title for the scale?
if (scaleLabelOpts.display && display) {
if (isHorizontal) {
minSize.height += (scaleLabelFontSize * 1.5);
} else {
minSize.width += (scaleLabelFontSize * 1.5);
}
}
if (tickOpts.display && display) {
// Don't bother fitting the ticks if we are not showing them
if (!me.longestTextCache) {
me.longestTextCache = {};
}
var largestTextWidth = helpers.longestText(me.ctx, tickLabelFont, me.ticks, me.longestTextCache);
var tallestLabelHeightInLines = helpers.numberOfLabelLines(me.ticks);
var lineSpace = tickFontSize * 0.5;
if (isHorizontal) {
// A horizontal axis is more constrained by the height.
me.longestLabelWidth = largestTextWidth;
// TODO - improve this calculation
var labelHeight = (Math.sin(helpers.toRadians(me.labelRotation)) * me.longestLabelWidth) + (tickFontSize * tallestLabelHeightInLines) + (lineSpace * tallestLabelHeightInLines);
minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight);
me.ctx.font = tickLabelFont;
var firstLabelWidth = me.ctx.measureText(me.ticks[0]).width;
var lastLabelWidth = me.ctx.measureText(me.ticks[me.ticks.length - 1]).width;
// Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned which means that the right padding is dominated
// by the font height
var cosRotation = Math.cos(helpers.toRadians(me.labelRotation));
var sinRotation = Math.sin(helpers.toRadians(me.labelRotation));
me.paddingLeft = me.labelRotation !== 0 ? (cosRotation * firstLabelWidth) + 3 : firstLabelWidth / 2 + 3; // add 3 px to move away from canvas edges
me.paddingRight = me.labelRotation !== 0 ? (sinRotation * (tickFontSize / 2)) + 3 : lastLabelWidth / 2 + 3; // when rotated
} else {
// A vertical axis is more constrained by the width. Labels are the dominant factor here, so get that length first
var maxLabelWidth = me.maxWidth - minSize.width;
// Account for padding
var mirror = tickOpts.mirror;
if (!mirror) {
largestTextWidth += me.options.ticks.padding;
} else {
// If mirrored text is on the inside so don't expand
largestTextWidth = 0;
}
if (largestTextWidth < maxLabelWidth) {
// We don't need all the room
minSize.width += largestTextWidth;
} else {
// Expand to max size
minSize.width = me.maxWidth;
}
me.paddingTop = tickFontSize / 2;
me.paddingBottom = tickFontSize / 2;
}
}
if (me.margins) {
me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0);
me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0);
me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0);
me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0);
}
me.width = minSize.width;
me.height = minSize.height;
},
afterFit: function() {
helpers.callCallback(this.options.afterFit, [this]);
},
// Shared Methods
isHorizontal: function() {
return this.options.position === "top" || this.options.position === "bottom";
},
isFullWidth: function() {
return (this.options.fullWidth);
},
// Get the correct value. NaN bad inputs, If the value type is object get the x or y based on whether we are horizontal or not
getRightValue: function getRightValue(rawValue) {
// Null and undefined values first
if (rawValue === null || typeof(rawValue) === 'undefined') {
return NaN;
}
// isNaN(object) returns true, so make sure NaN is checking for a number
if (typeof(rawValue) === 'number' && isNaN(rawValue)) {
return NaN;
}
// If it is in fact an object, dive in one more level
if (typeof(rawValue) === "object") {
if ((rawValue instanceof Date) || (rawValue.isValid)) {
return rawValue;
} else {
return getRightValue(this.isHorizontal() ? rawValue.x : rawValue.y);
}
}
// Value is good, return it
return rawValue;
},
// Used to get the value to display in the tooltip for the data at the given index
// function getLabelForIndex(index, datasetIndex)
getLabelForIndex: helpers.noop,
// Used to get data value locations. Value can either be an index or a numerical value
getPixelForValue: helpers.noop,
// Used to get the data value from a given pixel. This is the inverse of getPixelForValue
getValueForPixel: helpers.noop,
// Used for tick location, should
getPixelForTick: function(index, includeOffset) {
var me = this;
if (me.isHorizontal()) {
var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
var tickWidth = innerWidth / Math.max((me.ticks.length - ((me.options.gridLines.offsetGridLines) ? 0 : 1)), 1);
var pixel = (tickWidth * index) + me.paddingLeft;
if (includeOffset) {
pixel += tickWidth / 2;
}
var finalVal = me.left + Math.round(pixel);
finalVal += me.isFullWidth() ? me.margins.left : 0;
return finalVal;
} else {
var innerHeight = me.height - (me.paddingTop + me.paddingBottom);
return me.top + (index * (innerHeight / (me.ticks.length - 1)));
}
},
// Utility for getting the pixel location of a percentage of scale
getPixelForDecimal: function(decimal /*, includeOffset*/ ) {
var me = this;
if (me.isHorizontal()) {
var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
var valueOffset = (innerWidth * decimal) + me.paddingLeft;
var finalVal = me.left + Math.round(valueOffset);
finalVal += me.isFullWidth() ? me.margins.left : 0;
return finalVal;
} else {
return me.top + (decimal * me.height);
}
},
getBasePixel: function() {
var me = this;
var min = me.min;
var max = me.max;
return me.getPixelForValue(
me.beginAtZero? 0:
min < 0 && max < 0? max :
min > 0 && max > 0? min :
0);
},
// Actualy draw the scale on the canvas
// @param {rectangle} chartArea : the area of the chart to draw full grid lines on
draw: function(chartArea) {
var me = this;
var options = me.options;
if (!options.display) {
return;
}
var context = me.ctx;
var globalDefaults = Chart.defaults.global;
var optionTicks = options.ticks;
var gridLines = options.gridLines;
var scaleLabel = options.scaleLabel;
var isRotated = me.labelRotation !== 0;
var skipRatio;
var useAutoskipper = optionTicks.autoSkip;
var isHorizontal = me.isHorizontal();
// figure out the maximum number of gridlines to show
var maxTicks;
if (optionTicks.maxTicksLimit) {
maxTicks = optionTicks.maxTicksLimit;
}
var tickFontColor = helpers.getValueOrDefault(optionTicks.fontColor, globalDefaults.defaultFontColor);
var tickFontSize = helpers.getValueOrDefault(optionTicks.fontSize, globalDefaults.defaultFontSize);
var tickFontStyle = helpers.getValueOrDefault(optionTicks.fontStyle, globalDefaults.defaultFontStyle);
var tickFontFamily = helpers.getValueOrDefault(optionTicks.fontFamily, globalDefaults.defaultFontFamily);
var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);
var tl = gridLines.tickMarkLength;
var scaleLabelFontColor = helpers.getValueOrDefault(scaleLabel.fontColor, globalDefaults.defaultFontColor);
var scaleLabelFontSize = helpers.getValueOrDefault(scaleLabel.fontSize, globalDefaults.defaultFontSize);
var scaleLabelFontStyle = helpers.getValueOrDefault(scaleLabel.fontStyle, globalDefaults.defaultFontStyle);
var scaleLabelFontFamily = helpers.getValueOrDefault(scaleLabel.fontFamily, globalDefaults.defaultFontFamily);
var scaleLabelFont = helpers.fontString(scaleLabelFontSize, scaleLabelFontStyle, scaleLabelFontFamily);
var labelRotationRadians = helpers.toRadians(me.labelRotation);
var cosRotation = Math.cos(labelRotationRadians);
var sinRotation = Math.sin(labelRotationRadians);
var longestRotatedLabel = me.longestLabelWidth * cosRotation;
var rotatedLabelHeight = tickFontSize * sinRotation;
// Make sure we draw text in the correct color and font
context.fillStyle = tickFontColor;
var itemsToDraw = [];
if (isHorizontal) {
skipRatio = false;
// Only calculate the skip ratio with the half width of longestRotateLabel if we got an actual rotation
// See #2584
if (isRotated) {
longestRotatedLabel /= 2;
}
if ((longestRotatedLabel + optionTicks.autoSkipPadding) * me.ticks.length > (me.width - (me.paddingLeft + me.paddingRight))) {
skipRatio = 1 + Math.floor(((longestRotatedLabel + optionTicks.autoSkipPadding) * me.ticks.length) / (me.width - (me.paddingLeft + me.paddingRight)));
}
// if they defined a max number of optionTicks,
// increase skipRatio until that number is met
if (maxTicks && me.ticks.length > maxTicks) {
while (!skipRatio || me.ticks.length / (skipRatio || 1) > maxTicks) {
if (!skipRatio) {
skipRatio = 1;
}
skipRatio += 1;
}
}
if (!useAutoskipper) {
skipRatio = false;
}
}
var xTickStart = options.position === "right" ? me.left : me.right - tl;
var xTickEnd = options.position === "right" ? me.left + tl : me.right;
var yTickStart = options.position === "bottom" ? me.top : me.bottom - tl;
var yTickEnd = options.position === "bottom" ? me.top + tl : me.bottom;
helpers.each(me.ticks, function(label, index) {
// If the callback returned a null or undefined value, do not draw this line
if (label === undefined || label === null) {
return;
}
var isLastTick = me.ticks.length === index + 1;
// Since we always show the last tick,we need may need to hide the last shown one before
var shouldSkip = (skipRatio > 1 && index % skipRatio > 0) || (index % skipRatio === 0 && index + skipRatio >= me.ticks.length);
if (shouldSkip && !isLastTick || (label === undefined || label === null)) {
return;
}
var lineWidth, lineColor;
if (index === (typeof me.zeroLineIndex !== 'undefined' ? me.zeroLineIndex : 0)) {
// Draw the first index specially
lineWidth = gridLines.zeroLineWidth;
lineColor = gridLines.zeroLineColor;
} else {
lineWidth = helpers.getValueAtIndexOrDefault(gridLines.lineWidth, index);
lineColor = helpers.getValueAtIndexOrDefault(gridLines.color, index);
}
// Common properties
var tx1, ty1, tx2, ty2, x1, y1, x2, y2, labelX, labelY;
var textAlign, textBaseline = 'middle';
if (isHorizontal) {
if (!isRotated) {
textBaseline = options.position === 'top' ? 'bottom' : 'top';
}
textAlign = isRotated ? 'right' : 'center';
var xLineValue = me.getPixelForTick(index) + helpers.aliasPixel(lineWidth); // xvalues for grid lines
labelX = me.getPixelForTick(index, gridLines.offsetGridLines) + optionTicks.labelOffset; // x values for optionTicks (need to consider offsetLabel option)
labelY = (isRotated) ? me.top + 12 : options.position === 'top' ? me.bottom - tl : me.top + tl;
tx1 = tx2 = x1 = x2 = xLineValue;
ty1 = yTickStart;
ty2 = yTickEnd;
y1 = chartArea.top;
y2 = chartArea.bottom;
} else {
if (options.position === 'left') {
if (optionTicks.mirror) {
labelX = me.right + optionTicks.padding;
textAlign = 'left';
} else {
labelX = me.right - optionTicks.padding;
textAlign = 'right';
}
} else {
// right side
if (optionTicks.mirror) {
labelX = me.left - optionTicks.padding;
textAlign = 'right';
} else {
labelX = me.left + optionTicks.padding;
textAlign = 'left';
}
}
var yLineValue = me.getPixelForTick(index); // xvalues for grid lines
yLineValue += helpers.aliasPixel(lineWidth);
labelY = me.getPixelForTick(index, gridLines.offsetGridLines);
tx1 = xTickStart;
tx2 = xTickEnd;
x1 = chartArea.left;
x2 = chartArea.right;
ty1 = ty2 = y1 = y2 = yLineValue;
}
itemsToDraw.push({
tx1: tx1,
ty1: ty1,
tx2: tx2,
ty2: ty2,
x1: x1,
y1: y1,
x2: x2,
y2: y2,
labelX: labelX,
labelY: labelY,
glWidth: lineWidth,
glColor: lineColor,
rotation: -1 * labelRotationRadians,
label: label,
textBaseline: textBaseline,
textAlign: textAlign
});
});
// Draw all of the tick labels, tick marks, and grid lines at the correct places
helpers.each(itemsToDraw, function(itemToDraw) {
if (gridLines.display) {
context.lineWidth = itemToDraw.glWidth;
context.strokeStyle = itemToDraw.glColor;
context.beginPath();
if (gridLines.drawTicks) {
context.moveTo(itemToDraw.tx1, itemToDraw.ty1);
context.lineTo(itemToDraw.tx2, itemToDraw.ty2);
}
if (gridLines.drawOnChartArea) {
context.moveTo(itemToDraw.x1, itemToDraw.y1);
context.lineTo(itemToDraw.x2, itemToDraw.y2);
}
context.stroke();
}
if (optionTicks.display) {
context.save();
context.translate(itemToDraw.labelX, itemToDraw.labelY);
context.rotate(itemToDraw.rotation);
context.font = tickLabelFont;
context.textBaseline = itemToDraw.textBaseline;
context.textAlign = itemToDraw.textAlign;
var label = itemToDraw.label;
if (helpers.isArray(label)) {
for (var i = 0, y = 0; i < label.length; ++i) {
// We just make sure the multiline element is a string here..
context.fillText('' + label[i], 0, y);
// apply same lineSpacing as calculated @ L#320
y += (tickFontSize * 1.5);
}
} else {
context.fillText(label, 0, 0);
}
context.restore();
}
});
if (scaleLabel.display) {
// Draw the scale label
var scaleLabelX;
var scaleLabelY;
var rotation = 0;
if (isHorizontal) {
scaleLabelX = me.left + ((me.right - me.left) / 2); // midpoint of the width
scaleLabelY = options.position === 'bottom' ? me.bottom - (scaleLabelFontSize / 2) : me.top + (scaleLabelFontSize / 2);
} else {
var isLeft = options.position === 'left';
scaleLabelX = isLeft ? me.left + (scaleLabelFontSize / 2) : me.right - (scaleLabelFontSize / 2);
scaleLabelY = me.top + ((me.bottom - me.top) / 2);
rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
}
context.save();
context.translate(scaleLabelX, scaleLabelY);
context.rotate(rotation);
context.textAlign = 'center';
context.textBaseline = 'middle';
context.fillStyle = scaleLabelFontColor; // render in correct colour
context.font = scaleLabelFont;
context.fillText(scaleLabel.labelString, 0, 0);
context.restore();
}
if (gridLines.drawBorder) {
// Draw the line at the edge of the axis
context.lineWidth = helpers.getValueAtIndexOrDefault(gridLines.lineWidth, 0);
context.strokeStyle = helpers.getValueAtIndexOrDefault(gridLines.color, 0);
var x1 = me.left,
x2 = me.right,
y1 = me.top,
y2 = me.bottom;
var aliasPixel = helpers.aliasPixel(context.lineWidth);
if (isHorizontal) {
y1 = y2 = options.position === 'top' ? me.bottom : me.top;
y1 += aliasPixel;
y2 += aliasPixel;
} else {
x1 = x2 = options.position === 'left' ? me.right : me.left;
x1 += aliasPixel;
x2 += aliasPixel;
}
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.stroke();
}
}
});
};
},{}],31:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
Chart.scaleService = {
// Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
// use the new chart options to grab the correct scale
constructors: {},
// Use a registration function so that we can move to an ES6 map when we no longer need to support
// old browsers
// Scale config defaults
defaults: {},
registerScaleType: function(type, scaleConstructor, defaults) {
this.constructors[type] = scaleConstructor;
this.defaults[type] = helpers.clone(defaults);
},
getScaleConstructor: function(type) {
return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
},
getScaleDefaults: function(type) {
// Return the scale defaults merged with the global settings so that we always use the latest ones
return this.defaults.hasOwnProperty(type) ? helpers.scaleMerge(Chart.defaults.scale, this.defaults[type]) : {};
},
updateScaleDefaults: function(type, additions) {
var defaults = this.defaults;
if (defaults.hasOwnProperty(type)) {
defaults[type] = helpers.extend(defaults[type], additions);
}
},
addScalesToLayout: function(chartInstance) {
// Adds each scale to the chart.boxes array to be sized accordingly
helpers.each(chartInstance.scales, function(scale) {
Chart.layoutService.addBox(chartInstance, scale);
});
}
};
};
},{}],32:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
Chart.defaults.global.title = {
display: false,
position: 'top',
fullWidth: true, // marks that this box should take the full width of the canvas (pushing down other boxes)
fontStyle: 'bold',
padding: 10,
// actual title
text: ''
};
var noop = helpers.noop;
Chart.Title = Chart.Element.extend({
initialize: function(config) {
var me = this;
helpers.extend(me, config);
me.options = helpers.configMerge(Chart.defaults.global.title, config.options);
// Contains hit boxes for each dataset (in dataset order)
me.legendHitBoxes = [];
},
// These methods are ordered by lifecyle. Utilities then follow.
beforeUpdate: function () {
var chartOpts = this.chart.options;
if (chartOpts && chartOpts.title) {
this.options = helpers.configMerge(Chart.defaults.global.title, chartOpts.title);
}
},
update: function(maxWidth, maxHeight, margins) {
var me = this;
// Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
me.beforeUpdate();
// Absorb the master measurements
me.maxWidth = maxWidth;
me.maxHeight = maxHeight;
me.margins = margins;
// Dimensions
me.beforeSetDimensions();
me.setDimensions();
me.afterSetDimensions();
// Labels
me.beforeBuildLabels();
me.buildLabels();
me.afterBuildLabels();
// Fit
me.beforeFit();
me.fit();
me.afterFit();
//
me.afterUpdate();
return me.minSize;
},
afterUpdate: noop,
//
beforeSetDimensions: noop,
setDimensions: function() {
var me = this;
// Set the unconstrained dimension before label rotation
if (me.isHorizontal()) {
// Reset position before calculating rotation
me.width = me.maxWidth;
me.left = 0;
me.right = me.width;
} else {
me.height = me.maxHeight;
// Reset position before calculating rotation
me.top = 0;
me.bottom = me.height;
}
// Reset padding
me.paddingLeft = 0;
me.paddingTop = 0;
me.paddingRight = 0;
me.paddingBottom = 0;
// Reset minSize
me.minSize = {
width: 0,
height: 0
};
},
afterSetDimensions: noop,
//
beforeBuildLabels: noop,
buildLabels: noop,
afterBuildLabels: noop,
//
beforeFit: noop,
fit: function() {
var me = this,
ctx = me.ctx,
valueOrDefault = helpers.getValueOrDefault,
opts = me.options,
globalDefaults = Chart.defaults.global,
display = opts.display,
fontSize = valueOrDefault(opts.fontSize, globalDefaults.defaultFontSize),
minSize = me.minSize;
if (me.isHorizontal()) {
minSize.width = me.maxWidth; // fill all the width
minSize.height = display ? fontSize + (opts.padding * 2) : 0;
} else {
minSize.width = display ? fontSize + (opts.padding * 2) : 0;
minSize.height = me.maxHeight; // fill all the height
}
me.width = minSize.width;
me.height = minSize.height;
},
afterFit: noop,
// Shared Methods
isHorizontal: function() {
var pos = this.options.position;
return pos === "top" || pos === "bottom";
},
// Actualy draw the title block on the canvas
draw: function() {
var me = this,
ctx = me.ctx,
valueOrDefault = helpers.getValueOrDefault,
opts = me.options,
globalDefaults = Chart.defaults.global;
if (opts.display) {
var fontSize = valueOrDefault(opts.fontSize, globalDefaults.defaultFontSize),
fontStyle = valueOrDefault(opts.fontStyle, globalDefaults.defaultFontStyle),
fontFamily = valueOrDefault(opts.fontFamily, globalDefaults.defaultFontFamily),
titleFont = helpers.fontString(fontSize, fontStyle, fontFamily),
rotation = 0,
titleX,
titleY,
top = me.top,
left = me.left,
bottom = me.bottom,
right = me.right;
ctx.fillStyle = valueOrDefault(opts.fontColor, globalDefaults.defaultFontColor); // render in correct colour
ctx.font = titleFont;
// Horizontal
if (me.isHorizontal()) {
titleX = left + ((right - left) / 2); // midpoint of the width
titleY = top + ((bottom - top) / 2); // midpoint of the height
} else {
titleX = opts.position === 'left' ? left + (fontSize / 2) : right - (fontSize / 2);
titleY = top + ((bottom - top) / 2);
rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
}
ctx.save();
ctx.translate(titleX, titleY);
ctx.rotate(rotation);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(opts.text, 0, 0);
ctx.restore();
}
}
});
// Register the title plugin
Chart.plugins.register({
beforeInit: function(chartInstance) {
var opts = chartInstance.options;
var titleOpts = opts.title;
if (titleOpts) {
chartInstance.titleBlock = new Chart.Title({
ctx: chartInstance.chart.ctx,
options: titleOpts,
chart: chartInstance
});
Chart.layoutService.addBox(chartInstance, chartInstance.titleBlock);
}
}
});
};
},{}],33:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
Chart.defaults.global.tooltips = {
enabled: true,
custom: null,
mode: 'single',
backgroundColor: "rgba(0,0,0,0.8)",
titleFontStyle: "bold",
titleSpacing: 2,
titleMarginBottom: 6,
titleFontColor: "#fff",
titleAlign: "left",
bodySpacing: 2,
bodyFontColor: "#fff",
bodyAlign: "left",
footerFontStyle: "bold",
footerSpacing: 2,
footerMarginTop: 6,
footerFontColor: "#fff",
footerAlign: "left",
yPadding: 6,
xPadding: 6,
yAlign : 'center',
xAlign : 'center',
caretSize: 5,
cornerRadius: 6,
multiKeyBackground: '#fff',
callbacks: {
// Args are: (tooltipItems, data)
beforeTitle: helpers.noop,
title: function(tooltipItems, data) {
// Pick first xLabel for now
var title = '';
var labels = data.labels;
var labelCount = labels ? labels.length : 0;
if (tooltipItems.length > 0) {
var item = tooltipItems[0];
if (item.xLabel) {
title = item.xLabel;
} else if (labelCount > 0 && item.index < labelCount) {
title = labels[item.index];
}
}
return title;
},
afterTitle: helpers.noop,
// Args are: (tooltipItems, data)
beforeBody: helpers.noop,
// Args are: (tooltipItem, data)
beforeLabel: helpers.noop,
label: function(tooltipItem, data) {
var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || '';
return datasetLabel + ': ' + tooltipItem.yLabel;
},
labelColor: function(tooltipItem, chartInstance) {
var meta = chartInstance.getDatasetMeta(tooltipItem.datasetIndex);
var activeElement = meta.data[tooltipItem.index];
var view = activeElement._view;
return {
borderColor: view.borderColor,
backgroundColor: view.backgroundColor
};
},
afterLabel: helpers.noop,
// Args are: (tooltipItems, data)
afterBody: helpers.noop,
// Args are: (tooltipItems, data)
beforeFooter: helpers.noop,
footer: helpers.noop,
afterFooter: helpers.noop
}
};
// Helper to push or concat based on if the 2nd parameter is an array or not
function pushOrConcat(base, toPush) {
if (toPush) {
if (helpers.isArray(toPush)) {
//base = base.concat(toPush);
Array.prototype.push.apply(base, toPush);
} else {
base.push(toPush);
}
}
return base;
}
function getAveragePosition(elements) {
if (!elements.length) {
return false;
}
var i, len;
var xPositions = [];
var yPositions = [];
for (i = 0, len = elements.length; i < len; ++i) {
var el = elements[i];
if (el && el.hasValue()){
var pos = el.tooltipPosition();
xPositions.push(pos.x);
yPositions.push(pos.y);
}
}
var x = 0,
y = 0;
for (i = 0, len - xPositions.length; i < len; ++i) {
x += xPositions[i];
y += yPositions[i];
}
return {
x: Math.round(x / xPositions.length),
y: Math.round(y / xPositions.length)
};
}
// Private helper to create a tooltip iteam model
// @param element : the chart element (point, arc, bar) to create the tooltip item for
// @return : new tooltip item
function createTooltipItem(element) {
var xScale = element._xScale;
var yScale = element._yScale || element._scale; // handle radar || polarArea charts
var index = element._index,
datasetIndex = element._datasetIndex;
return {
xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
index: index,
datasetIndex: datasetIndex
};
}
Chart.Tooltip = Chart.Element.extend({
initialize: function() {
var me = this;
var globalDefaults = Chart.defaults.global;
var tooltipOpts = me._options;
var getValueOrDefault = helpers.getValueOrDefault;
helpers.extend(me, {
_model: {
// Positioning
xPadding: tooltipOpts.xPadding,
yPadding: tooltipOpts.yPadding,
xAlign : tooltipOpts.yAlign,
yAlign : tooltipOpts.xAlign,
// Body
bodyFontColor: tooltipOpts.bodyFontColor,
_bodyFontFamily: getValueOrDefault(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
_bodyFontStyle: getValueOrDefault(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
_bodyAlign: tooltipOpts.bodyAlign,
bodyFontSize: getValueOrDefault(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
bodySpacing: tooltipOpts.bodySpacing,
// Title
titleFontColor: tooltipOpts.titleFontColor,
_titleFontFamily: getValueOrDefault(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
_titleFontStyle: getValueOrDefault(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
titleFontSize: getValueOrDefault(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
_titleAlign: tooltipOpts.titleAlign,
titleSpacing: tooltipOpts.titleSpacing,
titleMarginBottom: tooltipOpts.titleMarginBottom,
// Footer
footerFontColor: tooltipOpts.footerFontColor,
_footerFontFamily: getValueOrDefault(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
_footerFontStyle: getValueOrDefault(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
footerFontSize: getValueOrDefault(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
_footerAlign: tooltipOpts.footerAlign,
footerSpacing: tooltipOpts.footerSpacing,
footerMarginTop: tooltipOpts.footerMarginTop,
// Appearance
caretSize: tooltipOpts.caretSize,
cornerRadius: tooltipOpts.cornerRadius,
backgroundColor: tooltipOpts.backgroundColor,
opacity: 0,
legendColorBackground: tooltipOpts.multiKeyBackground
}
});
},
// Get the title
// Args are: (tooltipItem, data)
getTitle: function() {
var me = this;
var opts = me._options;
var callbacks = opts.callbacks;
var beforeTitle = callbacks.beforeTitle.apply(me, arguments),
title = callbacks.title.apply(me, arguments),
afterTitle = callbacks.afterTitle.apply(me, arguments);
var lines = [];
lines = pushOrConcat(lines, beforeTitle);
lines = pushOrConcat(lines, title);
lines = pushOrConcat(lines, afterTitle);
return lines;
},
// Args are: (tooltipItem, data)
getBeforeBody: function() {
var lines = this._options.callbacks.beforeBody.apply(this, arguments);
return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : [];
},
// Args are: (tooltipItem, data)
getBody: function(tooltipItems, data) {
var me = this;
var callbacks = me._options.callbacks;
var bodyItems = [];
helpers.each(tooltipItems, function(tooltipItem) {
var bodyItem = {
before: [],
lines: [],
after: []
};
pushOrConcat(bodyItem.before, callbacks.beforeLabel.call(me, tooltipItem, data));
pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
pushOrConcat(bodyItem.after, callbacks.afterLabel.call(me, tooltipItem, data));
bodyItems.push(bodyItem);
});
return bodyItems;
},
// Args are: (tooltipItem, data)
getAfterBody: function() {
var lines = this._options.callbacks.afterBody.apply(this, arguments);
return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : [];
},
// Get the footer and beforeFooter and afterFooter lines
// Args are: (tooltipItem, data)
getFooter: function() {
var me = this;
var callbacks = me._options.callbacks;
var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
var footer = callbacks.footer.apply(me, arguments);
var afterFooter = callbacks.afterFooter.apply(me, arguments);
var lines = [];
lines = pushOrConcat(lines, beforeFooter);
lines = pushOrConcat(lines, footer);
lines = pushOrConcat(lines, afterFooter);
return lines;
},
update: function(changed) {
var me = this;
var opts = me._options;
var model = me._model;
var active = me._active;
var data = me._data;
var chartInstance = me._chartInstance;
var i, len;
if (active.length) {
model.opacity = 1;
var labelColors = [],
tooltipPosition = getAveragePosition(active);
var tooltipItems = [];
for (i = 0, len = active.length; i < len; ++i) {
tooltipItems.push(createTooltipItem(active[i]));
}
// If the user provided a sorting function, use it to modify the tooltip items
if (opts.itemSort) {
tooltipItems = tooltipItems.sort(opts.itemSort);
}
// If there is more than one item, show color items
if (active.length > 1) {
helpers.each(tooltipItems, function(tooltipItem) {
labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, chartInstance));
});
}
// Build the Text Lines
helpers.extend(model, {
title: me.getTitle(tooltipItems, data),
beforeBody: me.getBeforeBody(tooltipItems, data),
body: me.getBody(tooltipItems, data),
afterBody: me.getAfterBody(tooltipItems, data),
footer: me.getFooter(tooltipItems, data),
x: Math.round(tooltipPosition.x),
y: Math.round(tooltipPosition.y),
caretPadding: helpers.getValueOrDefault(tooltipPosition.padding, 2),
labelColors: labelColors
});
// We need to determine alignment of
var tooltipSize = me.getTooltipSize(model);
me.determineAlignment(tooltipSize); // Smart Tooltip placement to stay on the canvas
helpers.extend(model, me.getBackgroundPoint(model, tooltipSize));
} else {
me._model.opacity = 0;
}
if (changed && opts.custom) {
opts.custom.call(me, model);
}
return me;
},
getTooltipSize: function getTooltipSize(vm) {
var ctx = this._chart.ctx;
var size = {
height: vm.yPadding * 2, // Tooltip Padding
width: 0
};
// Count of all lines in the body
var body = vm.body;
var combinedBodyLength = body.reduce(function(count, bodyItem) {
return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
}, 0);
combinedBodyLength += vm.beforeBody.length + vm.afterBody.length;
var titleLineCount = vm.title.length;
var footerLineCount = vm.footer.length;
var titleFontSize = vm.titleFontSize,
bodyFontSize = vm.bodyFontSize,
footerFontSize = vm.footerFontSize;
size.height += titleLineCount * titleFontSize; // Title Lines
size.height += (titleLineCount - 1) * vm.titleSpacing; // Title Line Spacing
size.height += titleLineCount ? vm.titleMarginBottom : 0; // Title's bottom Margin
size.height += combinedBodyLength * bodyFontSize; // Body Lines
size.height += combinedBodyLength ? (combinedBodyLength - 1) * vm.bodySpacing : 0; // Body Line Spacing
size.height += footerLineCount ? vm.footerMarginTop : 0; // Footer Margin
size.height += footerLineCount * (footerFontSize); // Footer Lines
size.height += footerLineCount ? (footerLineCount - 1) * vm.footerSpacing : 0; // Footer Line Spacing
// Title width
var widthPadding = 0;
var maxLineWidth = function(line) {
size.width = Math.max(size.width, ctx.measureText(line).width + widthPadding);
};
ctx.font = helpers.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
helpers.each(vm.title, maxLineWidth);
// Body width
ctx.font = helpers.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
helpers.each(vm.beforeBody.concat(vm.afterBody), maxLineWidth);
// Body lines may include some extra width due to the color box
widthPadding = body.length > 1 ? (bodyFontSize + 2) : 0;
helpers.each(body, function(bodyItem) {
helpers.each(bodyItem.before, maxLineWidth);
helpers.each(bodyItem.lines, maxLineWidth);
helpers.each(bodyItem.after, maxLineWidth);
});
// Reset back to 0
widthPadding = 0;
// Footer width
ctx.font = helpers.fontString(footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
helpers.each(vm.footer, maxLineWidth);
// Add padding
size.width += 2 * vm.xPadding;
return size;
},
determineAlignment: function determineAlignment(size) {
var me = this;
var model = me._model;
var chart = me._chart;
var chartArea = me._chartInstance.chartArea;
if (model.y < size.height) {
model.yAlign = 'top';
} else if (model.y > (chart.height - size.height)) {
model.yAlign = 'bottom';
}
var lf, rf; // functions to determine left, right alignment
var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
var midX = (chartArea.left + chartArea.right) / 2;
var midY = (chartArea.top + chartArea.bottom) / 2;
if (model.yAlign === 'center') {
lf = function(x) {
return x <= midX;
};
rf = function(x) {
return x > midX;
};
} else {
lf = function(x) {
return x <= (size.width / 2);
};
rf = function(x) {
return x >= (chart.width - (size.width / 2));
};
}
olf = function(x) {
return x + size.width > chart.width;
};
orf = function(x) {
return x - size.width < 0;
};
yf = function(y) {
return y <= midY ? 'top' : 'bottom';
};
if (lf(model.x)) {
model.xAlign = 'left';
// Is tooltip too wide and goes over the right side of the chart.?
if (olf(model.x)) {
model.xAlign = 'center';
model.yAlign = yf(model.y);
}
} else if (rf(model.x)) {
model.xAlign = 'right';
// Is tooltip too wide and goes outside left edge of canvas?
if (orf(model.x)) {
model.xAlign = 'center';
model.yAlign = yf(model.y);
}
}
},
getBackgroundPoint: function getBackgroundPoint(vm, size) {
// Background Position
var pt = {
x: vm.x,
y: vm.y
};
var caretSize = vm.caretSize,
caretPadding = vm.caretPadding,
cornerRadius = vm.cornerRadius,
xAlign = vm.xAlign,
yAlign = vm.yAlign,
paddingAndSize = caretSize + caretPadding,
radiusAndPadding = cornerRadius + caretPadding;
if (xAlign === 'right') {
pt.x -= size.width;
} else if (xAlign === 'center') {
pt.x -= (size.width / 2);
}
if (yAlign === 'top') {
pt.y += paddingAndSize;
} else if (yAlign === 'bottom') {
pt.y -= size.height + paddingAndSize;
} else {
pt.y -= (size.height / 2);
}
if (yAlign === 'center') {
if (xAlign === 'left') {
pt.x += paddingAndSize;
} else if (xAlign === 'right') {
pt.x -= paddingAndSize;
}
} else {
if (xAlign === 'left') {
pt.x -= radiusAndPadding;
} else if (xAlign === 'right') {
pt.x += radiusAndPadding;
}
}
return pt;
},
drawCaret: function drawCaret(tooltipPoint, size, opacity, caretPadding) {
var vm = this._view;
var ctx = this._chart.ctx;
var x1, x2, x3;
var y1, y2, y3;
var caretSize = vm.caretSize;
var cornerRadius = vm.cornerRadius;
var xAlign = vm.xAlign,
yAlign = vm.yAlign;
var ptX = tooltipPoint.x,
ptY = tooltipPoint.y;
var width = size.width,
height = size.height;
if (yAlign === 'center') {
// Left or right side
if (xAlign === 'left') {
x1 = ptX;
x2 = x1 - caretSize;
x3 = x1;
} else {
x1 = ptX + width;
x2 = x1 + caretSize;
x3 = x1;
}
y2 = ptY + (height / 2);
y1 = y2 - caretSize;
y3 = y2 + caretSize;
} else {
if (xAlign === 'left') {
x1 = ptX + cornerRadius;
x2 = x1 + caretSize;
x3 = x2 + caretSize;
} else if (xAlign === 'right') {
x1 = ptX + width - cornerRadius;
x2 = x1 - caretSize;
x3 = x2 - caretSize;
} else {
x2 = ptX + (width / 2);
x1 = x2 - caretSize;
x3 = x2 + caretSize;
}
if (yAlign === 'top') {
y1 = ptY;
y2 = y1 - caretSize;
y3 = y1;
} else {
y1 = ptY + height;
y2 = y1 + caretSize;
y3 = y1;
}
}
var bgColor = helpers.color(vm.backgroundColor);
ctx.fillStyle = bgColor.alpha(opacity * bgColor.alpha()).rgbString();
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineTo(x3, y3);
ctx.closePath();
ctx.fill();
},
drawTitle: function drawTitle(pt, vm, ctx, opacity) {
var title = vm.title;
if (title.length) {
ctx.textAlign = vm._titleAlign;
ctx.textBaseline = "top";
var titleFontSize = vm.titleFontSize,
titleSpacing = vm.titleSpacing;
var titleFontColor = helpers.color(vm.titleFontColor);
ctx.fillStyle = titleFontColor.alpha(opacity * titleFontColor.alpha()).rgbString();
ctx.font = helpers.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
var i, len;
for (i = 0, len = title.length; i < len; ++i) {
ctx.fillText(title[i], pt.x, pt.y);
pt.y += titleFontSize + titleSpacing; // Line Height and spacing
if (i + 1 === title.length) {
pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
}
}
}
},
drawBody: function drawBody(pt, vm, ctx, opacity) {
var bodyFontSize = vm.bodyFontSize;
var bodySpacing = vm.bodySpacing;
var body = vm.body;
ctx.textAlign = vm._bodyAlign;
ctx.textBaseline = "top";
var bodyFontColor = helpers.color(vm.bodyFontColor);
var textColor = bodyFontColor.alpha(opacity * bodyFontColor.alpha()).rgbString();
ctx.fillStyle = textColor;
ctx.font = helpers.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
// Before Body
var xLinePadding = 0;
var fillLineOfText = function(line) {
ctx.fillText(line, pt.x + xLinePadding, pt.y);
pt.y += bodyFontSize + bodySpacing;
};
// Before body lines
helpers.each(vm.beforeBody, fillLineOfText);
var drawColorBoxes = body.length > 1;
xLinePadding = drawColorBoxes ? (bodyFontSize + 2) : 0;
// Draw body lines now
helpers.each(body, function(bodyItem, i) {
helpers.each(bodyItem.before, fillLineOfText);
helpers.each(bodyItem.lines, function(line) {
// Draw Legend-like boxes if needed
if (drawColorBoxes) {
// Fill a white rect so that colours merge nicely if the opacity is < 1
ctx.fillStyle = helpers.color(vm.legendColorBackground).alpha(opacity).rgbaString();
ctx.fillRect(pt.x, pt.y, bodyFontSize, bodyFontSize);
// Border
ctx.strokeStyle = helpers.color(vm.labelColors[i].borderColor).alpha(opacity).rgbaString();
ctx.strokeRect(pt.x, pt.y, bodyFontSize, bodyFontSize);
// Inner square
ctx.fillStyle = helpers.color(vm.labelColors[i].backgroundColor).alpha(opacity).rgbaString();
ctx.fillRect(pt.x + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
ctx.fillStyle = textColor;
}
fillLineOfText(line);
});
helpers.each(bodyItem.after, fillLineOfText);
});
// Reset back to 0 for after body
xLinePadding = 0;
// After body lines
helpers.each(vm.afterBody, fillLineOfText);
pt.y -= bodySpacing; // Remove last body spacing
},
drawFooter: function drawFooter(pt, vm, ctx, opacity) {
var footer = vm.footer;
if (footer.length) {
pt.y += vm.footerMarginTop;
ctx.textAlign = vm._footerAlign;
ctx.textBaseline = "top";
var footerFontColor = helpers.color(vm.footerFontColor);
ctx.fillStyle = footerFontColor.alpha(opacity * footerFontColor.alpha()).rgbString();
ctx.font = helpers.fontString(vm.footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
helpers.each(footer, function(line) {
ctx.fillText(line, pt.x, pt.y);
pt.y += vm.footerFontSize + vm.footerSpacing;
});
}
},
draw: function draw() {
var ctx = this._chart.ctx;
var vm = this._view;
if (vm.opacity === 0) {
return;
}
var tooltipSize = this.getTooltipSize(vm);
var pt = {
x: vm.x,
y: vm.y
};
// IE11/Edge does not like very small opacities, so snap to 0
var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
if (this._options.enabled) {
// Draw Background
var bgColor = helpers.color(vm.backgroundColor);
ctx.fillStyle = bgColor.alpha(opacity * bgColor.alpha()).rgbString();
helpers.drawRoundedRectangle(ctx, pt.x, pt.y, tooltipSize.width, tooltipSize.height, vm.cornerRadius);
ctx.fill();
// Draw Caret
this.drawCaret(pt, tooltipSize, opacity, vm.caretPadding);
// Draw Title, Body, and Footer
pt.x += vm.xPadding;
pt.y += vm.yPadding;
// Titles
this.drawTitle(pt, vm, ctx, opacity);
// Body
this.drawBody(pt, vm, ctx, opacity);
// Footer
this.drawFooter(pt, vm, ctx, opacity);
}
}
});
};
},{}],34:[function(require,module,exports){
"use strict";
module.exports = function(Chart, moment) {
var helpers = Chart.helpers,
globalOpts = Chart.defaults.global;
globalOpts.elements.arc = {
backgroundColor: globalOpts.defaultColor,
borderColor: "#fff",
borderWidth: 2
};
Chart.elements.Arc = Chart.Element.extend({
inLabelRange: function(mouseX) {
var vm = this._view;
if (vm) {
return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
} else {
return false;
}
},
inRange: function(chartX, chartY) {
var vm = this._view;
if (vm) {
var pointRelativePosition = helpers.getAngleFromPoint(vm, {
x: chartX,
y: chartY
}),
angle = pointRelativePosition.angle,
distance = pointRelativePosition.distance;
//Sanitise angle range
var startAngle = vm.startAngle;
var endAngle = vm.endAngle;
while (endAngle < startAngle) {
endAngle += 2.0 * Math.PI;
}
while (angle > endAngle) {
angle -= 2.0 * Math.PI;
}
while (angle < startAngle) {
angle += 2.0 * Math.PI;
}
//Check if within the range of the open/close angle
var betweenAngles = (angle >= startAngle && angle <= endAngle),
withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
return (betweenAngles && withinRadius);
} else {
return false;
}
},
tooltipPosition: function() {
var vm = this._view;
var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2),
rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
return {
x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
};
},
draw: function() {
var ctx = this._chart.ctx,
vm = this._view,
sA = vm.startAngle,
eA = vm.endAngle;
ctx.beginPath();
ctx.arc(vm.x, vm.y, vm.outerRadius, sA, eA);
ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);
ctx.closePath();
ctx.strokeStyle = vm.borderColor;
ctx.lineWidth = vm.borderWidth;
ctx.fillStyle = vm.backgroundColor;
ctx.fill();
ctx.lineJoin = 'bevel';
if (vm.borderWidth) {
ctx.stroke();
}
}
});
};
},{}],35:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
var globalDefaults = Chart.defaults.global;
Chart.defaults.global.elements.line = {
tension: 0.4,
backgroundColor: globalDefaults.defaultColor,
borderWidth: 3,
borderColor: globalDefaults.defaultColor,
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
fill: true // do we fill in the area between the line and its base axis
};
Chart.elements.Line = Chart.Element.extend({
lineToNextPoint: function(previousPoint, point, nextPoint, skipHandler, previousSkipHandler) {
var me = this;
var ctx = me._chart.ctx;
var spanGaps = me._view ? me._view.spanGaps : false;
if (point._view.skip && !spanGaps) {
skipHandler.call(me, previousPoint, point, nextPoint);
} else if (previousPoint._view.skip && !spanGaps) {
previousSkipHandler.call(me, previousPoint, point, nextPoint);
} else if (point._view.tension === 0) {
ctx.lineTo(point._view.x, point._view.y);
} else {
// Line between points
ctx.bezierCurveTo(
previousPoint._view.controlPointNextX,
previousPoint._view.controlPointNextY,
point._view.controlPointPreviousX,
point._view.controlPointPreviousY,
point._view.x,
point._view.y
);
}
},
draw: function() {
var me = this;
var vm = me._view;
var ctx = me._chart.ctx;
var first = me._children[0];
var last = me._children[me._children.length - 1];
function loopBackToStart(drawLineToCenter) {
if (!first._view.skip && !last._view.skip) {
// Draw a bezier line from last to first
ctx.bezierCurveTo(
last._view.controlPointNextX,
last._view.controlPointNextY,
first._view.controlPointPreviousX,
first._view.controlPointPreviousY,
first._view.x,
first._view.y
);
} else if (drawLineToCenter) {
// Go to center
ctx.lineTo(me._view.scaleZero.x, me._view.scaleZero.y);
}
}
ctx.save();
// If we had points and want to fill this line, do so.
if (me._children.length > 0 && vm.fill) {
// Draw the background first (so the border is always on top)
ctx.beginPath();
helpers.each(me._children, function(point, index) {
var previous = helpers.previousItem(me._children, index);
var next = helpers.nextItem(me._children, index);
// First point moves to it's starting position no matter what
if (index === 0) {
if (me._loop) {
ctx.moveTo(vm.scaleZero.x, vm.scaleZero.y);
} else {
ctx.moveTo(point._view.x, vm.scaleZero);
}
if (point._view.skip) {
if (!me._loop) {
ctx.moveTo(next._view.x, me._view.scaleZero);
}
} else {
ctx.lineTo(point._view.x, point._view.y);
}
} else {
me.lineToNextPoint(previous, point, next, function(previousPoint, point, nextPoint) {
if (me._loop) {
// Go to center
ctx.lineTo(me._view.scaleZero.x, me._view.scaleZero.y);
} else {
ctx.lineTo(previousPoint._view.x, me._view.scaleZero);
ctx.moveTo(nextPoint._view.x, me._view.scaleZero);
}
}, function(previousPoint, point) {
// If we skipped the last point, draw a line to ourselves so that the fill is nice
ctx.lineTo(point._view.x, point._view.y);
});
}
}, me);
// For radial scales, loop back around to the first point
if (me._loop) {
loopBackToStart(true);
} else {
//Round off the line by going to the base of the chart, back to the start, then fill.
ctx.lineTo(me._children[me._children.length - 1]._view.x, vm.scaleZero);
ctx.lineTo(me._children[0]._view.x, vm.scaleZero);
}
ctx.fillStyle = vm.backgroundColor || globalDefaults.defaultColor;
ctx.closePath();
ctx.fill();
}
var globalOptionLineElements = globalDefaults.elements.line;
// Now draw the line between all the points with any borders
ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
// IE 9 and 10 do not support line dash
if (ctx.setLineDash) {
ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
}
ctx.lineDashOffset = vm.borderDashOffset || globalOptionLineElements.borderDashOffset;
ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
ctx.lineWidth = vm.borderWidth || globalOptionLineElements.borderWidth;
ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
ctx.beginPath();
helpers.each(me._children, function(point, index) {
var previous = helpers.previousItem(me._children, index);
var next = helpers.nextItem(me._children, index);
if (index === 0) {
ctx.moveTo(point._view.x, point._view.y);
} else {
me.lineToNextPoint(previous, point, next, function(previousPoint, point, nextPoint) {
ctx.moveTo(nextPoint._view.x, nextPoint._view.y);
}, function(previousPoint, point) {
// If we skipped the last point, move up to our point preventing a line from being drawn
ctx.moveTo(point._view.x, point._view.y);
});
}
}, me);
if (me._loop && me._children.length > 0) {
loopBackToStart();
}
ctx.stroke();
ctx.restore();
}
});
};
},{}],36:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers,
globalOpts = Chart.defaults.global,
defaultColor = globalOpts.defaultColor;
globalOpts.elements.point = {
radius: 3,
pointStyle: 'circle',
backgroundColor: defaultColor,
borderWidth: 1,
borderColor: defaultColor,
// Hover
hitRadius: 1,
hoverRadius: 4,
hoverBorderWidth: 1
};
Chart.elements.Point = Chart.Element.extend({
inRange: function(mouseX, mouseY) {
var vm = this._view;
return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
},
inLabelRange: function(mouseX) {
var vm = this._view;
return vm ? (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hitRadius, 2)) : false;
},
tooltipPosition: function() {
var vm = this._view;
return {
x: vm.x,
y: vm.y,
padding: vm.radius + vm.borderWidth
};
},
draw: function() {
var vm = this._view;
var ctx = this._chart.ctx;
var pointStyle = vm.pointStyle;
var radius = vm.radius;
var x = vm.x;
var y = vm.y;
var type, edgeLength, xOffset, yOffset, height, size;
if (vm.skip) {
return;
}
if (typeof pointStyle === 'object') {
type = pointStyle.toString();
if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
ctx.drawImage(pointStyle, x - pointStyle.width / 2, y - pointStyle.height / 2);
return;
}
}
if (isNaN(radius) || radius <= 0) {
return;
}
ctx.strokeStyle = vm.borderColor || defaultColor;
ctx.lineWidth = helpers.getValueOrDefault(vm.borderWidth, globalOpts.elements.point.borderWidth);
ctx.fillStyle = vm.backgroundColor || defaultColor;
switch (pointStyle) {
// Default includes circle
default:
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
break;
case 'triangle':
ctx.beginPath();
edgeLength = 3 * radius / Math.sqrt(3);
height = edgeLength * Math.sqrt(3) / 2;
ctx.moveTo(x - edgeLength / 2, y + height / 3);
ctx.lineTo(x + edgeLength / 2, y + height / 3);
ctx.lineTo(x, y - 2 * height / 3);
ctx.closePath();
ctx.fill();
break;
case 'rect':
size = 1 / Math.SQRT2 * radius;
ctx.fillRect(x - size, y - size, 2 * size, 2 * size);
ctx.strokeRect(x - size, y - size, 2 * size, 2 * size);
break;
case 'rectRot':
size = 1 / Math.SQRT2 * radius;
ctx.beginPath();
ctx.moveTo(x - size, y);
ctx.lineTo(x, y + size);
ctx.lineTo(x + size, y);
ctx.lineTo(x, y - size);
ctx.closePath();
ctx.fill();
break;
case 'cross':
ctx.beginPath();
ctx.moveTo(x, y + radius);
ctx.lineTo(x, y - radius);
ctx.moveTo(x - radius, y);
ctx.lineTo(x + radius, y);
ctx.closePath();
break;
case 'crossRot':
ctx.beginPath();
xOffset = Math.cos(Math.PI / 4) * radius;
yOffset = Math.sin(Math.PI / 4) * radius;
ctx.moveTo(x - xOffset, y - yOffset);
ctx.lineTo(x + xOffset, y + yOffset);
ctx.moveTo(x - xOffset, y + yOffset);
ctx.lineTo(x + xOffset, y - yOffset);
ctx.closePath();
break;
case 'star':
ctx.beginPath();
ctx.moveTo(x, y + radius);
ctx.lineTo(x, y - radius);
ctx.moveTo(x - radius, y);
ctx.lineTo(x + radius, y);
xOffset = Math.cos(Math.PI / 4) * radius;
yOffset = Math.sin(Math.PI / 4) * radius;
ctx.moveTo(x - xOffset, y - yOffset);
ctx.lineTo(x + xOffset, y + yOffset);
ctx.moveTo(x - xOffset, y + yOffset);
ctx.lineTo(x + xOffset, y - yOffset);
ctx.closePath();
break;
case 'line':
ctx.beginPath();
ctx.moveTo(x - radius, y);
ctx.lineTo(x + radius, y);
ctx.closePath();
break;
case 'dash':
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + radius, y);
ctx.closePath();
break;
}
ctx.stroke();
}
});
};
},{}],37:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers,
globalOpts = Chart.defaults.global;
globalOpts.elements.rectangle = {
backgroundColor: globalOpts.defaultColor,
borderWidth: 0,
borderColor: globalOpts.defaultColor,
borderSkipped: 'bottom'
};
Chart.elements.Rectangle = Chart.Element.extend({
draw: function() {
var ctx = this._chart.ctx;
var vm = this._view;
var halfWidth = vm.width / 2,
leftX = vm.x - halfWidth,
rightX = vm.x + halfWidth,
top = vm.base - (vm.base - vm.y),
halfStroke = vm.borderWidth / 2;
// Canvas doesn't allow us to stroke inside the width so we can
// adjust the sizes to fit if we're setting a stroke on the line
if (vm.borderWidth) {
leftX += halfStroke;
rightX -= halfStroke;
top += halfStroke;
}
ctx.beginPath();
ctx.fillStyle = vm.backgroundColor;
ctx.strokeStyle = vm.borderColor;
ctx.lineWidth = vm.borderWidth;
// Corner points, from bottom-left to bottom-right clockwise
// | 1 2 |
// | 0 3 |
var corners = [
[leftX, vm.base],
[leftX, top],
[rightX, top],
[rightX, vm.base]
];
// Find first (starting) corner with fallback to 'bottom'
var borders = ['bottom', 'left', 'top', 'right'];
var startCorner = borders.indexOf(vm.borderSkipped, 0);
if (startCorner === -1)
startCorner = 0;
function cornerAt(index) {
return corners[(startCorner + index) % 4];
}
// Draw rectangle from 'startCorner'
ctx.moveTo.apply(ctx, cornerAt(0));
for (var i = 1; i < 4; i++)
ctx.lineTo.apply(ctx, cornerAt(i));
ctx.fill();
if (vm.borderWidth) {
ctx.stroke();
}
},
height: function() {
var vm = this._view;
return vm.base - vm.y;
},
inRange: function(mouseX, mouseY) {
var vm = this._view;
return vm ?
(vm.y < vm.base ?
(mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) && (mouseY >= vm.y && mouseY <= vm.base) :
(mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) && (mouseY >= vm.base && mouseY <= vm.y)) :
false;
},
inLabelRange: function(mouseX) {
var vm = this._view;
return vm ? (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) : false;
},
tooltipPosition: function() {
var vm = this._view;
return {
x: vm.x,
y: vm.y
};
}
});
};
},{}],38:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
// Default config for a category scale
var defaultConfig = {
position: "bottom"
};
var DatasetScale = Chart.Scale.extend({
// Implement this so that
determineDataLimits: function() {
var me = this;
me.minIndex = 0;
me.maxIndex = me.chart.data.labels.length - 1;
var findIndex;
if (me.options.ticks.min !== undefined) {
// user specified min value
findIndex = helpers.indexOf(me.chart.data.labels, me.options.ticks.min);
me.minIndex = findIndex !== -1 ? findIndex : me.minIndex;
}
if (me.options.ticks.max !== undefined) {
// user specified max value
findIndex = helpers.indexOf(me.chart.data.labels, me.options.ticks.max);
me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex;
}
me.min = me.chart.data.labels[me.minIndex];
me.max = me.chart.data.labels[me.maxIndex];
},
buildTicks: function(index) {
var me = this;
// If we are viewing some subset of labels, slice the original array
me.ticks = (me.minIndex === 0 && me.maxIndex === me.chart.data.labels.length - 1) ? me.chart.data.labels : me.chart.data.labels.slice(me.minIndex, me.maxIndex + 1);
},
getLabelForIndex: function(index, datasetIndex) {
return this.ticks[index];
},
// Used to get data value locations. Value can either be an index or a numerical value
getPixelForValue: function(value, index, datasetIndex, includeOffset) {
var me = this;
// 1 is added because we need the length but we have the indexes
var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - ((me.options.gridLines.offsetGridLines) ? 0 : 1)), 1);
if (me.isHorizontal()) {
var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
var valueWidth = innerWidth / offsetAmt;
var widthOffset = (valueWidth * (index - me.minIndex)) + me.paddingLeft;
if (me.options.gridLines.offsetGridLines && includeOffset) {
widthOffset += (valueWidth / 2);
}
return me.left + Math.round(widthOffset);
} else {
var innerHeight = me.height - (me.paddingTop + me.paddingBottom);
var valueHeight = innerHeight / offsetAmt;
var heightOffset = (valueHeight * (index - me.minIndex)) + me.paddingTop;
if (me.options.gridLines.offsetGridLines && includeOffset) {
heightOffset += (valueHeight / 2);
}
return me.top + Math.round(heightOffset);
}
},
getPixelForTick: function(index, includeOffset) {
return this.getPixelForValue(this.ticks[index], index + this.minIndex, null, includeOffset);
},
getValueForPixel: function(pixel) {
var me = this;
var value;
var offsetAmt = Math.max((me.ticks.length - ((me.options.gridLines.offsetGridLines) ? 0 : 1)), 1);
var horz = me.isHorizontal();
var innerDimension = horz ? me.width - (me.paddingLeft + me.paddingRight) : me.height - (me.paddingTop + me.paddingBottom);
var valueDimension = innerDimension / offsetAmt;
if (me.options.gridLines.offsetGridLines) {
pixel -= (valueDimension / 2);
}
pixel -= horz ? me.paddingLeft : me.paddingTop;
if (pixel <= 0) {
value = 0;
} else {
value = Math.round(pixel / valueDimension);
}
return value;
}
});
Chart.scaleService.registerScaleType("category", DatasetScale, defaultConfig);
};
},{}],39:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
var defaultConfig = {
position: "left",
ticks: {
callback: function(tickValue, index, ticks) {
// If we have lots of ticks, don't use the ones
var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
// If we have a number like 2.5 as the delta, figure out how many decimal places we need
if (Math.abs(delta) > 1) {
if (tickValue !== Math.floor(tickValue)) {
// not an integer
delta = tickValue - Math.floor(tickValue);
}
}
var logDelta = helpers.log10(Math.abs(delta));
var tickString = '';
if (tickValue !== 0) {
var numDecimal = -1 * Math.floor(logDelta);
numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
tickString = tickValue.toFixed(numDecimal);
} else {
tickString = '0'; // never show decimal places for 0
}
return tickString;
}
}
};
var LinearScale = Chart.LinearScaleBase.extend({
determineDataLimits: function() {
var me = this;
var opts = me.options;
var tickOpts = opts.ticks;
var chart = me.chart;
var data = chart.data;
var datasets = data.datasets;
var isHorizontal = me.isHorizontal();
function IDMatches(meta) {
return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
}
// First Calculate the range
me.min = null;
me.max = null;
if (opts.stacked) {
var valuesPerType = {};
var hasPositiveValues = false;
var hasNegativeValues = false;
helpers.each(datasets, function(dataset, datasetIndex) {
var meta = chart.getDatasetMeta(datasetIndex);
if (valuesPerType[meta.type] === undefined) {
valuesPerType[meta.type] = {
positiveValues: [],
negativeValues: []
};
}
// Store these per type
var positiveValues = valuesPerType[meta.type].positiveValues;
var negativeValues = valuesPerType[meta.type].negativeValues;
if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
helpers.each(dataset.data, function(rawValue, index) {
var value = +me.getRightValue(rawValue);
if (isNaN(value) || meta.data[index].hidden) {
return;
}
positiveValues[index] = positiveValues[index] || 0;
negativeValues[index] = negativeValues[index] || 0;
if (opts.relativePoints) {
positiveValues[index] = 100;
} else {
if (value < 0) {
hasNegativeValues = true;
negativeValues[index] += value;
} else {
hasPositiveValues = true;
positiveValues[index] += value;
}
}
});
}
});
helpers.each(valuesPerType, function(valuesForType) {
var values = valuesForType.positiveValues.concat(valuesForType.negativeValues);
var minVal = helpers.min(values);
var maxVal = helpers.max(values);
me.min = me.min === null ? minVal : Math.min(me.min, minVal);
me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
});
} else {
helpers.each(datasets, function(dataset, datasetIndex) {
var meta = chart.getDatasetMeta(datasetIndex);
if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
helpers.each(dataset.data, function(rawValue, index) {
var value = +me.getRightValue(rawValue);
if (isNaN(value) || meta.data[index].hidden) {
return;
}
if (me.min === null) {
me.min = value;
} else if (value < me.min) {
me.min = value;
}
if (me.max === null) {
me.max = value;
} else if (value > me.max) {
me.max = value;
}
});
}
});
}
// Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
this.handleTickRangeOptions();
},
getTickLimit: function() {
var maxTicks;
var me = this;
var tickOpts = me.options.ticks;
if (me.isHorizontal()) {
maxTicks = Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.width / 50));
} else {
// The factor of 2 used to scale the font size has been experimentally determined.
var tickFontSize = helpers.getValueOrDefault(tickOpts.fontSize, Chart.defaults.global.defaultFontSize);
maxTicks = Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.height / (2 * tickFontSize)));
}
return maxTicks;
},
// Called after the ticks are built. We need
handleDirectionalChanges: function() {
if (!this.isHorizontal()) {
// We are in a vertical orientation. The top value is the highest. So reverse the array
this.ticks.reverse();
}
},
getLabelForIndex: function(index, datasetIndex) {
return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
},
// Utils
getPixelForValue: function(value, index, datasetIndex, includeOffset) {
// This must be called after fit has been run so that
// this.left, this.top, this.right, and this.bottom have been defined
var me = this;
var paddingLeft = me.paddingLeft;
var paddingBottom = me.paddingBottom;
var start = me.start;
var rightValue = +me.getRightValue(value);
var pixel;
var innerDimension;
var range = me.end - start;
if (me.isHorizontal()) {
innerDimension = me.width - (paddingLeft + me.paddingRight);
pixel = me.left + (innerDimension / range * (rightValue - start));
return Math.round(pixel + paddingLeft);
} else {
innerDimension = me.height - (me.paddingTop + paddingBottom);
pixel = (me.bottom - paddingBottom) - (innerDimension / range * (rightValue - start));
return Math.round(pixel);
}
},
getValueForPixel: function(pixel) {
var me = this;
var isHorizontal = me.isHorizontal();
var paddingLeft = me.paddingLeft;
var paddingBottom = me.paddingBottom;
var innerDimension = isHorizontal ? me.width - (paddingLeft + me.paddingRight) : me.height - (me.paddingTop + paddingBottom);
var offset = (isHorizontal ? pixel - me.left - paddingLeft : me.bottom - paddingBottom - pixel) / innerDimension;
return me.start + ((me.end - me.start) * offset);
},
getPixelForTick: function(index, includeOffset) {
return this.getPixelForValue(this.ticksAsNumbers[index], null, null, includeOffset);
}
});
Chart.scaleService.registerScaleType("linear", LinearScale, defaultConfig);
};
},{}],40:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers,
noop = helpers.noop;
Chart.LinearScaleBase = Chart.Scale.extend({
handleTickRangeOptions: function() {
var me = this;
var opts = me.options;
var tickOpts = opts.ticks;
// If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
// do nothing since that would make the chart weird. If the user really wants a weird chart
// axis, they can manually override it
if (tickOpts.beginAtZero) {
var minSign = helpers.sign(me.min);
var maxSign = helpers.sign(me.max);
if (minSign < 0 && maxSign < 0) {
// move the top up to 0
me.max = 0;
} else if (minSign > 0 && maxSign > 0) {
// move the botttom down to 0
me.min = 0;
}
}
if (tickOpts.min !== undefined) {
me.min = tickOpts.min;
} else if (tickOpts.suggestedMin !== undefined) {
me.min = Math.min(me.min, tickOpts.suggestedMin);
}
if (tickOpts.max !== undefined) {
me.max = tickOpts.max;
} else if (tickOpts.suggestedMax !== undefined) {
me.max = Math.max(me.max, tickOpts.suggestedMax);
}
if (me.min === me.max) {
me.max++;
if (!tickOpts.beginAtZero) {
me.min--;
}
}
},
getTickLimit: noop,
handleDirectionalChanges: noop,
buildTicks: function() {
var me = this;
var opts = me.options;
var tickOpts = opts.ticks;
var getValueOrDefault = helpers.getValueOrDefault;
var isHorizontal = me.isHorizontal();
var ticks = me.ticks = [];
// Figure out what the max number of ticks we can support it is based on the size of
// the axis area. For now, we say that the minimum tick spacing in pixels must be 50
// We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
// the graph
var maxTicks = me.getTickLimit();
// Make sure we always have at least 2 ticks
maxTicks = Math.max(2, maxTicks);
// To get a "nice" value for the tick spacing, we will use the appropriately named
// "nice number" algorithm. See http://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
// for details.
var spacing;
var fixedStepSizeSet = (tickOpts.fixedStepSize && tickOpts.fixedStepSize > 0) || (tickOpts.stepSize && tickOpts.stepSize > 0);
if (fixedStepSizeSet) {
spacing = getValueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize);
} else {
var niceRange = helpers.niceNum(me.max - me.min, false);
spacing = helpers.niceNum(niceRange / (maxTicks - 1), true);
}
var niceMin = Math.floor(me.min / spacing) * spacing;
var niceMax = Math.ceil(me.max / spacing) * spacing;
var numSpaces = (niceMax - niceMin) / spacing;
// If very close to our rounded value, use it.
if (helpers.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
numSpaces = Math.round(numSpaces);
} else {
numSpaces = Math.ceil(numSpaces);
}
// Put the values into the ticks array
ticks.push(tickOpts.min !== undefined ? tickOpts.min : niceMin);
for (var j = 1; j < numSpaces; ++j) {
ticks.push(niceMin + (j * spacing));
}
ticks.push(tickOpts.max !== undefined ? tickOpts.max : niceMax);
me.handleDirectionalChanges();
// At this point, we need to update our max and min given the tick values since we have expanded the
// range of the scale
me.max = helpers.max(ticks);
me.min = helpers.min(ticks);
if (tickOpts.reverse) {
ticks.reverse();
me.start = me.max;
me.end = me.min;
} else {
me.start = me.min;
me.end = me.max;
}
},
convertTicksToLabels: function() {
var me = this;
me.ticksAsNumbers = me.ticks.slice();
me.zeroLineIndex = me.ticks.indexOf(0);
Chart.Scale.prototype.convertTicksToLabels.call(me);
},
});
};
},{}],41:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
var defaultConfig = {
position: "left",
// label settings
ticks: {
callback: function(value, index, arr) {
var remain = value / (Math.pow(10, Math.floor(helpers.log10(value))));
if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === arr.length - 1) {
return value.toExponential();
} else {
return '';
}
}
}
};
var LogarithmicScale = Chart.Scale.extend({
determineDataLimits: function() {
var me = this;
var opts = me.options;
var tickOpts = opts.ticks;
var chart = me.chart;
var data = chart.data;
var datasets = data.datasets;
var getValueOrDefault = helpers.getValueOrDefault;
var isHorizontal = me.isHorizontal();
function IDMatches(meta) {
return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
}
// Calculate Range
me.min = null;
me.max = null;
if (opts.stacked) {
var valuesPerType = {};
helpers.each(datasets, function(dataset, datasetIndex) {
var meta = chart.getDatasetMeta(datasetIndex);
if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
if (valuesPerType[meta.type] === undefined) {
valuesPerType[meta.type] = [];
}
helpers.each(dataset.data, function(rawValue, index) {
var values = valuesPerType[meta.type];
var value = +me.getRightValue(rawValue);
if (isNaN(value) || meta.data[index].hidden) {
return;
}
values[index] = values[index] || 0;
if (opts.relativePoints) {
values[index] = 100;
} else {
// Don't need to split positive and negative since the log scale can't handle a 0 crossing
values[index] += value;
}
});
}
});
helpers.each(valuesPerType, function(valuesForType) {
var minVal = helpers.min(valuesForType);
var maxVal = helpers.max(valuesForType);
me.min = me.min === null ? minVal : Math.min(me.min, minVal);
me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
});
} else {
helpers.each(datasets, function(dataset, datasetIndex) {
var meta = chart.getDatasetMeta(datasetIndex);
if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
helpers.each(dataset.data, function(rawValue, index) {
var value = +me.getRightValue(rawValue);
if (isNaN(value) || meta.data[index].hidden) {
return;
}
if (me.min === null) {
me.min = value;
} else if (value < me.min) {
me.min = value;
}
if (me.max === null) {
me.max = value;
} else if (value > me.max) {
me.max = value;
}
});
}
});
}
me.min = getValueOrDefault(tickOpts.min, me.min);
me.max = getValueOrDefault(tickOpts.max, me.max);
if (me.min === me.max) {
if (me.min !== 0 && me.min !== null) {
me.min = Math.pow(10, Math.floor(helpers.log10(me.min)) - 1);
me.max = Math.pow(10, Math.floor(helpers.log10(me.max)) + 1);
} else {
me.min = 1;
me.max = 10;
}
}
},
buildTicks: function() {
var me = this;
var opts = me.options;
var tickOpts = opts.ticks;
var getValueOrDefault = helpers.getValueOrDefault;
// Reset the ticks array. Later on, we will draw a grid line at these positions
// The array simply contains the numerical value of the spots where ticks will be
var ticks = me.ticks = [];
// Figure out what the max number of ticks we can support it is based on the size of
// the axis area. For now, we say that the minimum tick spacing in pixels must be 50
// We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
// the graph
var tickVal = getValueOrDefault(tickOpts.min, Math.pow(10, Math.floor(helpers.log10(me.min))));
while (tickVal < me.max) {
ticks.push(tickVal);
var exp = Math.floor(helpers.log10(tickVal));
var significand = Math.floor(tickVal / Math.pow(10, exp)) + 1;
if (significand === 10) {
significand = 1;
++exp;
}
tickVal = significand * Math.pow(10, exp);
}
var lastTick = getValueOrDefault(tickOpts.max, tickVal);
ticks.push(lastTick);
if (!me.isHorizontal()) {
// We are in a vertical orientation. The top value is the highest. So reverse the array
ticks.reverse();
}
// At this point, we need to update our max and min given the tick values since we have expanded the
// range of the scale
me.max = helpers.max(ticks);
me.min = helpers.min(ticks);
if (tickOpts.reverse) {
ticks.reverse();
me.start = me.max;
me.end = me.min;
} else {
me.start = me.min;
me.end = me.max;
}
},
convertTicksToLabels: function() {
this.tickValues = this.ticks.slice();
Chart.Scale.prototype.convertTicksToLabels.call(this);
},
// Get the correct tooltip label
getLabelForIndex: function(index, datasetIndex) {
return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
},
getPixelForTick: function(index, includeOffset) {
return this.getPixelForValue(this.tickValues[index], null, null, includeOffset);
},
getPixelForValue: function(value, index, datasetIndex, includeOffset) {
var me = this;
var innerDimension;
var pixel;
var start = me.start;
var newVal = +me.getRightValue(value);
var range = helpers.log10(me.end) - helpers.log10(start);
var paddingTop = me.paddingTop;
var paddingBottom = me.paddingBottom;
var paddingLeft = me.paddingLeft;
if (me.isHorizontal()) {
if (newVal === 0) {
pixel = me.left + paddingLeft;
} else {
innerDimension = me.width - (paddingLeft + me.paddingRight);
pixel = me.left + (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start)));
pixel += paddingLeft;
}
} else {
// Bottom - top since pixels increase downard on a screen
if (newVal === 0) {
pixel = me.top + paddingTop;
} else {
innerDimension = me.height - (paddingTop + paddingBottom);
pixel = (me.bottom - paddingBottom) - (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start)));
}
}
return pixel;
},
getValueForPixel: function(pixel) {
var me = this;
var offset;
var range = helpers.log10(me.end) - helpers.log10(me.start);
var value;
var innerDimension;
if (me.isHorizontal()) {
innerDimension = me.width - (me.paddingLeft + me.paddingRight);
value = me.start * Math.pow(10, (pixel - me.left - me.paddingLeft) * range / innerDimension);
} else {
innerDimension = me.height - (me.paddingTop + me.paddingBottom);
value = Math.pow(10, (me.bottom - me.paddingBottom - pixel) * range / innerDimension) / me.start;
}
return value;
}
});
Chart.scaleService.registerScaleType("logarithmic", LogarithmicScale, defaultConfig);
};
},{}],42:[function(require,module,exports){
"use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
var globalDefaults = Chart.defaults.global;
var defaultConfig = {
display: true,
//Boolean - Whether to animate scaling the chart from the centre
animate: true,
lineArc: false,
position: "chartArea",
angleLines: {
display: true,
color: "rgba(0, 0, 0, 0.1)",
lineWidth: 1
},
// label settings
ticks: {
//Boolean - Show a backdrop to the scale label
showLabelBackdrop: true,
//String - The colour of the label backdrop
backdropColor: "rgba(255,255,255,0.75)",
//Number - The backdrop padding above & below the label in pixels
backdropPaddingY: 2,
//Number - The backdrop padding to the side of the label in pixels
backdropPaddingX: 2
},
pointLabels: {
//Number - Point label font size in pixels
fontSize: 10,
//Function - Used to convert point labels
callback: function(label) {
return label;
}
}
};
var LinearRadialScale = Chart.LinearScaleBase.extend({
getValueCount: function() {
return this.chart.data.labels.length;
},
setDimensions: function() {
var me = this;
var opts = me.options;
var tickOpts = opts.ticks;
// Set the unconstrained dimension before label rotation
me.width = me.maxWidth;
me.height = me.maxHeight;
me.xCenter = Math.round(me.width / 2);
me.yCenter = Math.round(me.height / 2);
var minSize = helpers.min([me.height, me.width]);
var tickFontSize = helpers.getValueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
me.drawingArea = opts.display ? (minSize / 2) - (tickFontSize / 2 + tickOpts.backdropPaddingY) : (minSize / 2);
},
determineDataLimits: function() {
var me = this;
var chart = me.chart;
me.min = null;
me.max = null;
helpers.each(chart.data.datasets, function(dataset, datasetIndex) {
if (chart.isDatasetVisible(datasetIndex)) {
var meta = chart.getDatasetMeta(datasetIndex);
helpers.each(dataset.data, function(rawValue, index) {
var value = +me.getRightValue(rawValue);
if (isNaN(value) || meta.data[index].hidden) {
return;
}
if (me.min === null) {
me.min = value;
} else if (value < me.min) {
me.min = value;
}
if (me.max === null) {
me.max = value;
} else if (value > me.max) {
me.max = value;
}
});
}
});
// Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
me.handleTickRangeOptions();
},
getTickLimit: function() {
var tickOpts = this.options.ticks;
var tickFontSize = helpers.getValueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
return Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(this.drawingArea / (1.5 * tickFontSize)));
},
convertTicksToLabels: function() {
var me = this;
Chart.LinearScaleBase.prototype.convertTicksToLabels.call(me);
// Point labels
me.pointLabels = me.chart.data.labels.map(me.options.pointLabels.callback, me);
},
getLabelForIndex: function(index, datasetIndex) {
return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
},
fit: function() {
/*
* Right, this is really confusing and there is a lot of maths going on here
* The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
*
* Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
*
* Solution:
*
* We assume the radius of the polygon is half the size of the canvas at first
* at each index we check if the text overlaps.
*
* Where it does, we store that angle and that index.
*
* After finding the largest index and angle we calculate how much we need to remove
* from the shape radius to move the point inwards by that x.
*
* We average the left and right distances to get the maximum shape radius that can fit in the box
* along with labels.
*
* Once we have that, we can find the centre point for the chart, by taking the x text protrusion
* on each side, removing that from the size, halving it and adding the left x protrusion width.
*
* This will mean we have a shape fitted to the canvas, as large as it can be with the labels
* and position it in the most space efficient manner
*
* https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
*/
var pointLabels = this.options.pointLabels;
var pointLabelFontSize = helpers.getValueOrDefault(pointLabels.fontSize, globalDefaults.defaultFontSize);
var pointLabeFontStyle = helpers.getValueOrDefault(pointLabels.fontStyle, globalDefaults.defaultFontStyle);
var pointLabeFontFamily = helpers.getValueOrDefault(pointLabels.fontFamily, globalDefaults.defaultFontFamily);
var pointLabeFont = helpers.fontString(pointLabelFontSize, pointLabeFontStyle, pointLabeFontFamily);
// Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
// Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
var largestPossibleRadius = helpers.min([(this.height / 2 - pointLabelFontSize - 5), this.width / 2]),
pointPosition,
i,
textWidth,
halfTextWidth,
furthestRight = this.width,
furthestRightIndex,
furthestRightAngle,
furthestLeft = 0,
furthestLeftIndex,
furthestLeftAngle,
xProtrusionLeft,
xProtrusionRight,
radiusReductionRight,
radiusReductionLeft,
maxWidthRadius;
this.ctx.font = pointLabeFont;
for (i = 0; i < this.getValueCount(); i++) {
// 5px to space the text slightly out - similar to what we do in the draw function.
pointPosition = this.getPointPosition(i, largestPossibleRadius);
textWidth = this.ctx.measureText(this.pointLabels[i] ? this.pointLabels[i] : '').width + 5;
if (i === 0 || i === this.getValueCount() / 2) {
// If we're at index zero, or exactly the middle, we're at exactly the top/bottom
// of the radar chart, so text will be aligned centrally, so we'll half it and compare
// w/left and right text sizes
halfTextWidth = textWidth / 2;
if (pointPosition.x + halfTextWidth > furthestRight) {
furthestRight = pointPosition.x + halfTextWidth;
furthestRightIndex = i;
}
if (pointPosition.x - halfTextWidth < furthestLeft) {
furthestLeft = pointPosition.x - halfTextWidth;
furthestLeftIndex = i;
}
} else if (i < this.getValueCount() / 2) {
// Less than half the values means we'll left align the text
if (pointPosition.x + textWidth > furthestRight) {
furthestRight = pointPosition.x + textWidth;
furthestRightIndex = i;
}
} else if (i > this.getValueCount() / 2) {
// More than half the values means we'll right align the text
if (pointPosition.x - textWidth < furthestLeft) {
furthestLeft = pointPosition.x - textWidth;
furthestLeftIndex = i;
}
}
}
xProtrusionLeft = furthestLeft;
xProtrusionRight = Math.ceil(furthestRight - this.width);
furthestRightAngle = this.getIndexAngle(furthestRightIndex);
furthestLeftAngle = this.getIndexAngle(furthestLeftIndex);
radiusReductionRight = xProtrusionRight / Math.sin(furthestRightAngle + Math.PI / 2);
radiusReductionLeft = xProtrusionLeft / Math.sin(furthestLeftAngle + Math.PI / 2);
// Ensure we actually need to reduce the size of the chart
radiusReductionRight = (helpers.isNumber(radiusReductionRight)) ? radiusReductionRight : 0;
radiusReductionLeft = (helpers.isNumber(radiusReductionLeft)) ? radiusReductionLeft : 0;
this.drawingArea = Math.round(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2);
this.setCenterPoint(radiusReductionLeft, radiusReductionRight);
},
setCenterPoint: function(leftMovement, rightMovement) {
var me = this;
var maxRight = me.width - rightMovement - me.drawingArea,
maxLeft = leftMovement + me.drawingArea;
me.xCenter = Math.round(((maxLeft + maxRight) / 2) + me.left);
// Always vertically in the centre as the text height doesn't change
me.yCenter = Math.round((me.height / 2) + me.top);
},
getIndexAngle: function(index) {
var angleMultiplier = (Math.PI * 2) / this.getValueCount();
// Start from the top instead of right, so remove a quarter of the circle
return index * angleMultiplier - (Math.PI / 2);
},
getDistanceFromCenterForValue: function(value) {
var me = this;
if (value === null) {
return 0; // null always in center
}
// Take into account half font size + the yPadding of the top value
var scalingFactor = me.drawingArea / (me.max - me.min);
if (me.options.reverse) {
return (me.max - value) * scalingFactor;
} else {
return (value - me.min) * scalingFactor;
}
},
getPointPosition: function(index, distanceFromCenter) {
var me = this;
var thisAngle = me.getIndexAngle(index);
return {
x: Math.round(Math.cos(thisAngle) * distanceFromCenter) + me.xCenter,
y: Math.round(Math.sin(thisAngle) * distanceFromCenter) + me.yCenter
};
},
getPointPositionForValue: function(index, value) {
return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
},
getBasePosition: function() {
var me = this;
var min = me.min;
var max = me.max;
return me.getPointPositionForValue(0,
me.beginAtZero? 0:
min < 0 && max < 0? max :
min > 0 && max > 0? min :
0);
},
draw: function() {
var me = this;
var opts = me.options;
var gridLineOpts = opts.gridLines;
var tickOpts = opts.ticks;
var angleLineOpts = opts.angleLines;
var pointLabelOpts = opts.pointLabels;
var getValueOrDefault = helpers.getValueOrDefault;
if (opts.display) {
var ctx = me.ctx;
// Tick Font
var tickFontSize = getValueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
var tickFontStyle = getValueOrDefault(tickOpts.fontStyle, globalDefaults.defaultFontStyle);
var tickFontFamily = getValueOrDefault(tickOpts.fontFamily, globalDefaults.defaultFontFamily);
var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);
helpers.each(me.ticks, function(label, index) {
// Don't draw a centre value (if it is minimum)
if (index > 0 || opts.reverse) {
var yCenterOffset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
var yHeight = me.yCenter - yCenterOffset;
// Draw circular lines around the scale
if (gridLineOpts.display && index !== 0) {
ctx.strokeStyle = helpers.getValueAtIndexOrDefault(gridLineOpts.color, index - 1);
ctx.lineWidth = helpers.getValueAtIndexOrDefault(gridLineOpts.lineWidth, index - 1);
if (opts.lineArc) {
// Draw circular arcs between the points
ctx.beginPath();
ctx.arc(me.xCenter, me.yCenter, yCenterOffset, 0, Math.PI * 2);
ctx.closePath();
ctx.stroke();
} else {
// Draw straight lines connecting each index
ctx.beginPath();
for (var i = 0; i < me.getValueCount(); i++) {
var pointPosition = me.getPointPosition(i, yCenterOffset);
if (i === 0) {
ctx.moveTo(pointPosition.x, pointPosition.y);
} else {
ctx.lineTo(pointPosition.x, pointPosition.y);
}
}
ctx.closePath();
ctx.stroke();
}
}
if (tickOpts.display) {
var tickFontColor = getValueOrDefault(tickOpts.fontColor, globalDefaults.defaultFontColor);
ctx.font = tickLabelFont;
if (tickOpts.showLabelBackdrop) {
var labelWidth = ctx.measureText(label).width;
ctx.fillStyle = tickOpts.backdropColor;
ctx.fillRect(
me.xCenter - labelWidth / 2 - tickOpts.backdropPaddingX,
yHeight - tickFontSize / 2 - tickOpts.backdropPaddingY,
labelWidth + tickOpts.backdropPaddingX * 2,
tickFontSize + tickOpts.backdropPaddingY * 2
);
}
ctx.textAlign = 'center';
ctx.textBaseline = "middle";
ctx.fillStyle = tickFontColor;
ctx.fillText(label, me.xCenter, yHeight);
}
}
});
if (!opts.lineArc) {
ctx.lineWidth = angleLineOpts.lineWidth;
ctx.strokeStyle = angleLineOpts.color;
var outerDistance = me.getDistanceFromCenterForValue(opts.reverse ? me.min : me.max);
// Point Label Font
var pointLabelFontSize = getValueOrDefault(pointLabelOpts.fontSize, globalDefaults.defaultFontSize);
var pointLabeFontStyle = getValueOrDefault(pointLabelOpts.fontStyle, globalDefaults.defaultFontStyle);
var pointLabeFontFamily = getValueOrDefault(pointLabelOpts.fontFamily, globalDefaults.defaultFontFamily);
var pointLabeFont = helpers.fontString(pointLabelFontSize, pointLabeFontStyle, pointLabeFontFamily);
for (var i = me.getValueCount() - 1; i >= 0; i--) {
if (angleLineOpts.display) {
var outerPosition = me.getPointPosition(i, outerDistance);
ctx.beginPath();
ctx.moveTo(me.xCenter, me.yCenter);
ctx.lineTo(outerPosition.x, outerPosition.y);
ctx.stroke();
ctx.closePath();
}
// Extra 3px out for some label spacing
var pointLabelPosition = me.getPointPosition(i, outerDistance + 5);
// Keep this in loop since we may support array properties here
var pointLabelFontColor = getValueOrDefault(pointLabelOpts.fontColor, globalDefaults.defaultFontColor);
ctx.font = pointLabeFont;
ctx.fillStyle = pointLabelFontColor;
var pointLabels = me.pointLabels,
labelsCount = pointLabels.length,
halfLabelsCount = pointLabels.length / 2,
quarterLabelsCount = halfLabelsCount / 2,
upperHalf = (i < quarterLabelsCount || i > labelsCount - quarterLabelsCount),
exactQuarter = (i === quarterLabelsCount || i === labelsCount - quarterLabelsCount);
if (i === 0) {
ctx.textAlign = 'center';
} else if (i === halfLabelsCount) {
ctx.textAlign = 'center';
} else if (i < halfLabelsCount) {
ctx.textAlign = 'left';
} else {
ctx.textAlign = 'right';
}
// Set the correct text baseline based on outer positioning
if (exactQuarter) {
ctx.textBaseline = 'middle';
} else if (upperHalf) {
ctx.textBaseline = 'bottom';
} else {
ctx.textBaseline = 'top';
}
ctx.fillText(pointLabels[i] ? pointLabels[i] : '', pointLabelPosition.x, pointLabelPosition.y);
}
}
}
}
});
Chart.scaleService.registerScaleType("radialLinear", LinearRadialScale, defaultConfig);
};
},{}],43:[function(require,module,exports){
/*global window: false */
"use strict";
var moment = require(1);
moment = typeof(moment) === 'function' ? moment : window.moment;
module.exports = function(Chart) {
var helpers = Chart.helpers;
var time = {
units: [{
name: 'millisecond',
steps: [1, 2, 5, 10, 20, 50, 100, 250, 500]
}, {
name: 'second',
steps: [1, 2, 5, 10, 30]
}, {
name: 'minute',
steps: [1, 2, 5, 10, 30]
}, {
name: 'hour',
steps: [1, 2, 3, 6, 12]
}, {
name: 'day',
steps: [1, 2, 5]
}, {
name: 'week',
maxStep: 4
}, {
name: 'month',
maxStep: 3
}, {
name: 'quarter',
maxStep: 4
}, {
name: 'year',
maxStep: false
}]
};
var defaultConfig = {
position: "bottom",
time: {
parser: false, // false == a pattern string from http://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment
format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from http://momentjs.com/docs/#/parsing/string-format/
unit: false, // false == automatic or override with week, month, year, etc.
round: false, // none, or override with week, month, year, etc.
displayFormat: false, // DEPRECATED
isoWeekday: false, // override week start day - see http://momentjs.com/docs/#/get-set/iso-weekday/
// defaults to unit's corresponding unitFormat below or override using pattern string from http://momentjs.com/docs/#/displaying/format/
displayFormats: {
'millisecond': 'h:mm:ss.SSS a', // 11:20:01.123 AM,
'second': 'h:mm:ss a', // 11:20:01 AM
'minute': 'h:mm:ss a', // 11:20:01 AM
'hour': 'MMM D, hA', // Sept 4, 5PM
'day': 'll', // Sep 4 2015
'week': 'll', // Week 46, or maybe "[W]WW - YYYY" ?
'month': 'MMM YYYY', // Sept 2015
'quarter': '[Q]Q - YYYY', // Q3
'year': 'YYYY' // 2015
}
},
ticks: {
autoSkip: false
}
};
var TimeScale = Chart.Scale.extend({
initialize: function() {
if (!moment) {
throw new Error('Chart.js - Moment.js could not be found! You must include it before Chart.js to use the time scale. Download at https://momentjs.com');
}
Chart.Scale.prototype.initialize.call(this);
},
getLabelMoment: function(datasetIndex, index) {
return this.labelMoments[datasetIndex][index];
},
getMomentStartOf: function(tick) {
var me = this;
if (me.options.time.unit === 'week' && me.options.time.isoWeekday !== false) {
return tick.clone().startOf('isoWeek').isoWeekday(me.options.time.isoWeekday);
} else {
return tick.clone().startOf(me.tickUnit);
}
},
determineDataLimits: function() {
var me = this;
me.labelMoments = [];
// Only parse these once. If the dataset does not have data as x,y pairs, we will use
// these
var scaleLabelMoments = [];
if (me.chart.data.labels && me.chart.data.labels.length > 0) {
helpers.each(me.chart.data.labels, function(label, index) {
var labelMoment = me.parseTime(label);
if (labelMoment.isValid()) {
if (me.options.time.round) {
labelMoment.startOf(me.options.time.round);
}
scaleLabelMoments.push(labelMoment);
}
}, me);
me.firstTick = moment.min.call(me, scaleLabelMoments);
me.lastTick = moment.max.call(me, scaleLabelMoments);
} else {
me.firstTick = null;
me.lastTick = null;
}
helpers.each(me.chart.data.datasets, function(dataset, datasetIndex) {
var momentsForDataset = [];
var datasetVisible = me.chart.isDatasetVisible(datasetIndex);
if (typeof dataset.data[0] === 'object' && dataset.data[0] !== null) {
helpers.each(dataset.data, function(value, index) {
var labelMoment = me.parseTime(me.getRightValue(value));
if (labelMoment.isValid()) {
if (me.options.time.round) {
labelMoment.startOf(me.options.time.round);
}
momentsForDataset.push(labelMoment);
if (datasetVisible) {
// May have gone outside the scale ranges, make sure we keep the first and last ticks updated
me.firstTick = me.firstTick !== null ? moment.min(me.firstTick, labelMoment) : labelMoment;
me.lastTick = me.lastTick !== null ? moment.max(me.lastTick, labelMoment) : labelMoment;
}
}
}, me);
} else {
// We have no labels. Use the ones from the scale
momentsForDataset = scaleLabelMoments;
}
me.labelMoments.push(momentsForDataset);
}, me);
// Set these after we've done all the data
if (me.options.time.min) {
me.firstTick = me.parseTime(me.options.time.min);
}
if (me.options.time.max) {
me.lastTick = me.parseTime(me.options.time.max);
}
// We will modify these, so clone for later
me.firstTick = (me.firstTick || moment()).clone();
me.lastTick = (me.lastTick || moment()).clone();
},
buildTicks: function(index) {
var me = this;
me.ctx.save();
var tickFontSize = helpers.getValueOrDefault(me.options.ticks.fontSize, Chart.defaults.global.defaultFontSize);
var tickFontStyle = helpers.getValueOrDefault(me.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle);
var tickFontFamily = helpers.getValueOrDefault(me.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily);
var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);
me.ctx.font = tickLabelFont;
me.ticks = [];
me.unitScale = 1; // How much we scale the unit by, ie 2 means 2x unit per step
me.scaleSizeInUnits = 0; // How large the scale is in the base unit (seconds, minutes, etc)
// Set unit override if applicable
if (me.options.time.unit) {
me.tickUnit = me.options.time.unit || 'day';
me.displayFormat = me.options.time.displayFormats[me.tickUnit];
me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true);
me.unitScale = helpers.getValueOrDefault(me.options.time.unitStepSize, 1);
} else {
// Determine the smallest needed unit of the time
var innerWidth = me.isHorizontal() ? me.width - (me.paddingLeft + me.paddingRight) : me.height - (me.paddingTop + me.paddingBottom);
// Crude approximation of what the label length might be
var tempFirstLabel = me.tickFormatFunction(me.firstTick, 0, []);
var tickLabelWidth = me.ctx.measureText(tempFirstLabel).width;
var cosRotation = Math.cos(helpers.toRadians(me.options.ticks.maxRotation));
var sinRotation = Math.sin(helpers.toRadians(me.options.ticks.maxRotation));
tickLabelWidth = (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation);
var labelCapacity = innerWidth / (tickLabelWidth);
// Start as small as possible
me.tickUnit = 'millisecond';
me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true);
me.displayFormat = me.options.time.displayFormats[me.tickUnit];
var unitDefinitionIndex = 0;
var unitDefinition = time.units[unitDefinitionIndex];
// While we aren't ideal and we don't have units left
while (unitDefinitionIndex < time.units.length) {
// Can we scale this unit. If `false` we can scale infinitely
me.unitScale = 1;
if (helpers.isArray(unitDefinition.steps) && Math.ceil(me.scaleSizeInUnits / labelCapacity) < helpers.max(unitDefinition.steps)) {
// Use one of the prefedined steps
for (var idx = 0; idx < unitDefinition.steps.length; ++idx) {
if (unitDefinition.steps[idx] >= Math.ceil(me.scaleSizeInUnits / labelCapacity)) {
me.unitScale = helpers.getValueOrDefault(me.options.time.unitStepSize, unitDefinition.steps[idx]);
break;
}
}
break;
} else if ((unitDefinition.maxStep === false) || (Math.ceil(me.scaleSizeInUnits / labelCapacity) < unitDefinition.maxStep)) {
// We have a max step. Scale this unit
me.unitScale = helpers.getValueOrDefault(me.options.time.unitStepSize, Math.ceil(me.scaleSizeInUnits / labelCapacity));
break;
} else {
// Move to the next unit up
++unitDefinitionIndex;
unitDefinition = time.units[unitDefinitionIndex];
me.tickUnit = unitDefinition.name;
var leadingUnitBuffer = me.firstTick.diff(me.getMomentStartOf(me.firstTick), me.tickUnit, true);
var trailingUnitBuffer = me.getMomentStartOf(me.lastTick.clone().add(1, me.tickUnit)).diff(me.lastTick, me.tickUnit, true);
me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true) + leadingUnitBuffer + trailingUnitBuffer;
me.displayFormat = me.options.time.displayFormats[unitDefinition.name];
}
}
}
var roundedStart;
// Only round the first tick if we have no hard minimum
if (!me.options.time.min) {
me.firstTick = me.getMomentStartOf(me.firstTick);
roundedStart = me.firstTick;
} else {
roundedStart = me.getMomentStartOf(me.firstTick);
}
// Only round the last tick if we have no hard maximum
if (!me.options.time.max) {
var roundedEnd = me.getMomentStartOf(me.lastTick);
if (roundedEnd.diff(me.lastTick, me.tickUnit, true) !== 0) {
// Do not use end of because we need me to be in the next time unit
me.lastTick = me.getMomentStartOf(me.lastTick.add(1, me.tickUnit));
}
}
me.smallestLabelSeparation = me.width;
helpers.each(me.chart.data.datasets, function(dataset, datasetIndex) {
for (var i = 1; i < me.labelMoments[datasetIndex].length; i++) {
me.smallestLabelSeparation = Math.min(me.smallestLabelSeparation, me.labelMoments[datasetIndex][i].diff(me.labelMoments[datasetIndex][i - 1], me.tickUnit, true));
}
}, me);
// Tick displayFormat override
if (me.options.time.displayFormat) {
me.displayFormat = me.options.time.displayFormat;
}
// first tick. will have been rounded correctly if options.time.min is not specified
me.ticks.push(me.firstTick.clone());
// For every unit in between the first and last moment, create a moment and add it to the ticks tick
for (var i = 1; i <= me.scaleSizeInUnits; ++i) {
var newTick = roundedStart.clone().add(i, me.tickUnit);
// Are we greater than the max time
if (me.options.time.max && newTick.diff(me.lastTick, me.tickUnit, true) >= 0) {
break;
}
if (i % me.unitScale === 0) {
me.ticks.push(newTick);
}
}
// Always show the right tick
var diff = me.ticks[me.ticks.length - 1].diff(me.lastTick, me.tickUnit);
if (diff !== 0 || me.scaleSizeInUnits === 0) {
// this is a weird case. If the <max> option is the same as the end option, we can't just diff the times because the tick was created from the roundedStart
// but the last tick was not rounded.
if (me.options.time.max) {
me.ticks.push(me.lastTick.clone());
me.scaleSizeInUnits = me.lastTick.diff(me.ticks[0], me.tickUnit, true);
} else {
me.ticks.push(me.lastTick.clone());
me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true);
}
}
me.ctx.restore();
},
// Get tooltip label
getLabelForIndex: function(index, datasetIndex) {
var me = this;
var label = me.chart.data.labels && index < me.chart.data.labels.length ? me.chart.data.labels[index] : '';
if (typeof me.chart.data.datasets[datasetIndex].data[0] === 'object') {
label = me.getRightValue(me.chart.data.datasets[datasetIndex].data[index]);
}
// Format nicely
if (me.options.time.tooltipFormat) {
label = me.parseTime(label).format(me.options.time.tooltipFormat);
}
return label;
},
// Function to format an individual tick mark
tickFormatFunction: function tickFormatFunction(tick, index, ticks) {
var formattedTick = tick.format(this.displayFormat);
var tickOpts = this.options.ticks;
var callback = helpers.getValueOrDefault(tickOpts.callback, tickOpts.userCallback);
if (callback) {
return callback(formattedTick, index, ticks);
} else {
return formattedTick;
}
},
convertTicksToLabels: function() {
var me = this;
me.tickMoments = me.ticks;
me.ticks = me.ticks.map(me.tickFormatFunction, me);
},
getPixelForValue: function(value, index, datasetIndex, includeOffset) {
var me = this;
var labelMoment = value && value.isValid && value.isValid() ? value : me.getLabelMoment(datasetIndex, index);
if (labelMoment) {
var offset = labelMoment.diff(me.firstTick, me.tickUnit, true);
var decimal = offset / me.scaleSizeInUnits;
if (me.isHorizontal()) {
var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
var valueWidth = innerWidth / Math.max(me.ticks.length - 1, 1);
var valueOffset = (innerWidth * decimal) + me.paddingLeft;
return me.left + Math.round(valueOffset);
} else {
var innerHeight = me.height - (me.paddingTop + me.paddingBottom);
var valueHeight = innerHeight / Math.max(me.ticks.length - 1, 1);
var heightOffset = (innerHeight * decimal) + me.paddingTop;
return me.top + Math.round(heightOffset);
}
}
},
getPixelForTick: function(index, includeOffset) {
return this.getPixelForValue(this.tickMoments[index], null, null, includeOffset);
},
getValueForPixel: function(pixel) {
var me = this;
var innerDimension = me.isHorizontal() ? me.width - (me.paddingLeft + me.paddingRight) : me.height - (me.paddingTop + me.paddingBottom);
var offset = (pixel - (me.isHorizontal() ? me.left + me.paddingLeft : me.top + me.paddingTop)) / innerDimension;
offset *= me.scaleSizeInUnits;
return me.firstTick.clone().add(moment.duration(offset, me.tickUnit).asSeconds(), 'seconds');
},
parseTime: function(label) {
var me = this;
if (typeof me.options.time.parser === 'string') {
return moment(label, me.options.time.parser);
}
if (typeof me.options.time.parser === 'function') {
return me.options.time.parser(label);
}
// Date objects
if (typeof label.getMonth === 'function' || typeof label === 'number') {
return moment(label);
}
// Moment support
if (label.isValid && label.isValid()) {
return label;
}
// Custom parsing (return an instance of moment)
if (typeof me.options.time.format !== 'string' && me.options.time.format.call) {
console.warn("options.time.format is deprecated and replaced by options.time.parser. See http://nnnick.github.io/Chart.js/docs-v2/#scales-time-scale");
return me.options.time.format(label);
}
// Moment format parsing
return moment(label, me.options.time.format);
}
});
Chart.scaleService.registerScaleType("time", TimeScale, defaultConfig);
};
},{"1":1}]},{},[7])(7)
});
|
gpl-3.0
|
cosven/pat_play
|
leetcode/096.py
|
463
|
class Solution:
cache = {1: 1, 0:1}
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
if n in self.cache:
return self.cache[n]
sum = 0
ncopy = n - 1
while ncopy >= 0:
sum += self.numTrees(ncopy) * self.numTrees(n - 1 - ncopy)
ncopy -= 1
self.cache[n] = sum
return sum
if __name__ == '__main__':
print(Solution().numTrees(100))
|
gpl-3.0
|
j33f/apiMobitrans
|
routes/index.js
|
789
|
/*
API Mobitrans
Author : jean-François VIAL <http://about.me/Jeff_>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version
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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
exports.index = function(req, res){
res.redirect(301, 'https://github.com/Modulaweb/apiMobitrans');
};
|
gpl-3.0
|
miyachi-yu/Mellin
|
IntegUnpolDIS/nXsecComp.cc
|
2625
|
#include "nXsecComp.hh"
#include "StrFunc.hh"
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <QCD/Flavor.hh>
#include <Evolution/PDF.hh>
#include <Tranform/Mellin.hh>
#include <unpolPDF/Evolution.hh>
#include <unpolPDF/CTEQ6pdf.hh>
using namespace std;
using namespace Transform;
using namespace Utility;
using namespace QCD;
using namespace IntegUnpolDIS;
nXsecComp::nXsecComp( Arguments& args,
const IntegXsec::Charge::TARGET& n ) throw( int ) :
Xsection::XsecComp()
{
try { // prepare Evolution kernel for unpolDIS function
this->insert( unpolPDF::Evo::instance(), Flavor::PRp );
dynamic_cast< unpolPDF::Evo* >( this->vevo()[ 0 ] )->constNf( false );
}
catch( int error ) {
cerr << __FILE__ << ":" << __LINE__ << "\tcatch error ("
<< error << ") !!" << endl;
throw error;
}
this->coefficients( n );
}
nXsecComp::nXsecComp( Evolution::KernelBase *kernel,
const IntegXsec::Charge::TARGET& n ) throw( int ) :
Xsection::XsecComp()
{
if( dynamic_cast< unpolPDF::Evo* >( kernel ) ||
dynamic_cast< unpolPDF::CTEQ6pdf* >( kernel ) ){
this->insert( kernel, Flavor::PRp );
} else {
cerr << __FILE__ << ":" << __LINE__
<< "\tkernel should be either unpolPDF::Evo or unpolPDF::CTEQ6pdf"
<< endl;
throw( 1 );
}
this->coefficients( n );
}
nXsecComp::~nXsecComp(){
// delete all dynamically allocated objects by this
if( this->coeff() ) delete this->coeff();
for( int i = 0; i < rescaleFcn().size(); i++ )
if( rescaleFcn()[ i ] ) delete rescaleFcn()[ i ];
}
void nXsecComp::update(){
}
void nXsecComp::coefficients( const IntegXsec::Charge::TARGET& n ){
Arguments& args = Arguments::ref();
// register CKernel object
Xsection::CKernelBase *coeff;
if( args.hasOpt( "ShortInteg" ) ){
coeff = new IntegUnpolDIS::StrFunc( this, args, n, 4, 0, 1.0E-4 );
} else {
coeff = new IntegUnpolDIS::StrFunc( this, args, n, 4, 6, 1.0E-4 );
}
coeff->constNf( false );
this->coeff( coeff );
//! set Q^2 / \mu_R^2 to alpha_s
double rescaleQ2 = args.get( "rescaleQ2", 1.0 );
this->coeff()->alpha().setMURfact( rescaleQ2 );
//! Scale rescaling function
//! Q^2 / \mu_F^2
double rescaleUPDF = args.get( "rescaleUPDF", 1.0 );// for evo[ 0 ]
//! set \mu_F^2 / \mu_R^2 to alpha_s of each evolutoin
this->vevo()[ 0 ]->alpha().setMURfact( rescaleQ2 / rescaleUPDF );
RealFunction* rf_1_ = ( rescaleUPDF != 1.0 ?
new Xsection::XsecComp::SimpleRescale( rescaleUPDF )
: ( RealFunction* ) NULL );
this->rescaleFcn().resize( 0 );
this->rescaleFcn().push_back( rf_1_ );
}
|
gpl-3.0
|
Naoghuman/Dream-Better-Worlds
|
DBW-Application-Performance/src/main/java/de/pro/dbw/application/performance/entity/reflection/ReflectionView.java
|
1043
|
/*
* Copyright (C) 2015 Dream Better Worlds
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.pro.dbw.application.performance.entity.reflection;
import com.airhacks.afterburner.views.FXMLView;
/**
*
* @author PRo
*/
public class ReflectionView extends FXMLView {
public ReflectionPresenter getRealPresenter() {
return (ReflectionPresenter) super.getPresenter();
}
}
|
gpl-3.0
|
teiniker/teiniker-lectures-configurationmanagement
|
documentation/API-Stack/src/test/java/org/se/lab/StackTest.java
|
730
|
package org.se.lab;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class StackTest
{
private Stack stack;
@Before
public void setup()
{
stack = Stack.newInstance();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
}
@Test
public void testSize()
{
int size = stack.size();
Assert.assertEquals(4, size);
}
@Test
public void testPop()
{
Assert.assertEquals(Integer.valueOf(4), stack.pop());
Assert.assertEquals(Integer.valueOf(3), stack.pop());
Assert.assertEquals(Integer.valueOf(2), stack.pop());
Assert.assertEquals(Integer.valueOf(1), stack.pop());
Assert.assertEquals(0, stack.size());
Assert.assertNull(stack.pop());
}
}
|
gpl-3.0
|
Humanized/yii2-account
|
cli/DefaultController.php
|
1069
|
<?php
/**
* @link https://github.com/humanized/yii2-user-management
* @copyright Copyright (c) 2016 Humanized BV Comm V
* @license https://github.com/humanized/yii2-user-management/LICENSE.md
*/
namespace humanized\account\cli;
use humanized\account\models\base\UserCrud;
/**
*
* @name Yii2 User Managment Module CLI
* @version 1.0
* @author Jeffrey Geyssens <jeffrey@humanized.be>
* @package yii2-user-management
*
*/
class DefaultController extends \yii\console\Controller
{
public $setPassword = false;
public function options()
{
return ['setPassword'];
}
public function optionAliases()
{
return ['pswd' => 'setPassword'];
}
public function actionCreate($email, $username = null)
{
$attributes = ['email' => $email];
if (isset($username)) {
$attributes['username'] = $username;
}
if ($this->setPassword) {
$attributes['password'] = 'debug123';
}
$success = UserCrud::create($attributes);
return 0;
}
}
|
gpl-3.0
|
guiguilechat/EveOnline
|
model/sde/SDE-Types/src/generated/java/fr/guiguilechat/jcelechat/model/sde/types/commodity/ShipLogs.java
|
1841
|
package fr.guiguilechat.jcelechat.model.sde.types.commodity;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import fr.guiguilechat.jcelechat.model.sde.IMetaCategory;
import fr.guiguilechat.jcelechat.model.sde.IMetaGroup;
import fr.guiguilechat.jcelechat.model.sde.types.Commodity;
import org.yaml.snakeyaml.Yaml;
public class ShipLogs
extends Commodity
{
public static final ShipLogs.MetaGroup METAGROUP = new ShipLogs.MetaGroup();
@Override
public IMetaGroup<ShipLogs> getGroup() {
return METAGROUP;
}
public static class MetaGroup
implements IMetaGroup<ShipLogs>
{
public static final String RESOURCE_PATH = "SDE/types/commodity/ShipLogs.yaml";
private Map<String, ShipLogs> cache = (null);
@Override
public IMetaCategory<? super ShipLogs> category() {
return Commodity.METACAT;
}
@Override
public int getGroupId() {
return 369;
}
@Override
public String getName() {
return "ShipLogs";
}
@Override
public synchronized Map<String, ShipLogs> load() {
if (cache == null) {
try(final InputStreamReader reader = new InputStreamReader(ShipLogs.MetaGroup.class.getClassLoader().getResourceAsStream((RESOURCE_PATH)))) {
cache = new Yaml().loadAs(reader, (Container.class)).types;
} catch (final Exception exception) {
throw new UnsupportedOperationException("catch this", exception);
}
}
return Collections.unmodifiableMap(cache);
}
private static class Container {
public LinkedHashMap<String, ShipLogs> types;
}
}
}
|
gpl-3.0
|
imsure/ndn-tools-dev
|
tools/pib/pib-db.cpp
|
29709
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016, Regents of the University of California.
*
* This file is part of ndn-tools (Named Data Networking Essential Tools).
* See AUTHORS.md for complete list of ndn-tools authors and contributors.
*
* ndn-tools is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* ndn-tools 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* ndn-tools, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Yingdi Yu <yingdi@cs.ucla.edu>
*/
#include "pib-db.hpp"
#include <sqlite3.h>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
namespace ndn {
namespace pib {
using std::string;
using std::vector;
using std::set;
const Name PibDb::NON_EXISTING_IDENTITY("/localhost/reserved/non-existing-identity");
const Name PibDb::NON_EXISTING_KEY("/localhost/reserved/non-existing-key");
const Name PibDb::NON_EXISTING_CERTIFICATE("/localhost/reserved/non-existing-certificate");
const Name PibDb::LOCALHOST_PIB("/localhost/pib");
const name::Component PibDb::MGMT_LABEL("mgmt");
static const string INITIALIZATION =
"CREATE TABLE IF NOT EXISTS \n"
" mgmt( \n"
" id INTEGER PRIMARY KEY,\n"
" owner BLOB NOT NULL, \n"
" tpm_locator BLOB, \n"
" local_management_cert BLOB NOT NULL \n"
" ); \n"
"CREATE TRIGGER IF NOT EXISTS \n"
" mgmt_insert_trigger \n"
" BEFORE INSERT ON mgmt \n"
" FOR EACH ROW \n"
" BEGIN \n"
" DELETE FROM mgmt; \n"
" END; \n"
" \n"
"CREATE TABLE IF NOT EXISTS \n"
" identities( \n"
" id INTEGER PRIMARY KEY,\n"
" identity BLOB NOT NULL, \n"
" is_default INTEGER DEFAULT 0 \n"
" ); \n"
"CREATE UNIQUE INDEX IF NOT EXISTS \n"
" identityIndex ON identities(identity); \n"
"CREATE TRIGGER IF NOT EXISTS \n"
" identity_default_before_insert_trigger \n"
" BEFORE INSERT ON identities \n"
" FOR EACH ROW \n"
" WHEN NEW.is_default=1 \n"
" BEGIN \n"
" UPDATE identities SET is_default=0; \n"
" END; \n"
"CREATE TRIGGER IF NOT EXISTS \n"
" identity_default_after_insert_trigger \n"
" AFTER INSERT ON identities \n"
" FOR EACH ROW \n"
" WHEN NOT EXISTS \n"
" (SELECT id \n"
" FROM identities \n"
" WHERE is_default=1) \n"
" BEGIN \n"
" UPDATE identities \n"
" SET is_default=1 \n"
" WHERE identity=NEW.identity; \n"
" END; \n"
"CREATE TRIGGER IF NOT EXISTS \n"
" identity_default_update_trigger \n"
" BEFORE UPDATE ON identities \n"
" FOR EACH ROW \n"
" WHEN NEW.is_default=1 AND OLD.is_default=0 \n"
" BEGIN \n"
" UPDATE identities SET is_default=0; \n"
" END; \n"
"CREATE TRIGGER IF NOT EXISTS \n"
" identity_delete_trigger \n"
" AFTER DELETE ON identities \n"
" FOR EACH ROW \n"
" BEGIN \n"
" SELECT identityDeleted (OLD.identity); \n"
" END; \n"
" \n"
"CREATE TABLE IF NOT EXISTS \n"
" keys( \n"
" id INTEGER PRIMARY KEY,\n"
" identity_id INTEGER NOT NULL, \n"
" key_name BLOB NOT NULL, \n"
" key_type INTEGER NOT NULL, \n"
" key_bits BLOB NOT NULL, \n"
" is_default INTEGER DEFAULT 0, \n"
" FOREIGN KEY(identity_id) \n"
" REFERENCES identities(id) \n"
" ON DELETE CASCADE \n"
" ON UPDATE CASCADE \n"
" ); \n"
"CREATE UNIQUE INDEX IF NOT EXISTS \n"
" keyIndex ON keys(key_name); \n"
"CREATE TRIGGER IF NOT EXISTS \n"
" key_default_before_insert_trigger \n"
" BEFORE INSERT ON keys \n"
" FOR EACH ROW \n"
" WHEN NEW.is_default=1 \n"
" BEGIN \n"
" UPDATE keys \n"
" SET is_default=0 \n"
" WHERE identity_id=NEW.identity_id; \n"
" END; \n"
"CREATE TRIGGER IF NOT EXISTS \n"
" key_default_after_insert_trigger \n"
" AFTER INSERT ON keys \n"
" FOR EACH ROW \n"
" WHEN NOT EXISTS \n"
" (SELECT id \n"
" FROM keys \n"
" WHERE is_default=1 \n"
" AND identity_id=NEW.identity_id) \n"
" BEGIN \n"
" UPDATE keys \n"
" SET is_default=1 \n"
" WHERE key_name=NEW.key_name; \n"
" END; \n"
"CREATE TRIGGER IF NOT EXISTS \n"
" key_default_update_trigger \n"
" BEFORE UPDATE ON keys \n"
" FOR EACH ROW \n"
" WHEN NEW.is_default=1 AND OLD.is_default=0 \n"
" BEGIN \n"
" UPDATE keys \n"
" SET is_default=0 \n"
" WHERE identity_id=NEW.identity_id; \n"
" END; \n"
"CREATE TRIGGER IF NOT EXISTS \n"
" key_delete_trigger \n"
" AFTER DELETE ON keys \n"
" FOR EACH ROW \n"
" BEGIN \n"
" SELECT keyDeleted (OLD.key_name); \n"
" END; \n"
" \n"
"CREATE TABLE IF NOT EXISTS \n"
" certificates( \n"
" id INTEGER PRIMARY KEY,\n"
" key_id INTEGER NOT NULL, \n"
" certificate_name BLOB NOT NULL, \n"
" certificate_data BLOB NOT NULL, \n"
" is_default INTEGER DEFAULT 0, \n"
" FOREIGN KEY(key_id) \n"
" REFERENCES keys(id) \n"
" ON DELETE CASCADE \n"
" ON UPDATE CASCADE \n"
" ); \n"
"CREATE UNIQUE INDEX IF NOT EXISTS \n"
" certIndex ON certificates(certificate_name);\n"
"CREATE TRIGGER IF NOT EXISTS \n"
" cert_default_before_insert_trigger \n"
" BEFORE INSERT ON certificates \n"
" FOR EACH ROW \n"
" WHEN NEW.is_default=1 \n"
" BEGIN \n"
" UPDATE certificates \n"
" SET is_default=0 \n"
" WHERE key_id=NEW.key_id; \n"
" END; \n"
"CREATE TRIGGER IF NOT EXISTS \n"
" cert_default_after_insert_trigger \n"
" AFTER INSERT ON certificates \n"
" FOR EACH ROW \n"
" WHEN NOT EXISTS \n"
" (SELECT id \n"
" FROM certificates \n"
" WHERE is_default=1 \n"
" AND key_id=NEW.key_id) \n"
" BEGIN \n"
" UPDATE certificates \n"
" SET is_default=1 \n"
" WHERE certificate_name=NEW.certificate_name;\n"
" END; \n"
"CREATE TRIGGER IF NOT EXISTS \n"
" cert_default_update_trigger \n"
" BEFORE UPDATE ON certificates \n"
" FOR EACH ROW \n"
" WHEN NEW.is_default=1 AND OLD.is_default=0 \n"
" BEGIN \n"
" UPDATE certificates \n"
" SET is_default=0 \n"
" WHERE key_id=NEW.key_id; \n"
" END; \n"
"CREATE TRIGGER IF NOT EXISTS \n"
" cert_delete_trigger \n"
" AFTER DELETE ON certificates \n"
" FOR EACH ROW \n"
" BEGIN \n"
" SELECT certDeleted (OLD.certificate_name);\n"
" END; \n"
"CREATE TRIGGER IF NOT EXISTS \n"
" cert_insert_trigger \n"
" AFTER INSERT ON certificates \n"
" FOR EACH ROW \n"
" BEGIN \n"
" SELECT certInserted (NEW.certificate_name);\n"
" END; \n";
/**
* A utility function to call the normal sqlite3_bind_text where the value and length are
* value.c_str() and value.size().
*/
static int
sqlite3_bind_string(sqlite3_stmt* statement,
int index,
const string& value,
void(*destructor)(void*))
{
return sqlite3_bind_text(statement, index, value.c_str(), value.size(), destructor);
}
/**
* A utility function to call the normal sqlite3_bind_blob where the value and length are
* block.wire() and block.size().
*/
static int
sqlite3_bind_block(sqlite3_stmt* statement,
int index,
const Block& block,
void(*destructor)(void*))
{
return sqlite3_bind_blob(statement, index, block.wire(), block.size(), destructor);
}
/**
* A utility function to generate string by calling the normal sqlite3_column_text.
*/
static string
sqlite3_column_string(sqlite3_stmt* statement, int column)
{
return string(reinterpret_cast<const char*>(sqlite3_column_text(statement, column)),
sqlite3_column_bytes(statement, column));
}
/**
* A utility function to generate block by calling the normal sqlite3_column_text.
*/
static Block
sqlite3_column_block(sqlite3_stmt* statement, int column)
{
return Block(sqlite3_column_blob(statement, column), sqlite3_column_bytes(statement, column));
}
PibDb::PibDb(const string& dbDir)
{
// Determine the path of PIB DB
boost::filesystem::path dir;
if (dbDir == "") {
dir = boost::filesystem::path(getenv("HOME")) / ".ndn";
boost::filesystem::create_directories(dir);
}
else {
dir = boost::filesystem::path(dbDir);
boost::filesystem::create_directories(dir);
}
// Open PIB
int result = sqlite3_open_v2((dir / "pib.db").c_str(), &m_database,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
#ifdef NDN_CXX_DISABLE_SQLITE3_FS_LOCKING
"unix-dotfile"
#else
nullptr
#endif
);
if (result != SQLITE_OK)
throw Error("PIB DB cannot be opened/created: " + dbDir);
// enable foreign key
sqlite3_exec(m_database, "PRAGMA foreign_keys = ON", nullptr, nullptr, nullptr);
// initialize PIB specific tables
char* errorMessage = nullptr;
result = sqlite3_exec(m_database, INITIALIZATION.c_str(), nullptr, nullptr, &errorMessage);
if (result != SQLITE_OK && errorMessage != nullptr) {
sqlite3_free(errorMessage);
throw Error("PIB DB cannot be initialized");
}
// create delete trigger functions
createDbDeleteTrigger();
getOwnerName();
}
void
PibDb::createDbDeleteTrigger()
{
int res = 0;
res = sqlite3_create_function(m_database, "identityDeleted", -1, SQLITE_UTF8,
reinterpret_cast<void*>(this),
PibDb::identityDeletedFun, nullptr, nullptr);
if (res != SQLITE_OK)
throw Error("Cannot create function ``identityDeleted''");
res = sqlite3_create_function(m_database, "keyDeleted", -1, SQLITE_UTF8,
reinterpret_cast<void*>(this),
PibDb::keyDeletedFun, nullptr, nullptr);
if (res != SQLITE_OK)
throw Error("Cannot create function ``keyDeleted''");
res = sqlite3_create_function(m_database, "certDeleted", -1, SQLITE_UTF8,
reinterpret_cast<void*>(this),
PibDb::certDeletedFun, nullptr, nullptr);
if (res != SQLITE_OK)
throw Error("Cannot create function ``certDeleted''");
res = sqlite3_create_function(m_database, "certInserted", -1, SQLITE_UTF8,
reinterpret_cast<void*>(this),
PibDb::certInsertedFun, nullptr, nullptr);
if (res != SQLITE_OK)
throw Error("Cannot create function ``certInserted''");
}
void
PibDb::identityDeletedFun(sqlite3_context* context, int argc, sqlite3_value** argv)
{
BOOST_ASSERT(argc == 1);
PibDb* pibDb = reinterpret_cast<PibDb*>(sqlite3_user_data(context));
Name identity(Block(sqlite3_value_blob(argv[0]), sqlite3_value_bytes(argv[0])));
pibDb->identityDeleted(identity);
}
void
PibDb::keyDeletedFun(sqlite3_context* context, int argc, sqlite3_value** argv)
{
BOOST_ASSERT(argc == 1);
PibDb* pibDb = reinterpret_cast<PibDb*>(sqlite3_user_data(context));
Name keyName(Block(sqlite3_value_blob(argv[0]), sqlite3_value_bytes(argv[0])));
pibDb->keyDeleted(keyName);
}
void
PibDb::certDeletedFun(sqlite3_context* context, int argc, sqlite3_value** argv)
{
BOOST_ASSERT(argc == 1);
PibDb* pibDb = reinterpret_cast<PibDb*>(sqlite3_user_data(context));
Name certName(Block(sqlite3_value_blob(argv[0]), sqlite3_value_bytes(argv[0])));
pibDb->certificateDeleted(certName);
}
void
PibDb::certInsertedFun(sqlite3_context* context, int argc, sqlite3_value** argv)
{
BOOST_ASSERT(argc == 1);
PibDb* pibDb = reinterpret_cast<PibDb*>(sqlite3_user_data(context));
Name certName(Block(sqlite3_value_blob(argv[0]), sqlite3_value_bytes(argv[0])));
pibDb->certificateInserted(certName);
}
void
PibDb::updateMgmtCertificate(const IdentityCertificate& certificate)
{
const Name& keyName = certificate.getPublicKeyName();
// Name of mgmt key should be "/localhost/pib/[UserName]/mgmt/[KeyID]"
if (keyName.size() != 5 ||
keyName.compare(0, 2, LOCALHOST_PIB) ||
keyName.get(3) != MGMT_LABEL)
throw Error("PibDb::updateMgmtCertificate: certificate does not follow the naming convention");
string owner = keyName.get(2).toUri();
sqlite3_stmt* statement;
if (!m_owner.empty()) {
if (m_owner != owner)
throw Error("PibDb::updateMgmtCertificate: owner name does not match");
else {
sqlite3_prepare_v2(m_database,
"UPDATE mgmt SET local_management_cert=? WHERE owner=?",
-1, &statement, nullptr);
}
}
else {
sqlite3_prepare_v2(m_database,
"INSERT INTO mgmt (local_management_cert, owner) VALUES (?, ?)",
-1, &statement, nullptr);
}
sqlite3_bind_block(statement, 1, certificate.wireEncode(), SQLITE_TRANSIENT);
sqlite3_bind_string(statement, 2, owner, SQLITE_TRANSIENT);
sqlite3_step(statement);
sqlite3_finalize(statement);
m_owner = owner;
mgmtCertificateChanged();
}
string
PibDb::getOwnerName() const
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database, "SELECT owner FROM mgmt", -1, &statement, nullptr);
if (sqlite3_step(statement) == SQLITE_ROW) {
m_owner = sqlite3_column_string(statement, 0);
}
sqlite3_finalize(statement);
return m_owner;
}
shared_ptr<IdentityCertificate>
PibDb::getMgmtCertificate() const
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database, "SELECT local_management_cert FROM mgmt", -1, &statement, nullptr);
shared_ptr<IdentityCertificate> certificate;
if (sqlite3_step(statement) == SQLITE_ROW) {
certificate = make_shared<IdentityCertificate>();
certificate->wireDecode(sqlite3_column_block(statement, 0));
}
sqlite3_finalize(statement);
return certificate;
}
void
PibDb::setTpmLocator(const std::string& tpmLocator)
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"UPDATE mgmt SET tpm_locator=? WHERE owner=?",
-1, &statement, nullptr);
sqlite3_bind_string(statement, 1, tpmLocator, SQLITE_TRANSIENT);
sqlite3_bind_string(statement, 2, m_owner, SQLITE_TRANSIENT);
sqlite3_step(statement);
sqlite3_finalize(statement);
}
std::string
PibDb::getTpmLocator() const
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database, "SELECT tpm_locator FROM mgmt", -1, &statement, nullptr);
string tpmLocator;
if (sqlite3_step(statement) == SQLITE_ROW) {
tpmLocator = sqlite3_column_string(statement, 0);
}
sqlite3_finalize(statement);
return tpmLocator;
}
int64_t
PibDb::addIdentity(const Name& identity)
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"INSERT INTO identities (identity) values (?)",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, identity.wireEncode(), SQLITE_TRANSIENT);
sqlite3_step(statement);
sqlite3_finalize(statement);
return sqlite3_last_insert_rowid(m_database);
}
void
PibDb::deleteIdentity(const Name& identity)
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"DELETE FROM identities WHERE identity=?",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, identity.wireEncode(), SQLITE_TRANSIENT);
sqlite3_step(statement);
sqlite3_finalize(statement);
}
bool
PibDb::hasIdentity(const Name& identity) const
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"SELECT id FROM identities WHERE identity=?",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, identity.wireEncode(), SQLITE_TRANSIENT);
int result = sqlite3_step(statement);
sqlite3_finalize(statement);
if (result == SQLITE_ROW)
return true;
else
return false;
}
void
PibDb::setDefaultIdentity(const Name& identity)
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"UPDATE identities SET is_default=1 WHERE identity=?",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, identity.wireEncode(), SQLITE_TRANSIENT);
sqlite3_step(statement);
sqlite3_finalize(statement);
}
Name
PibDb::getDefaultIdentity() const
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"SELECT identity FROM identities WHERE is_default=1",
-1, &statement, nullptr);
Name identity = NON_EXISTING_IDENTITY;
if (sqlite3_step(statement) == SQLITE_ROW && sqlite3_column_bytes(statement, 0) != 0) {
identity = Name(sqlite3_column_block(statement, 0));
}
sqlite3_finalize(statement);
return identity;
}
vector<Name>
PibDb::listIdentities() const
{
vector<Name> identities;
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database, "SELECT identity FROM identities", -1, &statement, nullptr);
identities.clear();
while (sqlite3_step(statement) == SQLITE_ROW) {
Name name(sqlite3_column_block(statement, 0));
identities.push_back(name);
}
sqlite3_finalize(statement);
return identities;
}
int64_t
PibDb::addKey(const Name& keyName, const PublicKey& key)
{
if (keyName.empty())
return 0;
Name&& identity = keyName.getPrefix(-1);
if (!hasIdentity(identity))
addIdentity(identity);
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"INSERT INTO keys (identity_id, key_name, key_type, key_bits) \
values ((SELECT id FROM identities WHERE identity=?), ?, ?, ?)",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, identity.wireEncode(), SQLITE_TRANSIENT);
sqlite3_bind_block(statement, 2, keyName.wireEncode(), SQLITE_TRANSIENT);
sqlite3_bind_int(statement, 3, static_cast<int>(key.getKeyType()));
sqlite3_bind_blob(statement, 4, key.get().buf(), key.get().size(), SQLITE_STATIC);
sqlite3_step(statement);
sqlite3_finalize(statement);
return sqlite3_last_insert_rowid(m_database);
}
shared_ptr<PublicKey>
PibDb::getKey(const Name& keyName) const
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"SELECT key_bits FROM keys WHERE key_name=?"
, -1, &statement, nullptr);
sqlite3_bind_block(statement, 1, keyName.wireEncode(), SQLITE_TRANSIENT);
shared_ptr<PublicKey> key;
if (sqlite3_step(statement) == SQLITE_ROW) {
key = make_shared<PublicKey>(static_cast<const uint8_t*>(sqlite3_column_blob(statement, 0)),
sqlite3_column_bytes(statement, 0));
}
sqlite3_finalize(statement);
return key;
}
void
PibDb::deleteKey(const Name& keyName)
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"DELETE FROM keys WHERE key_name=?",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, keyName.wireEncode(), SQLITE_TRANSIENT);
sqlite3_step(statement);
sqlite3_finalize(statement);
}
bool
PibDb::hasKey(const Name& keyName) const
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"SELECT id FROM keys WHERE key_name=?",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, keyName.wireEncode(), SQLITE_TRANSIENT);
int result = sqlite3_step(statement);
sqlite3_finalize(statement);
if (result == SQLITE_ROW)
return true;
else
return false;
}
void
PibDb::setDefaultKeyNameOfIdentity(const Name& keyName)
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"UPDATE keys SET is_default=1 WHERE key_name=?",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, keyName.wireEncode(), SQLITE_TRANSIENT);
sqlite3_step(statement);
sqlite3_finalize(statement);
}
Name
PibDb::getDefaultKeyNameOfIdentity(const Name& identity) const
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"SELECT key_name FROM keys JOIN identities ON keys.identity_id=identities.id\
WHERE identities.identity=? AND keys.is_default=1",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, identity.wireEncode(), SQLITE_TRANSIENT);
Name keyName = NON_EXISTING_KEY;
if (sqlite3_step(statement) == SQLITE_ROW && sqlite3_column_bytes(statement, 0) != 0) {
keyName = Name(sqlite3_column_block(statement, 0));
}
sqlite3_finalize(statement);
return keyName;
}
vector<Name>
PibDb::listKeyNamesOfIdentity(const Name& identity) const
{
vector<Name> keyNames;
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"SELECT key_name FROM keys JOIN identities ON keys.identity_id=identities.id\
WHERE identities.identity=?",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, identity.wireEncode(), SQLITE_TRANSIENT);
keyNames.clear();
while (sqlite3_step(statement) == SQLITE_ROW) {
Name keyName(sqlite3_column_block(statement, 0));
keyNames.push_back(keyName);
}
sqlite3_finalize(statement);
return keyNames;
}
int64_t
PibDb::addCertificate(const IdentityCertificate& certificate)
{
const Name& certName = certificate.getName();
const Name& keyName = certificate.getPublicKeyName();
if (!hasKey(keyName))
addKey(keyName, certificate.getPublicKeyInfo());
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"INSERT INTO certificates \
(key_id, certificate_name, certificate_data) \
values ((SELECT id FROM keys WHERE key_name=?), ?, ?)",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, keyName.wireEncode(), SQLITE_TRANSIENT);
sqlite3_bind_block(statement, 2, certName.wireEncode(), SQLITE_TRANSIENT);
sqlite3_bind_block(statement, 3, certificate.wireEncode(), SQLITE_STATIC);
sqlite3_step(statement);
sqlite3_finalize(statement);
return sqlite3_last_insert_rowid(m_database);
}
shared_ptr<IdentityCertificate>
PibDb::getCertificate(const Name& certificateName) const
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"SELECT certificate_data FROM certificates WHERE certificate_name=?",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, certificateName.wireEncode(), SQLITE_TRANSIENT);
shared_ptr<IdentityCertificate> certificate;
if (sqlite3_step(statement) == SQLITE_ROW) {
certificate = make_shared<IdentityCertificate>();
certificate->wireDecode(sqlite3_column_block(statement, 0));
}
sqlite3_finalize(statement);
return certificate;
}
void
PibDb::deleteCertificate(const Name& certificateName)
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"DELETE FROM certificates WHERE certificate_name=?",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, certificateName.wireEncode(), SQLITE_TRANSIENT);
sqlite3_step(statement);
sqlite3_finalize(statement);
}
bool
PibDb::hasCertificate(const Name& certificateName) const
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"SELECT id FROM certificates WHERE certificate_name=?",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, certificateName.wireEncode(), SQLITE_TRANSIENT);
int result = sqlite3_step(statement);
sqlite3_finalize(statement);
if (result == SQLITE_ROW)
return true;
else
return false;
}
void
PibDb::setDefaultCertNameOfKey(const Name& certificateName)
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"UPDATE certificates SET is_default=1 WHERE certificate_name=?",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, certificateName.wireEncode(), SQLITE_TRANSIENT);
sqlite3_step(statement);
sqlite3_finalize(statement);
}
Name
PibDb::getDefaultCertNameOfKey(const Name& keyName) const
{
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"SELECT certificate_name\
FROM certificates JOIN keys ON certificates.key_id=keys.id\
WHERE keys.key_name=? AND certificates.is_default=1",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, keyName.wireEncode(), SQLITE_TRANSIENT);
Name certName = NON_EXISTING_CERTIFICATE;
if (sqlite3_step(statement) == SQLITE_ROW && sqlite3_column_bytes(statement, 0) != 0) {
certName = Name(sqlite3_column_block(statement, 0));
}
sqlite3_finalize(statement);
return certName;
}
vector<Name>
PibDb::listCertNamesOfKey(const Name& keyName) const
{
vector<Name> certNames;
sqlite3_stmt* statement;
sqlite3_prepare_v2(m_database,
"SELECT certificate_name\
FROM certificates JOIN keys ON certificates.key_id=keys.id\
WHERE keys.key_name=?",
-1, &statement, nullptr);
sqlite3_bind_block(statement, 1, keyName.wireEncode(), SQLITE_TRANSIENT);
certNames.clear();
while (sqlite3_step(statement) == SQLITE_ROW) {
Name name(sqlite3_column_block(statement, 0));
certNames.push_back(name);
}
sqlite3_finalize(statement);
return certNames;
}
} // namespace pib
} // namespace ndn
|
gpl-3.0
|
arielk/elementor
|
core/app/modules/import-export/assets/js/pages/import/import-content/import-content.js
|
1887
|
import React, { useContext, useEffect } from 'react';
import { useNavigate } from '@reach/router';
import { Context } from '../../../context/context-provider';
import Layout from '../../../templates/layout';
import PageHeader from '../../../ui/page-header/page-header';
import KitContent from '../../../shared/kit-content/kit-content';
import InlineLink from 'elementor-app/ui/molecules/inline-link';
import Button from 'elementor-app/ui/molecules/button';
import WizardFooter from 'elementor-app/organisms/wizard-footer';
import ImportButton from './components/import-button/import-button';
export default function ImportContent() {
const context = useContext( Context ),
navigate = useNavigate(),
getFooter = () => (
<WizardFooter separator justify="end">
<Button
text={ __( 'Previous', 'elementor' ) }
variant="contained"
onClick={ () => context.dispatch( { type: 'SET_FILE', payload: null } ) }
/>
<ImportButton />
</WizardFooter>
),
getLearnMoreLink = () => (
<InlineLink url="https://go.elementor.com/app-what-are-kits" italic>
{ __( 'Learn More', 'elementor' ) }
</InlineLink>
);
useEffect( () => {
if ( ! context.data.file ) {
navigate( 'import' );
}
}, [ context.data.file ] );
return (
<Layout type="import" footer={ getFooter() }>
<section className="e-app-export-kit">
<PageHeader
heading={ __( 'Import a Template Kit', 'elementor' ) }
description={ [
__( 'Choose which Elementor components - templates, content and site settings - to include in your kit.', 'elementor' ),
<React.Fragment key="description-secondary-line">
{ __( 'By default, all of your components will be imported.', 'elementor' ) } { getLearnMoreLink() }
</React.Fragment>,
] }
/>
<KitContent manifest={ context.data.uploadedData?.manifest } />
</section>
</Layout>
);
}
|
gpl-3.0
|
aravindkarthik96/bluebot-android
|
app/src/main/java/com/bluebot/bluebotapp/homePage/HomeActivityPresenter.java
|
298
|
package com.bluebot.bluebotapp.homePage;
/**
* Created by aravind karthik on 10/23/2016.
*/
public class HomeActivityPresenter {
HomeActivityView homeActivityView;
public HomeActivityPresenter(HomeActivityView homeActivityView) {
this.homeActivityView=homeActivityView;
}
}
|
gpl-3.0
|
rudin-io/wikidoclet
|
src/li/rudin/wikidoc/processor/impl/CategoryProcessor.java
|
296
|
package li.rudin.wikidoc.processor.impl;
import li.rudin.wikidoc.processor.base.ProcessorBase;
public class CategoryProcessor extends ProcessorBase
{
@Override
public void process()
{
article.addTextnl("[[Category:" + category + "]]");
article.addTextnl("[[Category:JavaDoc]]");
}
}
|
gpl-3.0
|
grueni75/GeoDiscoverer
|
Source/Platform/Target/Android/core/src/main/jni/gdal-3.2.1/alg/gdalcutline.cpp
|
15958
|
/******************************************************************************
*
* Project: High Performance Image Reprojector
* Purpose: Implement cutline/blend mask generator.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 2008, Frank Warmerdam <warmerdam@pobox.com>
* Copyright (c) 2008-2013, Even Rouault <even dot rouault at spatialys.com>
*
* 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 "cpl_port.h"
#include "gdalwarper.h"
#include <cmath>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_string.h"
#include "gdal.h"
#include "gdal_alg.h"
#include "ogr_api.h"
#include "ogr_core.h"
#include "ogr_geometry.h"
#include "ogr_geos.h"
CPL_CVSID("$Id: gdalcutline.cpp ab04d3bd6e63f3824c0d4a3bd40e3e3f3d84740a 2020-10-09 01:31:35 +0200 Even Rouault $")
/************************************************************************/
/* BlendMaskGenerator() */
/************************************************************************/
#ifndef HAVE_GEOS
static CPLErr
BlendMaskGenerator( int /* nXOff */, int /* nYOff */,
int /* nXSize */, int /* nYSize */,
GByte * /* pabyPolyMask */,
float * /* pafValidityMask */,
OGRGeometryH /* hPolygon */,
double /* dfBlendDist */ )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Blend distance support not available without the GEOS library.");
return CE_Failure;
}
#else
static CPLErr
BlendMaskGenerator( int nXOff, int nYOff, int nXSize, int nYSize,
GByte *pabyPolyMask, float *pafValidityMask,
OGRGeometryH hPolygon, double dfBlendDist )
{
/* -------------------------------------------------------------------- */
/* Convert the polygon into a collection of lines so that we */
/* measure distance from the edge even on the inside. */
/* -------------------------------------------------------------------- */
OGRGeometry *poLines =
OGRGeometryFactory::forceToMultiLineString(
reinterpret_cast<OGRGeometry *>(hPolygon)->clone() );
/* -------------------------------------------------------------------- */
/* Prepare a clipping polygon a bit bigger than the area of */
/* interest in the hopes of simplifying the cutline down to */
/* stuff that will be relevant for this area of interest. */
/* -------------------------------------------------------------------- */
CPLString osClipRectWKT;
osClipRectWKT.Printf( "POLYGON((%g %g,%g %g,%g %g,%g %g,%g %g))",
nXOff - (dfBlendDist + 1),
nYOff - (dfBlendDist + 1),
nXOff + nXSize + (dfBlendDist + 1),
nYOff - (dfBlendDist + 1),
nXOff + nXSize + (dfBlendDist + 1),
nYOff + nYSize + (dfBlendDist + 1),
nXOff - (dfBlendDist + 1),
nYOff + nYSize + (dfBlendDist + 1),
nXOff - (dfBlendDist + 1),
nYOff - (dfBlendDist + 1) );
OGRPolygon *poClipRect = nullptr;
OGRGeometryFactory::createFromWkt( osClipRectWKT.c_str(), nullptr,
reinterpret_cast<OGRGeometry**>(&poClipRect) );
if( poClipRect )
{
// If it does not intersect the polym, zero the mask and return.
if( !reinterpret_cast<OGRGeometry *>(hPolygon)->Intersects(poClipRect) )
{
memset( pafValidityMask, 0, sizeof(float) * nXSize * nYSize );
delete poLines;
delete poClipRect;
return CE_None;
}
// If it does not intersect the line at all, just return.
else if( !static_cast<OGRGeometry *>(poLines)->Intersects(poClipRect) )
{
delete poLines;
delete poClipRect;
return CE_None;
}
OGRGeometry *poClippedLines = poLines->Intersection(poClipRect);
delete poLines;
poLines = poClippedLines;
delete poClipRect;
}
/* -------------------------------------------------------------------- */
/* Convert our polygon into GEOS format, and compute an */
/* envelope to accelerate later distance operations. */
/* -------------------------------------------------------------------- */
OGREnvelope sEnvelope;
GEOSContextHandle_t hGEOSCtxt = OGRGeometry::createGEOSContext();
GEOSGeom poGEOSPoly = poLines->exportToGEOS(hGEOSCtxt);
OGR_G_GetEnvelope( hPolygon, &sEnvelope );
delete poLines;
// This check was already done in the calling
// function and should never be true.
// if( sEnvelope.MinY - dfBlendDist > nYOff+nYSize
// || sEnvelope.MaxY + dfBlendDist < nYOff
// || sEnvelope.MinX - dfBlendDist > nXOff+nXSize
// || sEnvelope.MaxX + dfBlendDist < nXOff )
// return CE_None;
const int iXMin =
std::max(0,
static_cast<int>(floor(sEnvelope.MinX - dfBlendDist - nXOff)));
const int iXMax =
std::min(nXSize,
static_cast<int>(ceil(sEnvelope.MaxX + dfBlendDist - nXOff)));
const int iYMin =
std::max(0,
static_cast<int>(floor(sEnvelope.MinY - dfBlendDist - nYOff)));
const int iYMax =
std::min(nYSize,
static_cast<int>(ceil(sEnvelope.MaxY + dfBlendDist - nYOff)));
/* -------------------------------------------------------------------- */
/* Loop over potential area within blend line distance, */
/* processing each pixel. */
/* -------------------------------------------------------------------- */
for( int iY = 0; iY < nYSize; iY++ )
{
double dfLastDist = 0.0;
for( int iX = 0; iX < nXSize; iX++ )
{
if( iX < iXMin || iX >= iXMax
|| iY < iYMin || iY > iYMax
|| dfLastDist > dfBlendDist + 1.5 )
{
if( pabyPolyMask[iX + iY * nXSize] == 0 )
pafValidityMask[iX + iY * nXSize] = 0.0;
dfLastDist -= 1.0;
continue;
}
CPLString osPointWKT;
osPointWKT.Printf( "POINT(%d.5 %d.5)", iX + nXOff, iY + nYOff );
GEOSGeom poGEOSPoint = GEOSGeomFromWKT_r( hGEOSCtxt, osPointWKT );
double dfDist = 0.0;
GEOSDistance_r( hGEOSCtxt, poGEOSPoly, poGEOSPoint, &dfDist );
GEOSGeom_destroy_r( hGEOSCtxt, poGEOSPoint );
dfLastDist = dfDist;
if( dfDist > dfBlendDist )
{
if( pabyPolyMask[iX + iY * nXSize] == 0 )
pafValidityMask[iX + iY * nXSize] = 0.0;
continue;
}
const double dfRatio =
pabyPolyMask[iX + iY * nXSize] == 0
? 0.5 - (dfDist / dfBlendDist) * 0.5 // Outside.
: 0.5 + (dfDist / dfBlendDist) * 0.5; // Inside.
pafValidityMask[iX + iY * nXSize] *= static_cast<float>(dfRatio);
}
}
/* -------------------------------------------------------------------- */
/* Cleanup */
/* -------------------------------------------------------------------- */
GEOSGeom_destroy_r( hGEOSCtxt, poGEOSPoly );
OGRGeometry::freeGEOSContext( hGEOSCtxt );
return CE_None;
}
#endif // HAVE_GEOS
/************************************************************************/
/* CutlineTransformer() */
/* */
/* A simple transformer for the cutline that just offsets */
/* relative to the current chunk. */
/************************************************************************/
static int CutlineTransformer( void *pTransformArg,
int bDstToSrc,
int nPointCount,
double *x,
double *y,
double * /* z */,
int * /* panSuccess */ )
{
int nXOff = static_cast<int *>(pTransformArg)[0];
int nYOff = static_cast<int *>(pTransformArg)[1];
if( bDstToSrc )
{
nXOff *= -1;
nYOff *= -1;
}
for( int i = 0; i < nPointCount; i++ )
{
x[i] -= nXOff;
y[i] -= nYOff;
}
return TRUE;
}
/************************************************************************/
/* GDALWarpCutlineMasker() */
/* */
/* This function will generate a source mask based on a */
/* provided cutline, and optional blend distance. */
/************************************************************************/
CPLErr
GDALWarpCutlineMasker( void *pMaskFuncArg,
int /* nBandCount */,
GDALDataType /* eType */,
int nXOff, int nYOff, int nXSize, int nYSize,
GByte ** /*ppImageData */,
int bMaskIsFloat, void *pValidityMask )
{
if( nXSize < 1 || nYSize < 1 )
return CE_None;
/* -------------------------------------------------------------------- */
/* Do some minimal checking. */
/* -------------------------------------------------------------------- */
if( !bMaskIsFloat )
{
CPLAssert( false );
return CE_Failure;
}
GDALWarpOptions *psWO = static_cast<GDALWarpOptions *>(pMaskFuncArg);
if( psWO == nullptr || psWO->hCutline == nullptr )
{
CPLAssert( false );
return CE_Failure;
}
GDALDriverH hMemDriver = GDALGetDriverByName("MEM");
if( hMemDriver == nullptr )
{
CPLError(CE_Failure, CPLE_AppDefined,
"GDALWarpCutlineMasker needs MEM driver");
return CE_Failure;
}
/* -------------------------------------------------------------------- */
/* Check the polygon. */
/* -------------------------------------------------------------------- */
OGRGeometryH hPolygon = static_cast<OGRGeometryH>(psWO->hCutline);
if( wkbFlatten(OGR_G_GetGeometryType(hPolygon)) != wkbPolygon
&& wkbFlatten(OGR_G_GetGeometryType(hPolygon)) != wkbMultiPolygon )
{
CPLError(CE_Failure, CPLE_NotSupported,
"Cutline should be a polygon or a multipolygon");
return CE_Failure;
}
OGREnvelope sEnvelope;
OGR_G_GetEnvelope( hPolygon, &sEnvelope );
float *pafMask = static_cast<float *>(pValidityMask);
if( sEnvelope.MaxX + psWO->dfCutlineBlendDist < nXOff
|| sEnvelope.MinX - psWO->dfCutlineBlendDist > nXOff + nXSize
|| sEnvelope.MaxY + psWO->dfCutlineBlendDist < nYOff
|| sEnvelope.MinY - psWO->dfCutlineBlendDist > nYOff + nYSize )
{
// We are far from the blend line - everything is masked to zero.
// It would be nice to realize no work is required for this whole
// chunk!
memset( pafMask, 0, sizeof(float) * nXSize * nYSize );
return CE_None;
}
/* -------------------------------------------------------------------- */
/* Create a byte buffer into which we can burn the */
/* mask polygon and wrap it up as a memory dataset. */
/* -------------------------------------------------------------------- */
GByte *pabyPolyMask = static_cast<GByte *>(CPLCalloc(nXSize, nYSize));
char szDataPointer[100] = {};
// cppcheck-suppress redundantCopy
snprintf( szDataPointer, sizeof(szDataPointer), "DATAPOINTER=" );
CPLPrintPointer(
szDataPointer+strlen(szDataPointer),
pabyPolyMask,
static_cast<int>(sizeof(szDataPointer) - strlen(szDataPointer)) );
GDALDatasetH hMemDS = GDALCreate( hMemDriver, "warp_temp",
nXSize, nYSize, 0, GDT_Byte, nullptr );
char *apszOptions[] = { szDataPointer, nullptr };
GDALAddBand( hMemDS, GDT_Byte, apszOptions );
double adfGeoTransform[6] = { 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 };
GDALSetGeoTransform( hMemDS, adfGeoTransform );
/* -------------------------------------------------------------------- */
/* Burn the polygon into the mask with 1.0 values. */
/* -------------------------------------------------------------------- */
int nTargetBand = 1;
double dfBurnValue = 255.0;
char **papszRasterizeOptions = nullptr;
if( CPLFetchBool( psWO->papszWarpOptions, "CUTLINE_ALL_TOUCHED", false ))
papszRasterizeOptions =
CSLSetNameValue( papszRasterizeOptions, "ALL_TOUCHED", "TRUE" );
int anXYOff[2] = { nXOff, nYOff };
CPLErr eErr =
GDALRasterizeGeometries( hMemDS, 1, &nTargetBand,
1, &hPolygon,
CutlineTransformer, anXYOff,
&dfBurnValue, papszRasterizeOptions,
nullptr, nullptr );
CSLDestroy( papszRasterizeOptions );
// Close and ensure data flushed to underlying array.
GDALClose( hMemDS );
/* -------------------------------------------------------------------- */
/* In the case with no blend distance, we just apply this as a */
/* mask, zeroing out everything outside the polygon. */
/* -------------------------------------------------------------------- */
if( psWO->dfCutlineBlendDist == 0.0 )
{
for( int i = nXSize * nYSize - 1; i >= 0; i-- )
{
if( pabyPolyMask[i] == 0 )
static_cast<float *>(pValidityMask)[i] = 0.0;
}
}
else
{
eErr = BlendMaskGenerator( nXOff, nYOff, nXSize, nYSize,
pabyPolyMask,
static_cast<float *>(pValidityMask),
hPolygon, psWO->dfCutlineBlendDist );
}
/* -------------------------------------------------------------------- */
/* Clean up. */
/* -------------------------------------------------------------------- */
CPLFree( pabyPolyMask );
return eErr;
}
|
gpl-3.0
|
eishub/eis
|
eis/src/main/java/eis/eis2java/environment/AbstractEnvironment.java
|
5893
|
package eis.eis2java.environment;
import java.util.HashMap;
import java.util.Map;
import eis.EIDefaultImpl;
import eis.PerceptUpdate;
import eis.eis2java.handlers.ActionHandler;
import eis.eis2java.handlers.DefaultActionHandler;
import eis.eis2java.handlers.DefaultPerceptHandler;
import eis.eis2java.handlers.PerceptHandler;
import eis.exceptions.ActException;
import eis.exceptions.EntityException;
import eis.exceptions.ManagementException;
import eis.exceptions.NoEnvironmentException;
import eis.exceptions.PerceiveException;
import eis.exceptions.RelationException;
import eis.iilang.Action;
import eis.iilang.Parameter;
/**
* Base implementation for environments that want to work with automated percept
* and action discovery in EIS2Java.
*/
public abstract class AbstractEnvironment extends EIDefaultImpl {
private static final long serialVersionUID = 1L;
/** Map of entity names to objects representing those entities */
private final Map<String, Object> entities = new HashMap<>();
/** Maps an entity to an action handler */
private final Map<String, PerceptHandler> perceptHandlers = new HashMap<>();
/** Maps a Class to a map of action names and methods */
private final Map<String, ActionHandler> actionHandlers = new HashMap<>();
/**
* Couples a name to an entity and parses it's annotations for percepts and
* actions.
*
* @param name The name of the entity.
* @param entity The entity itself.
* @param <T> the type of the entity
* @throws EntityException if the entity could not be added.
*/
public final <T> void registerEntity(final String name, final T entity) throws EntityException {
registerEntity(name, entity, new DefaultActionHandler(entity), new DefaultPerceptHandler(entity));
}
/**
* Couples a name to an entity and parses it's annotations for percepts and
* actions using the specified handlers.
*
* @param name The name of the entity.
* @param entity The entity itself.
* @param actionHandler the associated action handler.
* @param <T> the type of the entity
*
* @param perceptHandler the associated percept handler.
* @throws EntityException if the entity could not be added.
*/
public final <T> void registerEntity(final String name, final T entity, final ActionHandler actionHandler,
final PerceptHandler perceptHandler) throws EntityException {
this.actionHandlers.put(name, actionHandler);
this.perceptHandlers.put(name, perceptHandler);
this.entities.put(name, entity);
addEntity(name);
}
/**
* Couples a name to an entity and parses it's annotations for percepts and
* actions.
*
* @param <T> the type of the entity
*
* @param name The name of the entity.
* @param type The type of entity
* @param entity The entity itself.
* @throws EntityException if the entity could not be added.
*/
public final <T> void registerEntity(final String name, final String type, final T entity) throws EntityException {
registerEntity(name, type, entity, new DefaultActionHandler(entity), new DefaultPerceptHandler(entity));
}
/**
* Couples a name to an entity and parses it's annotations for percepts and
* actions using the specified handlers.
* <p>
* Your environment must be able to handle
* {@link #getAllPercepts(String, String...)} and
* {@link #getAllPerceptsFromEntity(String)} when this is called.
*
*
* @param name The name of the entity.
* @param type The type of entity
* @param entity The entity itself.
* @param actionHandler the associated action handler.
* @param <T> the type of the entity
*
* @param perceptHandler the associated percept handler.
* @throws EntityException if the entity could not be added.
*/
public final <T> void registerEntity(final String name, final String type, final T entity,
final ActionHandler actionHandler, final PerceptHandler perceptHandler) throws EntityException {
this.actionHandlers.put(name, actionHandler);
this.perceptHandlers.put(name, perceptHandler);
this.entities.put(name, entity);
addEntity(name, type);
}
@Override
public final void deleteEntity(final String name) throws EntityException, RelationException {
super.deleteEntity(name);
this.entities.remove(name);
this.actionHandlers.remove(name);
this.perceptHandlers.remove(name);
}
/**
* Retrieve an entity for a given name.
*
* @param <T> The class of entity to return.
* @param name The name of the entity.
* @return the entity behind this name
*/
@SuppressWarnings("unchecked")
public final <T> T getEntity(final String name) {
return (T) this.entities.get(name);
}
@Override
protected final PerceptUpdate getPerceptsForEntity(final String name)
throws PerceiveException, NoEnvironmentException {
final PerceptHandler handler = this.perceptHandlers.get(name);
if (handler == null) {
throw new PerceiveException("Entity with name " + name + " has no handler");
}
return handler.getPercepts();
}
@Override
protected final boolean isSupportedByEntity(final Action action, final String name) {
final ActionHandler handler = this.actionHandlers.get(name);
return handler.isSupportedByEntity(action);
}
@Override
protected final void performEntityAction(final Action action, final String name) throws ActException {
final ActionHandler handler = this.actionHandlers.get(name);
if (handler == null) {
throw new ActException(ActException.FAILURE, "Entity with name " + name + " has no handler");
}
handler.performAction(action);
}
@Override
public void reset(final Map<String, Parameter> parameters) throws ManagementException {
super.reset(parameters);
for (final PerceptHandler handler : this.perceptHandlers.values()) {
handler.reset();
}
for (final ActionHandler handler : this.actionHandlers.values()) {
handler.reset();
}
}
}
|
gpl-3.0
|
NGO-DB/ndb-core
|
src/app/features/historical-data/demo-historical-data-generator.ts
|
2371
|
import { DemoDataGenerator } from "../../core/demo-data/demo-data-generator";
import { HistoricalEntityData } from "./historical-entity-data";
import { Injectable } from "@angular/core";
import { DemoChildGenerator } from "../../child-dev-project/children/demo-data-generators/demo-child-generator.service";
import { ConfigService } from "../../core/config/config.service";
import {
CONFIGURABLE_ENUM_CONFIG_PREFIX,
ConfigurableEnumConfig,
} from "../../core/configurable-enum/configurable-enum.interface";
import { faker } from "../../core/demo-data/faker";
import { ENTITY_CONFIG_PREFIX } from "../../core/entity/model/entity";
export class DemoHistoricalDataConfig {
minCountAttributes: number;
maxCountAttributes: number;
}
@Injectable()
export class DemoHistoricalDataGenerator extends DemoDataGenerator<HistoricalEntityData> {
static provider(config: DemoHistoricalDataConfig) {
return [
{
provide: DemoHistoricalDataGenerator,
useClass: DemoHistoricalDataGenerator,
},
{ provide: DemoHistoricalDataConfig, useValue: config },
];
}
constructor(
private childrenGenerator: DemoChildGenerator,
private configService: ConfigService,
private config: DemoHistoricalDataConfig
) {
super();
}
protected generateEntities(): HistoricalEntityData[] {
const attributes: any[] = this.configService
.getConfig<any>(ENTITY_CONFIG_PREFIX + HistoricalEntityData.ENTITY_TYPE)
.attributes.map((attr) => attr.name);
const ratingAnswer = this.configService.getConfig<ConfigurableEnumConfig>(
CONFIGURABLE_ENUM_CONFIG_PREFIX + "rating-answer"
);
const entities: HistoricalEntityData[] = [];
for (const child of this.childrenGenerator.entities) {
const countOfData =
faker.datatype.number(this.config.maxCountAttributes) +
this.config.minCountAttributes;
const historicalDataOfChild = [...Array(countOfData)].map(() => {
const historicalData = new HistoricalEntityData();
historicalData.date = faker.date.past();
historicalData.relatedEntity = child.getId();
for (const attribute of attributes) {
historicalData[attribute] = faker.random.arrayElement(ratingAnswer);
}
return historicalData;
});
entities.push(...historicalDataOfChild);
}
return entities;
}
}
|
gpl-3.0
|
kevoree-modeling/java2typescript
|
transpiler/src/test/java/sources/strings/ClassFields.java
|
843
|
/**
* Copyright 2017 The Java2TypeScript Authors. All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 sources.strings;
public class ClassFields {
String str = new String("foo");
String str2 = String.join(", ", new String[]{"a", "b", "c"});
public String[] values = new String[0];
}
|
gpl-3.0
|
snegron17/Horas-Comunitarias
|
app.js
|
1457
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var search = require('./routes/search');
var ads = require('./routes/ads');
var team = require('./routes/team');
var survey = require('./routes/survey');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/search', search);
app.use('/team', team);
app.use('/registracion', ads);
app.use('/survey', survey);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
|
gpl-3.0
|
michelesr/ingsw-project
|
project/doc/html/search/functions_9.js
|
164
|
var searchData=
[
['opensession',['OpenSession',['../classproject_1_1Models_1_1Session.html#a0da87c701e8e2e3be052899bfb8a2af8',1,'project::Models::Session']]]
];
|
gpl-3.0
|
dilirove92/Asistente-de-Pacientes
|
tables/TblTipoActividad.java
|
2406
|
package com.Notifications.patientssassistant.tables;
import com.Notifications.patientssassistant.R;
import android.util.Log;
import com.orm.SugarRecord;
import com.orm.query.Condition;
import com.orm.query.Select;
public class TblTipoActividad extends SugarRecord<TblTipoActividad>{
private Long IdTipoActividad;
private String TipoActividad;
private String DescripcionTipoAct;
private Boolean Eliminado;
public TblTipoActividad() {super();}
public TblTipoActividad(Long idTipoActividad, String tipoActividad, String descripcionTipoAct, Boolean eliminado) {
super();
this.IdTipoActividad = idTipoActividad;
this.TipoActividad = tipoActividad;
this.DescripcionTipoAct = descripcionTipoAct;
this.Eliminado = eliminado;
}
public void EliminarPorIdTipoActividadRegTblTipoActividad(Long idTipoActividad) {
try {
//ELIMINAR ACTIVIDADES POR ID_TIPO_ACTIVIDAD
TblActividades laAct=new TblActividades();
laAct.EliminarPorIdTipoActividadRegTblActividades(idTipoActividad);
//FINALMENTE SE ELIMINA EL TIPO DE ACTIVIDAD
TblTipoActividad elTipoActividad = Select.from(TblTipoActividad.class).where(Condition.prop("ID_TIPO_ACTIVIDAD").eq(idTipoActividad)).first();
elTipoActividad.delete();
} catch (Exception e) {
Log.e(String.valueOf(R.string.ErrorEliminarTipAct), e.getMessage());
}
}
public Long getIdTipoActividad() {
return IdTipoActividad;
}
public void setIdTipoActividad(Long idTipoActividad) {
IdTipoActividad = idTipoActividad;
}
public String getTipoActividad() {
return TipoActividad;
}
public void setTipoActividad(String tipoActividad) {
TipoActividad = tipoActividad;
}
public String getDescripcionTipoAct() {
return DescripcionTipoAct;
}
public void setDescripcionTipoAct(String descripcionTipoAct) {
DescripcionTipoAct = descripcionTipoAct;
}
public Boolean getEliminado() {
return Eliminado;
}
public void setEliminado(Boolean eliminado) {
Eliminado = eliminado;
}
public static void EliminarDatos(){
TblTipoActividad.executeQuery("delete from "+TblTipoActividad.getTableName(TblTipoActividad.class));
if(TblTipoActividad.count(TblTipoActividad.class)==0) {
Log.i("TBLTIPOACTIVIDAD","------------->Eliminado");
}else{
Log.i("TBLTIPOACTIVIDAD","-------------> NOOOOOO Eliminado :'(");
}
}
}
|
gpl-3.0
|
MrCerealGuy/Stonecraft
|
games/stonecraft_game/mods/cottages/nodes_historic.lua
|
8216
|
---------------------------------------------------------------------------------------
-- decoration and building material
---------------------------------------------------------------------------------------
-- * includes a wagon wheel that can be used as decoration on walls or to build (stationary) wagons
-- * dirt road - those are more natural in small old villages than cobble roads
-- * loam - no, old buildings are usually not built out of clay; loam was used
-- * straw - useful material for roofs
-- * glass pane - an improvement compared to fence posts as windows :-)
---------------------------------------------------------------------------------------
local S = cottages.S
-- can be used to buid real stationary wagons or attached to walls as decoration
minetest.register_node("cottages:wagon_wheel", {
description = S("Wagon wheel"),
drawtype = "signlike",
tiles = {"cottages_wagonwheel.png"}, -- done by VanessaE!
inventory_image = "cottages_wagonwheel.png",
wield_image = "cottages_wagonwheel.png",
paramtype = "light",
paramtype2 = "wallmounted",
sunlight_propagates = true,
walkable = false,
selection_box = {
type = "wallmounted",
},
groups = {choppy=2,dig_immediate=2,attached_node=1},
legacy_wallmounted = true,
is_ground_content = false,
})
-- people didn't use clay for houses; they did build with loam
minetest.register_node("cottages:loam", {
description = S("Loam"),
tiles = {"cottages_loam.png"},
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2},
groups = {crumbly=3},
sounds = cottages.sounds.dirt,
is_ground_content = false,
})
-- create stairs if possible
if( minetest.get_modpath("stairs") and stairs and stairs.register_stair_and_slab) then
stairs.register_stair_and_slab("loam", "cottages:loam",
{snappy=2,choppy=2,oddly_breakable_by_hand=2},
{"cottages_loam.png"},
S("Loam Stairs"),
S("Loam Slab"),
cottages.sounds.dirt)
if( minetest.registered_nodes["default:clay"]) then
stairs.register_stair_and_slab("clay", "default:clay",
{crumbly=3},
{"cottages_clay.png"},
S("Clay Stairs"),
S("Clay Slab"),
cottages.sounds.dirt)
end
end
-- straw is a common material for places where animals are kept indoors
-- right now, this block mostly serves as a placeholder
minetest.register_node("cottages:straw_ground", {
description = S("straw ground for animals"),
tiles = {cottages.straw_texture,"cottages_loam.png","cottages_loam.png","cottages_loam.png","cottages_loam.png","cottages_loam.png"},
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2},
groups = {crumbly=3},
sounds = cottages.sounds.leaves,
is_ground_content = false,
})
-- note: these houses look good with a single fence pile as window! the glass pane is the version for 'richer' inhabitants
minetest.register_node("cottages:glass_pane", {
description = S("Simple glass pane (centered)"),
drawtype = "nodebox",
-- top, bottom, side1, side2, inner, outer
tiles = {"cottages_glass_pane.png"},
paramtype = "light",
paramtype2 = "facedir",
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2},
node_box = {
type = "fixed",
fixed = {
{ -0.5, -0.5, -0.05, 0.5, 0.5, 0.05},
},
},
selection_box = {
type = "fixed",
fixed = {
{ -0.5, -0.5, -0.05, 0.5, 0.5, 0.05},
},
},
is_ground_content = false,
})
minetest.register_node("cottages:glass_pane_side", {
description = S("Simple glass pane"),
drawtype = "nodebox",
-- top, bottom, side1, side2, inner, outer
tiles = {"cottages_glass_pane.png"},
paramtype = "light",
paramtype2 = "facedir",
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2},
node_box = {
type = "fixed",
fixed = {
{ -0.5, -0.5, -0.40, 0.5, 0.5, -0.50},
},
},
selection_box = {
type = "fixed",
fixed = {
{ -0.5, -0.5, -0.40, 0.5, 0.5, -0.50},
},
},
is_ground_content = false,
})
---------------------------------------------------------------------------------------
-- a very small wooden slab
---------------------------------------------------------------------------------------
minetest.register_node("cottages:wood_flat", {
description = S("Flat wooden planks"),
drawtype = "nodebox",
-- top, bottom, side1, side2, inner, outer
tiles = {"cottages_minimal_wood.png"},
paramtype = "light",
paramtype2 = "facedir",
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2},
node_box = {
type = "fixed",
fixed = {
{ -0.5, -0.5, -0.50, 0.5, -0.5+1/16, 0.50},
},
},
selection_box = {
type = "fixed",
fixed = {
{ -0.5, -0.5, -0.50, 0.5, -0.5+1/16, 0.50},
},
},
is_ground_content = false,
on_place = minetest.rotate_node,
})
---------------------------------------------------------------------------------------
-- useful for building tents
---------------------------------------------------------------------------------------
minetest.register_node("cottages:wool_tent", {
description = S("Wool for tents"),
drawtype = "nodebox",
-- top, bottom, side1, side2, inner, outer
tiles = {"cottages_wool.png"},
paramtype = "light",
paramtype2 = "facedir",
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2},
node_box = {
type = "fixed",
fixed = {
{ -0.5, -0.5, -0.50, 0.5, -0.5+1/16, 0.50},
},
},
selection_box = {
type = "fixed",
fixed = {
{ -0.5, -0.5, -0.50, 0.5, -0.5+1/16, 0.50},
},
},
is_ground_content = false,
on_place = minetest.rotate_node,
})
-- a fallback for cases in which there is no wool
if( not( minetest.registered_nodes["wool:white"])) then
minetest.register_node("cottages:wool", {
description = "Wool",
tiles = {"cottages_wool.png"},
is_ground_content = false,
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1},
})
else
minetest.register_alias("cottages:wool", "wool:white")
end
---------------------------------------------------------------------------------------
-- crafting receipes
---------------------------------------------------------------------------------------
minetest.register_craft({
output = "cottages:wagon_wheel 3",
recipe = {
{cottages.craftitem_iron, cottages.craftitem_stick, cottages.craftitem_iron },
{cottages.craftitem_stick, cottages.craftitem_steel, cottages.craftitem_stick },
{cottages.craftitem_iron, cottages.craftitem_stick, cottages.craftitem_iron }
}
})
-- run a wagon wheel over dirt :-)
minetest.register_craft({
output = "cottages:feldweg 4",
recipe = {
{"", "cottages:wagon_wheel", "" },
{cottages.craftitem_dirt,cottages.craftitem_dirt,cottages.craftitem_dirt }
},
replacements = { {'cottages:wagon_wheel', 'cottages:wagon_wheel'}, }
})
minetest.register_craft({
output = "cottages:loam 4",
recipe = {
{cottages.craftitem_sand},
{cottages.craftitem_clay}
}
})
minetest.register_craft({
output = "cottages:straw_ground 2",
recipe = {
{"cottages:straw_mat" },
{"cottages:loam"}
}
})
minetest.register_craft({
output = "cottages:glass_pane 4",
recipe = {
{cottages.craftitem_stick, cottages.craftitem_stick, cottages.craftitem_stick },
{cottages.craftitem_stick, cottages.craftitem_glass, cottages.craftitem_stick },
{cottages.craftitem_stick, cottages.craftitem_stick, cottages.craftitem_stick }
}
})
minetest.register_craft({
output = "cottages:glass_pane_side",
recipe = {
{"cottages:glass_pane"},
}
})
minetest.register_craft({
output = "cottages:glass_pane",
recipe = {
{"cottages:glass_pane_side"},
}
})
minetest.register_craft({
output = "cottages:wood_flat 16",
recipe = {
{cottages.craftitem_stick, "farming:string",cottages.craftitem_stick },
{cottages.craftitem_stick, "", cottages.craftitem_stick },
}
})
minetest.register_craft({
output = "cottages:wool_tent 2",
recipe = {
{"farming:string", "farming:string"},
{"",cottages.craftitem_stick}
}
})
minetest.register_craft({
output = "cottages:wool",
recipe = {
{"cottages:wool_tent", "cottages:wool_tent"}
}
})
|
gpl-3.0
|
haywoodspartan/Aura-Personal-Build
|
src/Mabi/Const/Regions.cs
|
506
|
// Copyright (c) Aura development team - Licensed under GNU GPL
// For more information, see license file in the main folder
namespace Aura.Mabi.Const
{
public enum EventType : int
{
Unk1 = 1,
AreaChange = 10, // ? (texts, bgm change)
Collision = 14,
CreatureSpawn = 2000,
}
public enum SignalType : int
{
/// <summary>
/// Triggered by entering event area.
/// </summary>
Enter = 101,
/// <summary>
/// Triggered by leaving event area.
/// </summary>
Leave = 102,
}
}
|
gpl-3.0
|
SciCatProject/catanie
|
src/app/shared/sdk/models/Proposal.ts
|
4143
|
/* eslint-disable */
import {
Attachment
} from '../index';
declare var Object: any;
export interface ProposalInterface {
"proposalId": string;
"pi_email"?: string;
"pi_firstname"?: string;
"pi_lastname"?: string;
"email": string;
"firstname"?: string;
"lastname"?: string;
"title"?: string;
"abstract"?: string;
"startTime"?: Date;
"endTime"?: Date;
"ownerGroup": string;
"accessGroups"?: Array<any>;
"createdBy"?: string;
"updatedBy"?: string;
"MeasurementPeriodList"?: Array<any>;
"createdAt"?: Date;
"updatedAt"?: Date;
measurementPeriods?: any[];
attachments?: Attachment[];
}
export class Proposal implements ProposalInterface {
"proposalId": string;
"pi_email": string;
"pi_firstname": string;
"pi_lastname": string;
"email": string;
"firstname": string;
"lastname": string;
"title": string;
"abstract": string;
"startTime": Date;
"endTime": Date;
"ownerGroup": string;
"accessGroups": Array<any>;
"createdBy": string;
"updatedBy": string;
"MeasurementPeriodList": Array<any>;
"createdAt": Date;
"updatedAt": Date;
measurementPeriods: any[];
attachments: Attachment[];
constructor(data?: ProposalInterface) {
Object.assign(this, data);
}
/**
* The name of the model represented by this $resource,
* i.e. `Proposal`.
*/
public static getModelName() {
return "Proposal";
}
/**
* @method factory
* @author Jonathan Casarrubias
* @license MIT
* This method creates an instance of Proposal for dynamic purposes.
**/
public static factory(data: ProposalInterface): Proposal{
return new Proposal(data);
}
/**
* @method getModelDefinition
* @author Julien Ledun
* @license MIT
* This method returns an object that represents some of the model
* definitions.
**/
public static getModelDefinition() {
return {
name: 'Proposal',
plural: 'Proposals',
path: 'Proposals',
idName: 'proposalId',
properties: {
"proposalId": {
name: 'proposalId',
type: 'string'
},
"pi_email": {
name: 'pi_email',
type: 'string'
},
"pi_firstname": {
name: 'pi_firstname',
type: 'string'
},
"pi_lastname": {
name: 'pi_lastname',
type: 'string'
},
"email": {
name: 'email',
type: 'string'
},
"firstname": {
name: 'firstname',
type: 'string'
},
"lastname": {
name: 'lastname',
type: 'string'
},
"title": {
name: 'title',
type: 'string'
},
"abstract": {
name: 'abstract',
type: 'string'
},
"startTime": {
name: 'startTime',
type: 'Date'
},
"endTime": {
name: 'endTime',
type: 'Date'
},
"ownerGroup": {
name: 'ownerGroup',
type: 'string'
},
"accessGroups": {
name: 'accessGroups',
type: 'Array<any>'
},
"createdBy": {
name: 'createdBy',
type: 'string'
},
"updatedBy": {
name: 'updatedBy',
type: 'string'
},
"MeasurementPeriodList": {
name: 'MeasurementPeriodList',
type: 'Array<any>',
default: <any>[]
},
"createdAt": {
name: 'createdAt',
type: 'Date'
},
"updatedAt": {
name: 'updatedAt',
type: 'Date'
},
},
relations: {
measurementPeriods: {
name: 'measurementPeriods',
type: 'any[]',
model: '',
relationType: 'embedsMany',
keyFrom: 'MeasurementPeriodList',
keyTo: 'id'
},
attachments: {
name: 'attachments',
type: 'Attachment[]',
model: 'Attachment',
relationType: 'hasMany',
keyFrom: 'proposalId',
keyTo: 'proposalId'
},
}
}
}
}
|
gpl-3.0
|
dstockhammer/burgerama
|
Services/Venues/Data/Converters/VenueConverter.cs
|
1588
|
using System;
using System.Diagnostics.Contracts;
using System.Linq;
using Burgerama.Services.Venues.Data.Models;
using Burgerama.Services.Venues.Domain;
namespace Burgerama.Services.Venues.Data.Converters
{
internal static class VenueConverter
{
public static VenueModel ToModel(this Venue venue)
{
Contract.Requires<ArgumentNullException>(venue != null);
return new VenueModel
{
Id = venue.Id.ToString(),
Name = venue.Name,
Location = venue.Location,
CreatedByUser = venue.CreatedByUser,
CreatedOn = venue.CreatedOn,
Url = venue.Url,
Description = venue.Description,
Address = venue.Address,
Outings = venue.Outings.Select(o => o.ToModel()),
TotalVotes = venue.TotalVotes,
TotalRating = venue.TotalRating
};
}
public static Venue ToDomain(this VenueModel venue)
{
if (venue == null)
return null;
var id = Guid.Parse(venue.Id);
var outings = venue.Outings.Select(o => o.ToDomain());
return new Venue(id, venue.Name, venue.Location, venue.CreatedByUser, venue.CreatedOn, outings)
{
Url = venue.Url,
Description = venue.Description,
Address = venue.Address,
TotalVotes = venue.TotalVotes,
TotalRating = venue.TotalRating
};
}
}
}
|
gpl-3.0
|
uds-se/backstage
|
src/main/java/st/cs/uni/saarland/de/searchDynDecStrings/StmtSwitchForStrings.java
|
23350
|
package st.cs.uni.saarland.de.searchDynDecStrings;
import soot.Scene;
import soot.SootField;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.*;
import st.cs.uni.saarland.de.entities.FieldInfo;
import st.cs.uni.saarland.de.helpClasses.Helper;
import st.cs.uni.saarland.de.helpClasses.Info;
import st.cs.uni.saarland.de.helpClasses.InterProcInfo;
import st.cs.uni.saarland.de.helpClasses.MyStmtSwitch;
import st.cs.uni.saarland.de.helpMethods.InterprocAnalysis2;
import st.cs.uni.saarland.de.helpMethods.StmtSwitchForArrayAdapter;
import st.cs.uni.saarland.de.testApps.Content;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class StmtSwitchForStrings extends MyStmtSwitch {
// private DynDecStringInfo searchedString;
public StmtSwitchForStrings(SootMethod currentSootMethod) {
super(currentSootMethod);
}
// case 2: arrays:
// listView = (ListView) findViewById(R.id.list);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1, android.R.id.text1, values);
// listView.setAdapter(adapter);
// searchedReg == searched element
public StmtSwitchForStrings(DynDecStringInfo newInfo, SootMethod currentSootMethod) {
super(newInfo, currentSootMethod);
}
public void caseIdentityStmt(IdentityStmt stmt){
if(Thread.currentThread().isInterrupted()){
return;
}
String leftReg = helpMethods.getLeftRegOfIdentityStmt(stmt);
if (stmt.getRightOp() instanceof ParameterRef){
Set<Info> toAddInfos = new LinkedHashSet<>();
for (Info i: getResultInfos()){
if(Thread.currentThread().isInterrupted()){
return;
}
DynDecStringInfo searchedString = (DynDecStringInfo) i;
if (leftReg.equals(searchedString.getSearchedEReg()) || leftReg.equals(searchedString.getUiEIDReg())){
searchedString.setSearchedEReg("");
searchedString.setUiEIDReg("");
int paramIndex = ((ParameterRef)stmt.getRightOp()).getIndex();
List<Info> resList = interprocMethods2.findInReachableMethods2(paramIndex, getCurrentSootMethod(), new ArrayList<SootMethod>());
if (resList.size() > 0){
searchedString.setUiEID(((InterProcInfo)resList.get(0)).getValueOfSearchedReg());
if (resList.size() > 1){
for (int j = 1; j < resList.size() ; j++){
InterProcInfo workingInfo = (InterProcInfo) resList.get(j);
DynDecStringInfo newInfo = (DynDecStringInfo) searchedString.clone();
newInfo.setUiEID(workingInfo.getValueOfSearchedReg());
toAddInfos.add(newInfo);
}
}
}
}
if (searchedString.getTextReg().contains(leftReg)){
searchedString.removeTextReg(leftReg);
int paramIndex = ((ParameterRef)stmt.getRightOp()).getIndex();
List<Info> resList = interprocMethods2.findInReachableMethods2(paramIndex, getCurrentSootMethod(), new ArrayList<SootMethod>());
if (resList.size() > 0){
searchedString.addText(((InterProcInfo)resList.get(0)).getValueOfSearchedReg());
if (resList.size() > 1){
for (int j = 1; j < resList.size() ; j++){
InterProcInfo workingInfo = (InterProcInfo) resList.get(j);
searchedString.addText(workingInfo.getValueOfSearchedReg());
}
}
}
}
}
addAllToResultInfo(toAddInfos);
}
}
public void caseAssignStmt(AssignStmt stmt){
if(Thread.currentThread().isInterrupted()){
return;
}
// System.out.println(stmt);
// List<Info> resultInfos = getResultInfos();
Set<Info> toAddInfos = new LinkedHashSet<>();
Set<Info> toRemoveInfos = new LinkedHashSet<>();
for (Info i: getResultInfos()){
if(Thread.currentThread().isInterrupted()){
return;
}
DynDecStringInfo searchedString = (DynDecStringInfo) i;
// call the arraySwitch on the assignStmt, if it is used
if (searchedString.getArraySwitch() != null)
searchedString = (DynDecStringInfo) searchedString.getArraySwitch().caseAssignStmt(stmt, searchedString);
searchedString.setProcessedStmtInStringBuilder(false);
searchedString = (DynDecStringInfo) searchedString.getStringBuilderSwitch().caseAssignStmt(stmt, searchedString);
// if the stringBuilder processed this statement, nobody else has to do it
if (searchedString.isProcessedStmtInStringBuilder())
continue;
String rightReg = helpMethods.getRightRegOfAssignStmt(stmt);
String leftReg = stmt.getLeftOpBox().getValue().toString();
// check if inside the assign stmt is an invoke, e.g.:
// $r2 = virtualinvoke $r0.<com.example.Testapp.MainActivity: android.view.View findViewById(int)>(2131034120);
if (stmt.containsInvokeExpr()){
InvokeExpr invokeExpr = stmt.getInvokeExpr();
String methodSignature = helpMethods.getSignatureOfInvokeExpr(invokeExpr);
String methodName = helpMethods.getMethodNameOfInvokeStmt(invokeExpr);
if ("findViewById".equals(methodName)){
// get left side of assign stmt
if (leftReg.equals(searchedString.getSearchedEReg())){
if (!(invokeExpr.getArg(0) instanceof NullConstant)){
// get the id of the layout
String param = helpMethods.getParameterOfInvokeStmt(invokeExpr,0);
searchedString.setSearchedEReg("");
if (invokeExpr.getArg(0) instanceof IntConstant){
searchedString.setUiEID(param);
}else{
searchedString.setUiEIDReg(param);
}
}else{
searchedString.setUiEID("-No integer given: NullType");
}
}
}else
if (methodSignature.equals("<android.content.res.Resources: CharSequence getTextFromElement(int)>") ||
methodSignature.equals("<android.content.res.Resources: java.lang.String getTextFromElement(int,CharSequence)>") ||
methodSignature.equals("<android.content.res.Resources: java.lang.String getString(int)>") ||
invokeExpr.getMethod().getSubSignature().startsWith("java.lang.String getString(int") ||
methodSignature.equals("<android.content.res.Resources: java.lang.String[] getStringArray(int)>")){
if (searchedString.getTextReg().contains(leftReg)){
searchedString.removeTextReg(leftReg);
String text = helpMethods.getParameterOfInvokeStmt(invokeExpr, 0);
searchedString.addText(text);
}
else if (searchedString.getSearchedPlaceHolders() != null && searchedString.getSearchedPlaceHolders().contains(leftReg)){
searchedString.removeSearchedPlaceHolders(leftReg);
String tmp = helpMethods.getParameterOfInvokeStmt(invokeExpr, 0);
if (checkMethods.checkIfValueIsID(tmp)){
tmp = Content.getInstance().getStringValueFromStringId(tmp);
}else if (checkMethods.checkIfValueIsString(tmp)){
tmp = tmp.replace("\"", "");
}
searchedString.replacePlaceHolder(leftReg, tmp);
}
}
else{
if (leftReg.equals(searchedString.getUiEIDReg())){
searchedString.setUiEIDReg(""); //textId
List<InterProcInfo> resList = interprocMethods2.findReturnValueInMethod2(stmt);
if (resList.size() > 0){
searchedString.setUiEID(((InterProcInfo)resList.get(0)).getValueOfSearchedReg());
if (resList.size() > 1){
for (int j = 1; j < resList.size() ; j++){
InterProcInfo workingInfo = (InterProcInfo) resList.get(j);
DynDecStringInfo newInfo = (DynDecStringInfo) searchedString.clone();
newInfo.setUiEID(workingInfo.getValueOfSearchedReg());
toAddInfos.add(newInfo);
}
}
}
}
if(leftReg.equals(searchedString.getSearchedEReg())){
searchedString.setSearchedEReg(""); // View
//search for the View, not ID!!!
//search for the findViewById in the method
//we also need to find the value
List<Integer> ids = InterprocAnalysis2.getInstance().findElementIdFromForTheView(stmt, getCurrentSootMethod());
if(!ids.isEmpty()){
searchedString.setUiEID(ids.get(0).toString());
if (ids.size() > 1){
for (int j = 1; j < ids.size() ; j++){
DynDecStringInfo newInfo = (DynDecStringInfo) searchedString.clone();
newInfo.setUiEID(ids.get(j).toString());
newInfo.setSearchedEReg("");
toAddInfos.add(newInfo);
}
}
continue;
}
}
if (searchedString.getTextReg().contains(leftReg)) {
searchedString.removeTextReg(leftReg);
if (invokeExpr.getMethod().getSignature().startsWith("<android.text.Html: android.text.Spanned fromHtml(java.lang.String")) {
searchedString.addTextReg(invokeExpr.getArg(0).toString());
} else {
List<InterProcInfo> resList = interprocMethods2.findReturnValueInMethod2(stmt);
if (resList.size() > 0) {
searchedString.addText(((InterProcInfo) resList.get(0)).getValueOfSearchedReg());
if (resList.size() > 1) {
for (int j = 1; j < resList.size(); j++) {
InterProcInfo workingInfo = (InterProcInfo) resList.get(j);
searchedString.addText(workingInfo.getValueOfSearchedReg());
}
}
}
}
}
//}
}
}
// check if an existing register that is searched for, changes the register
else{
if (leftReg.equals(searchedString.getSearchedEReg())){
if (stmt.getRightOp() instanceof FieldRef){
SootField f = ((FieldRef)stmt.getRightOp()).getField();
if(previousFields.contains(f)){
if(!previousFieldsForCurrentStmtSwitch.contains(f)){
continue;
}
}else{
previousFields.add(f);
previousFieldsForCurrentStmtSwitch.add(f);
}
Set<FieldInfo> fInfos = interprocMethods2.findInitializationsOfTheField2(f, stmt, getCurrentSootMethod());
if(fInfos.size() > 0){
toRemoveInfos.add(searchedString);
for (FieldInfo fInfo : fInfos){
if(Thread.currentThread().isInterrupted()){
return;
}
if(fInfo.value != null){
DynDecStringInfo newInfo = (DynDecStringInfo) searchedString.clone();
newInfo.setUiEID(fInfo.value);
newInfo.setSearchedEReg("");
toAddInfos.add(newInfo);
continue;
}else{
if(fInfo.methodToStart != null && fInfo.methodToStart.method().hasActiveBody()) {
Unit workingUnit = fInfo.unitToStart;
DynDecStringInfo newInfo = new DynDecStringInfo("", getCurrentSootMethod());
newInfo.setSearchedEReg(fInfo.register.getName());
StmtSwitchForStrings newStmtSwitch = new StmtSwitchForStrings(newInfo, getCurrentSootMethod());
previousFields.forEach(x -> newStmtSwitch.addPreviousField(x));
iteratorHelper.runOverToFindSpecValuesBackwards(fInfo.methodToStart.method().getActiveBody(), workingUnit, newStmtSwitch);
Set<Info> initValues = newStmtSwitch.getResultInfos();
if(initValues.size() > 0) {
List<Info> listInfo = initValues.stream().collect(Collectors.toList());
if(listInfo.indexOf(newInfo) == -1){
continue;
}
Info initInfo = listInfo.get(listInfo.indexOf(newInfo));
DynDecStringInfo newInfo2 = (DynDecStringInfo) searchedString.clone();
newInfo2.setUiEID(((DynDecStringInfo) initInfo).getUiEID());
newInfo2.setSearchedEReg("");
toAddInfos.add(newInfo2);
}
}
}
}
}else{
searchedString.setSearchedEReg("");
Helper.saveToStatisticalFile("Error StringSwitch: Doesn't find searchedReg in initializationOfField: " + stmt);
}
}else{
searchedString.setSearchedEReg("");
searchedString.setSearchedEReg(rightReg);
}
}
if (leftReg.equals(searchedString.getUiEIDReg())){
if (stmt.getRightOp() instanceof FieldRef){
SootField f = ((FieldRef)stmt.getRightOp()).getField();
if(previousFields.contains(f)){
if(!previousFieldsForCurrentStmtSwitch.contains(f)){
continue;
}
}else{
previousFields.add(f);
previousFieldsForCurrentStmtSwitch.add(f);
}
Set<FieldInfo> fInfos = interprocMethods2.findInitializationsOfTheField2(f, stmt, getCurrentSootMethod());
if(fInfos.size() > 0){
toRemoveInfos.add(searchedString);
for (FieldInfo fInfo : fInfos){
if(Thread.currentThread().isInterrupted()){
return;
}
if(fInfo.value != null){
DynDecStringInfo newInfo = (DynDecStringInfo) searchedString.clone();
newInfo.setUiEID(fInfo.value);
newInfo.setUiEIDReg("");
toAddInfos.add(newInfo);
continue;
}else{
if(fInfo.methodToStart != null && fInfo.methodToStart.method().hasActiveBody()){
Unit workingUnit = fInfo.unitToStart;
DynDecStringInfo newInfo = new DynDecStringInfo("", getCurrentSootMethod());
newInfo.setUiEIDReg(fInfo.register.getName());
StmtSwitchForStrings newStmtSwitch = new StmtSwitchForStrings(newInfo, getCurrentSootMethod());
previousFields.forEach(x->newStmtSwitch.addPreviousField(x));
iteratorHelper.runOverToFindSpecValuesBackwards(fInfo.methodToStart.method().getActiveBody(), workingUnit, newStmtSwitch);
Set<Info> initValues = newStmtSwitch.getResultInfos();
if(initValues.size() > 0) {
List<Info> listInfo = initValues.stream().collect(Collectors.toList());
if(listInfo.indexOf(newInfo) == -1){
continue;
}
Info initInfo = listInfo.get(listInfo.indexOf(newInfo));
DynDecStringInfo newInfo2 = (DynDecStringInfo) searchedString.clone();
newInfo2.setUiEID(((DynDecStringInfo)initInfo).getUiEID());
newInfo2.setUiEIDReg("");
toAddInfos.add(newInfo2);
}
}
}
}
}else{
searchedString.setUiEIDReg("");
Helper.saveToStatisticalFile("Error StringSwitch: Doesn't find uiEIDReg in initializationOfField: " + stmt);
}
}else{
searchedString.setUiEIDReg("");
searchedString.setUiEIDReg(rightReg);
}
}
if (searchedString.getTextReg().contains(leftReg)){
searchedString.removeTextReg(leftReg);
if (stmt.getRightOp() instanceof FieldRef){
SootField f = ((FieldRef)stmt.getRightOp()).getField();
if(previousFields.contains(f)){
if(!previousFieldsForCurrentStmtSwitch.contains(f)){
continue;
}
}else{
previousFields.add(f);
previousFieldsForCurrentStmtSwitch.add(f);
}
Set<FieldInfo> fInfos = interprocMethods2.findInitializationsOfTheField2(f, stmt, getCurrentSootMethod());
if(fInfos.size() > 0){
for (FieldInfo fInfo : fInfos){
if(Thread.currentThread().isInterrupted()){
return;
}
if(fInfo.value != null){
searchedString.addText(fInfo.value);
continue;
}else{
if(fInfo.methodToStart != null && fInfo.methodToStart.method().hasActiveBody()){
Unit workingUnit = fInfo.unitToStart;
DynDecStringInfo newInfo = new DynDecStringInfo("", getCurrentSootMethod());
newInfo.addTextReg(fInfo.register.getName());
StmtSwitchForStrings newStmtSwitch = new StmtSwitchForStrings(newInfo, getCurrentSootMethod());
previousFields.forEach(x->newStmtSwitch.addPreviousField(x));
iteratorHelper.runOverToFindSpecValuesBackwards(fInfo.methodToStart.method().getActiveBody(), workingUnit, newStmtSwitch);
Set<Info> initValues = newStmtSwitch.getResultInfos();
if(initValues.size() > 0) {
List<Info> listInfo = initValues.stream().collect(Collectors.toList());
if(listInfo.indexOf(newInfo) == -1){
continue;
}
Info initInfo = listInfo.get(listInfo.indexOf(newInfo));
// DynDecStringInfo newInfo2 = (DynDecStringInfo) searchedString.clone();
searchedString.addText(((DynDecStringInfo)initInfo).getText());
// toAddInfos.add(newInfo2);
}
}
}
}
}else{
Helper.saveToStatisticalFile("Error StringSwitch: Doesn't find textReg in initializationOfField: " + stmt);
}
}else{
if (checkMethods.checkIfValueIsVariable(rightReg)){
searchedString.addTextReg(rightReg);
}else{
searchedString.addText(rightReg);
}
}
}
if (searchedString.getSearchedPlaceHolders() != null && searchedString.getSearchedPlaceHolders().contains(leftReg)){
searchedString.removeSearchedPlaceHolders(leftReg);
if (stmt.getRightOp() instanceof FieldRef){
SootField f = ((FieldRef)stmt.getRightOp()).getField();
if(previousFields.contains(f)){
if(!previousFieldsForCurrentStmtSwitch.contains(f)){
continue;
}
}else{
previousFields.add(f);
previousFieldsForCurrentStmtSwitch.add(f);
}
Set<FieldInfo> fInfos = interprocMethods2.findInitializationsOfTheField2(f, stmt, getCurrentSootMethod());
if(fInfos.size() > 0){
for (FieldInfo fInfo : fInfos){
if(Thread.currentThread().isInterrupted()){
return;
}
if(fInfo.value != null){
searchedString.replacePlaceHolder(leftReg, fInfo.value);
continue;
}else{
if(fInfo.methodToStart != null && fInfo.methodToStart.method().hasActiveBody()){
Unit workingUnit = fInfo.unitToStart;
DynDecStringInfo newInfo = new DynDecStringInfo("", getCurrentSootMethod());
newInfo.addTextReg(fInfo.register.getName());
StmtSwitchForStrings newStmtSwitch = new StmtSwitchForStrings(newInfo, getCurrentSootMethod());
previousFields.forEach(x->newStmtSwitch.addPreviousField(x));
iteratorHelper.runOverToFindSpecValuesBackwards(fInfo.methodToStart.method().getActiveBody(), workingUnit, newStmtSwitch);
Set<Info> initValues = newStmtSwitch.getResultInfos();
if(initValues.size() > 0) {
List<Info> listInfo = initValues.stream().collect(Collectors.toList());
if(listInfo.indexOf(newInfo) == -1){
continue;
}
Info initInfo = listInfo.get(listInfo.indexOf(newInfo));
searchedString.replacePlaceHolder(leftReg,((DynDecStringInfo)initInfo).getText());
}
}
}
}
}else{
Helper.saveToStatisticalFile("Error StringSwitch: Doesn't find textReg in initializationOfField: " + stmt);
}
}else{
if (checkMethods.checkIfValueIsVariable(rightReg)){
searchedString.addSearchedPlaceHolders(rightReg);
searchedString.replacePlaceHolder(leftReg, rightReg);
}else{
searchedString.replacePlaceHolder(leftReg, rightReg.replace("\"", ""));
}
}
if (searchedString.getSearchedPlaceHolders().size() == 0){
searchedString.addText(searchedString.joinNotJoinedText());
}
}
}
}
if (toRemoveInfos.size() > 0){
removeAllFromResultInfos(toRemoveInfos);
}
addAllToResultInfo(toAddInfos);
}
public void caseInvokeStmt(InvokeStmt stmt) {
if(Thread.currentThread().isInterrupted()){
return;
}
// System.out.println(stmt);
InvokeExpr invokeExpr = stmt.getInvokeExpr();
String method_name = helpMethods.getMethodNameOfInvokeStmt(invokeExpr);
// call this method only if it is the first call and
// and call this method once
// List<Info> resultInfos = getResultInfos();
for (Info i: getResultInfos()){
if(Thread.currentThread().isInterrupted()){
return;
}
DynDecStringInfo searchedString = (DynDecStringInfo) i;
if (searchedString.getArraySwitch() != null)
searchedString = (DynDecStringInfo) searchedString.getArraySwitch().caseInvokeStmt(stmt, searchedString);
searchedString.setProcessedStmtInStringBuilder(false);
searchedString = (DynDecStringInfo) searchedString.getStringBuilderSwitch().caseInvokeStmt(stmt, searchedString);
// if the stringBuilder processed this statement, nobody else has to do it
if (searchedString.isProcessedStmtInStringBuilder())
continue;
}
// case set setText: e.g.:
// virtualinvoke $r10.<android.widget.Button: void setText(int)>(2130968577);
// or
// virtualinvoke $r10.<android.widget.Button: void setText(java.lang.CharSequence)>("nextIntentInternet");
if (method_name.equals("setText") && invokeExpr.getArgCount() > 0){
String typeOfParam = helpMethods.getParameterTypeOfInvokeStmt(invokeExpr,0);
String param = helpMethods.getParameterOfInvokeStmt(invokeExpr,0);
// if typeOfParam is int, then the text is set via the string id: e.g.:
// virtualinvoke $r10.<android.widget.Button: void setText(int)>(2130968577);
if (typeOfParam.equals("int")){
if (invokeExpr.getArg(0) instanceof IntConstant){
DynDecStringInfo searchedString = new DynDecStringInfo(helpMethods.getCallerOfInvokeStmt(invokeExpr), getCurrentSootMethod());
String text =param;
searchedString.addText(text);
addToResultInfo(searchedString);
}else{
DynDecStringInfo searchedString = new DynDecStringInfo(helpMethods.getCallerOfInvokeStmt(invokeExpr), getCurrentSootMethod());
searchedString.addTextReg(param);
addToResultInfo(searchedString);
}
// otherwise the text is set directly as String e.g.:
// virtualinvoke $r10.<android.widget.Button: void setText(java.lang.CharSequence)>("nextIntentInternet");
}else if (typeOfParam.equals("java.lang.CharSequence") || typeOfParam.equals("java.lang.String") || Scene.v().getSootClass(typeOfParam).implementsInterface("java.lang.CharSequence")){
DynDecStringInfo searchedString = new DynDecStringInfo(helpMethods.getCallerOfInvokeStmt(invokeExpr), getCurrentSootMethod());
// TODO add other check if its variable
// TODO include arrays
if (checkMethods.checkIfValueIsVariable(param)){
searchedString.addTextReg(param);
}else{
searchedString.addText(param.replace("\"", ""));
}
addToResultInfo(searchedString);
}
}else if (method_name.equals("setAdapter") && (invokeExpr.getArgCount() > 0)){
// virtualinvoke $r5.<android.widget.ListView: void setAdapter(android.widget.ListAdapter)>($r2);
String typeOfParam = helpMethods.getParameterTypeOfInvokeStmt(invokeExpr,0);
if (typeOfParam.equals("android.widget.ArrayAdapter") || typeOfParam.equals("android.widget.ListAdapter")){
DynDecStringInfo searchedString = new DynDecStringInfo(helpMethods.getCallerOfInvokeStmt(invokeExpr), getCurrentSootMethod());
StmtSwitchForArrayAdapter arraySwitch = new StmtSwitchForArrayAdapter(helpMethods.getParameterOfInvokeStmt(invokeExpr, 0), getCurrentSootMethod());
searchedString.setArraySwitch(arraySwitch);
addToResultInfo(searchedString);
}
}
// }
}
// private void checkIfStringIsFinished(){
// if (searchedString.ready())
// shouldBreak = true;
// }
}
|
gpl-3.0
|
RealizedMC/Duels
|
duels-api/src/main/java/me/realized/duels/api/event/request/RequestAcceptEvent.java
|
1617
|
package me.realized.duels.api.event.request;
import javax.annotation.Nonnull;
import me.realized.duels.api.request.Request;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
/**
* Called when a {@link Player} accepts a {@link Request} from a {@link Player}.
*
* @since 3.2.1
*/
public class RequestAcceptEvent extends RequestEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancelled;
/**
* @param source {@link Player} who is accepting this {@link Request}.
* @param target {@link Player} who sent this {@link Request}.
* @param request {@link Request} that is being handled.
*/
public RequestAcceptEvent(@Nonnull final Player source, @Nonnull final Player target, @Nonnull final Request request) {
super(source, target, request);
}
/**
* Whether or not this event has been cancelled.
*
* @return True if this event has been cancelled. False otherwise.
*/
@Override
public boolean isCancelled() {
return cancelled;
}
/**
* Whether or not to cancel this event.
* When cancelled, the request will not be removed and remain as unhandled.
*
* @param cancelled True to cancel this event.
*/
@Override
public void setCancelled(final boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
|
gpl-3.0
|
gcsadovy/generalPY
|
manageParcels.py
|
217
|
# manageParcels.py
import parcelClass
myParcel = parcelClass.parcel(145000, "residential")
print "Value:", myParcel.value
print "Zoning:", myParcel.zoning
mytax = myParcel.calculateTax()
print "Tax:", mytax
|
gpl-3.0
|
bramfoo/algorithms
|
src/main/java/edu/princeton/cs/algs4/fundamentals/LinkedQueue.java
|
7443
|
package edu.princeton.cs.algs4.fundamentals;
import edu.princeton.cs.algs4.io.*;
/*************************************************************************
* Compilation: javac LinkedQueue.java
* Execution: java LinkedQueue < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: http://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* A generic queue, implemented using a singly-linked list.
*
* % java Queue < tobe.txt
* to be or not to be (2 left on queue)
*
*************************************************************************/
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* The <tt>LinkedQueue</tt> class represents a first-in-first-out (FIFO)
* queue of generic items.
* It supports the usual <em>enqueue</em> and <em>dequeue</em>
* operations, along with methods for peeking at the first item,
* testing if the queue is empty, and iterating through
* the items in FIFO order.
* <p>
* This implementation uses a singly-linked list with a non-static nested class
* for linked-list nodes. See {@link Queue} for a version that uses a static nested class.
* The <em>enqueue</em>, <em>dequeue</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em>
* operations all take constant time in the worst case.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class LinkedQueue<Item> implements Iterable<Item> {
private int N; // number of elements on queue
private Node first; // beginning of queue
private Node last; // end of queue
// helper linked list class
private class Node {
private Item item;
private Node next;
}
/**
* Initializes an empty queue.
*/
public LinkedQueue() {
first = null;
last = null;
N = 0;
assert check();
}
/**
* Is this queue empty?
* @return true if this queue is empty; false otherwise
*/
public boolean isEmpty() {
return first == null;
}
/**
* Returns the number of items in this queue.
* @return the number of items in this queue
*/
public int size() {
return N;
}
/**
* Returns the item least recently added to this queue.
* @return the item least recently added to this queue
* @throws java.util.NoSuchElementException if this queue is empty
*/
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
return first.item;
}
/**
* Adds the item to this queue.
* @param item the item to add
*/
public void enqueue(Item item) {
Node oldlast = last;
last = new Node();
last.item = item;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
N++;
assert check();
}
/**
* Removes and returns the item on this queue that was least recently added.
* @return the item on this queue that was least recently added
* @throws java.util.NoSuchElementException if this queue is empty
*/
public Item dequeue() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
Item item = first.item;
first = first.next;
N--;
if (isEmpty()) last = null; // to avoid loitering
assert check();
return item;
}
/**
* Returns a string representation of this queue.
* @return the sequence of items in FIFO order, separated by spaces
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this)
s.append(item + " ");
return s.toString();
}
// check internal invariants
private boolean check() {
if (N == 0) {
if (first != null) return false;
if (last != null) return false;
}
else if (N == 1) {
if (first == null || last == null) return false;
if (first != last) return false;
if (first.next != null) return false;
}
else {
if (first == last) return false;
if (first.next == null) return false;
if (last.next != null) return false;
// check internal consistency of instance variable N
int numberOfNodes = 0;
for (Node x = first; x != null; x = x.next) {
numberOfNodes++;
}
if (numberOfNodes != N) return false;
// check internal consistency of instance variable last
Node lastNode = first;
while (lastNode.next != null) {
lastNode = lastNode.next;
}
if (last != lastNode) return false;
}
return true;
}
/**
* Returns an iterator that iterates over the items in this queue in FIFO order.
* @return an iterator that iterates over the items in this queue in FIFO order
*/
public Iterator<Item> iterator() {
return new ListIterator();
}
// an iterator, doesn't implement remove() since it's optional
private class ListIterator implements Iterator<Item> {
private Node current = first;
public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
/**
* Unit tests the <tt>LinkedQueue</tt> data type.
*/
public static void main(String[] args) {
LinkedQueue<String> q = new LinkedQueue<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) q.enqueue(item);
else if (!q.isEmpty()) StdOut.print(q.dequeue() + " ");
}
StdOut.println("(" + q.size() + " left on queue)");
}
}
/*************************************************************************
* Copyright 2002-2012, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4-package.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4-package.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4-package.jar 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with algs4-package.jar. If not, see http://www.gnu.org/licenses.
*************************************************************************/
|
gpl-3.0
|
prife/VirtualApp
|
VirtualApp/lib/src/main/java/com/lody/virtual/server/pm/VAppManagerService.java
|
10353
|
package com.lody.virtual.server.pm;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageParser;
import android.net.Uri;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Pair;
import com.lody.virtual.client.core.InstallStrategy;
import com.lody.virtual.client.core.VirtualCore;
import com.lody.virtual.client.env.Constants;
import com.lody.virtual.client.env.VirtualRuntime;
import com.lody.virtual.helper.compat.NativeLibraryHelperCompat;
import com.lody.virtual.helper.compat.PackageParserCompat;
import com.lody.virtual.helper.proto.AppSetting;
import com.lody.virtual.helper.proto.InstallResult;
import com.lody.virtual.helper.utils.FileUtils;
import com.lody.virtual.helper.utils.VLog;
import com.lody.virtual.os.VEnvironment;
import com.lody.virtual.os.VUserHandle;
import com.lody.virtual.server.accounts.VAccountManagerService;
import com.lody.virtual.server.am.StaticBroadcastSystem;
import com.lody.virtual.server.am.UidSystem;
import com.lody.virtual.server.am.VActivityManagerService;
import com.lody.virtual.service.IAppManager;
import com.lody.virtual.service.interfaces.IAppObserver;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author Lody
*/
public class VAppManagerService extends IAppManager.Stub {
private static final String TAG = VAppManagerService.class.getSimpleName();
private boolean isBooting;
private final UidSystem mUidSystem = new UidSystem();
private final StaticBroadcastSystem mBroadcastSystem =
new StaticBroadcastSystem(
VirtualCore.get().getContext(),
VActivityManagerService.get(),
this
);
private static final AtomicReference<VAppManagerService> gService = new AtomicReference<>();
private RemoteCallbackList<IAppObserver> mRemoteCallbackList = new RemoteCallbackList<IAppObserver>();
public static VAppManagerService get() {
return gService.get();
}
public boolean isBooting() {
return isBooting;
}
public static void systemReady() {
VAppManagerService instance = new VAppManagerService();
instance.mUidSystem.initUidList();
instance.preloadAllApps();
gService.set(instance);
}
public void preloadAllApps() {
isBooting = true;
for (File appDir : VEnvironment.getDataAppDirectory().listFiles()) {
String pkgName = appDir.getName();
File storeFile = new File(appDir, "base.apk");
int flags = 0;
if (!storeFile.exists()) {
ApplicationInfo appInfo = null;
try {
appInfo = VirtualCore.get().getUnHookPackageManager()
.getApplicationInfo(pkgName, 0);
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
if (appInfo == null || appInfo.publicSourceDir == null) {
FileUtils.deleteDir(appDir);
continue;
}
storeFile = new File(appInfo.publicSourceDir);
flags |= InstallStrategy.DEPEND_SYSTEM_IF_EXIST;
}
InstallResult res = install(storeFile.getPath(), flags, true);
if (!res.isSuccess) {
VLog.e(TAG, "Unable to install app %s: %s.", pkgName, res.error);
FileUtils.deleteDir(appDir);
}
}
isBooting = false;
}
@Override
public InstallResult installApp(String apkPath, int flags) {
return install(apkPath, flags, false);
}
private synchronized InstallResult install(String apkPath, int flags, boolean onlyScan) {
if (apkPath == null) {
return InstallResult.makeFailure("Not given the apk path.");
}
File apk = new File(apkPath);
if (!apk.exists() || !apk.isFile()) {
return InstallResult.makeFailure("APK File is not exist.");
}
PackageParser.Package pkg = null;
PackageParser parser = null;
try {
Pair<PackageParser, PackageParser.Package> parseResult = PackageParserCompat.parsePackage(apk, 0);
if (parseResult != null) {
parser = parseResult.first;
pkg = parseResult.second;
}
} catch (Throwable e) {
e.printStackTrace();
}
if (parser == null || pkg == null || pkg.packageName == null) {
return InstallResult.makeFailure("Unable to parse the package.");
}
InstallResult res = new InstallResult();
res.packageName = pkg.packageName;
// PackageCache holds all packages, try to check if need update.
PackageParser.Package existOne = PackageCache.get(pkg.packageName);
if (existOne != null) {
if ((flags & InstallStrategy.IGNORE_NEW_VERSION) != 0) {
res.isUpdate = true;
return res;
}
if (!canUpdate(existOne, pkg, flags)) {
return InstallResult.makeFailure("Unable to update the Apk.");
}
res.isUpdate = true;
}
File appDir = VEnvironment.getDataAppPackageDirectory(pkg.packageName);
File libDir = new File(appDir, "lib");
if (!libDir.exists() && !libDir.mkdirs()) {
return InstallResult.makeFailure("Unable to create lib dir.");
}
boolean dependSystem = (flags & InstallStrategy.DEPEND_SYSTEM_IF_EXIST) != 0
&& VirtualCore.get().isOutsideInstalled(pkg.packageName);
if (!onlyScan) {
if (res.isUpdate) {
FileUtils.deleteDir(libDir);
}
NativeLibraryHelperCompat.copyNativeBinaries(new File(apkPath), libDir);
if (!dependSystem) {
// /data/app/com.xxx.xxx-1/base.apk
File storeFile = new File(appDir, "base.apk");
File parentFolder = storeFile.getParentFile();
if (!parentFolder.exists() && !parentFolder.mkdirs()) {
VLog.w(TAG, "Warning: unable to create folder : " + storeFile.getPath());
} else if (storeFile.exists() && !storeFile.delete()) {
VLog.w(TAG, "Warning: unable to delete file : " + storeFile.getPath());
}
FileUtils.copyFile(apk, storeFile);
apk = storeFile;
}
}
if (existOne != null) {
PackageCache.remove(pkg.packageName);
}
AppSetting appSetting = new AppSetting();
appSetting.parser = parser;
appSetting.dependSystem = dependSystem;
appSetting.apkPath = apk.getPath();
appSetting.libPath = libDir.getPath();
File odexFolder = new File(appDir, VirtualRuntime.isArt() ? "oat" : "odex");
if (!odexFolder.exists() && !odexFolder.mkdirs()) {
VLog.w(TAG, "Warning: unable to create folder : " + odexFolder.getPath());
}
appSetting.odexDir = odexFolder.getPath();
appSetting.packageName = pkg.packageName;
appSetting.appId = VUserHandle.getAppId(mUidSystem.getOrCreateUid(pkg));
PackageCache.put(pkg, appSetting);
mBroadcastSystem.startApp(pkg);
if (!onlyScan) {
notifyAppInstalled(appSetting);
}
res.isSuccess = true;
return res;
}
private boolean canUpdate(PackageParser.Package existOne, PackageParser.Package newOne, int flags) {
if ((flags & InstallStrategy.COMPARE_VERSION) != 0) {
if (existOne.mVersionCode < newOne.mVersionCode) {
return true;
}
}
if ((flags & InstallStrategy.TERMINATE_IF_EXIST) != 0) {
return false;
}
if ((flags & InstallStrategy.UPDATE_IF_EXIST) != 0) {
return true;
}
return false;
}
public boolean uninstallApp(String pkg) {
synchronized (PackageCache.sPackageCaches) {
AppSetting setting = findAppInfo(pkg);
if (setting != null) {
try {
mBroadcastSystem.stopApp(pkg);
VActivityManagerService.get().killAppByPkg(pkg, VUserHandle.USER_ALL);
FileUtils.deleteDir(VEnvironment.getDataAppPackageDirectory(pkg));
for (int userId : VUserManagerService.get().getUserIds()) {
FileUtils.deleteDir(VEnvironment.getDataUserPackageDirectory(userId, pkg));
}
PackageCache.remove(pkg);
} catch (Exception e) {
e.printStackTrace();
} finally {
notifyAppUninstalled(setting);
}
return true;
}
}
return false;
}
public List<AppSetting> getAllApps() {
List<AppSetting> settings = new ArrayList<>(getAppCount());
for (PackageParser.Package p : PackageCache.sPackageCaches.values()) {
settings.add((AppSetting) p.mExtras);
}
return settings;
}
public int getAppCount() {
return PackageCache.sPackageCaches.size();
}
public boolean isAppInstalled(String pkg) {
return pkg != null && PackageCache.sPackageCaches.get(pkg) != null;
}
private void notifyAppInstalled(AppSetting setting) {
int N = mRemoteCallbackList.beginBroadcast();
while (N-- > 0) {
try {
mRemoteCallbackList.getBroadcastItem(N).onNewApp(setting.packageName);
} catch (RemoteException e) {
// Ignore
}
}
mRemoteCallbackList.finishBroadcast();
Intent virtualIntent = new Intent(Constants.ACTION_PACKAGE_ADDED);
Uri uri = Uri.fromParts("package", setting.packageName, null);
virtualIntent.setData(uri);
for (int userId : VUserManagerService.get().getUserIds()) {
Intent intent = new Intent(virtualIntent);
intent.putExtra(Intent.EXTRA_UID, VUserHandle.getUid(userId, setting.appId));
VirtualCore.get().getContext().sendBroadcast(virtualIntent);
}
VAccountManagerService.get().refreshAuthenticatorCache(null);
}
private void notifyAppUninstalled(AppSetting setting) {
int N = mRemoteCallbackList.beginBroadcast();
while (N-- > 0) {
try {
mRemoteCallbackList.getBroadcastItem(N).onRemoveApp(setting.packageName);
} catch (RemoteException e) {
// Ignore
}
}
mRemoteCallbackList.finishBroadcast();
Intent virtualIntent = new Intent(Constants.ACTION_PACKAGE_REMOVED);
Uri uri = Uri.fromParts("package", setting.packageName, null);
virtualIntent.setData(uri);
for (int userId : VUserManagerService.get().getUserIds()) {
Intent intent = new Intent(virtualIntent);
intent.putExtra(Intent.EXTRA_UID, VUserHandle.getUid(userId, setting.appId));
VirtualCore.get().getContext().sendBroadcast(virtualIntent);
}
VAccountManagerService.get().refreshAuthenticatorCache(null);
}
@Override
public void registerObserver(IAppObserver observer) {
try {
mRemoteCallbackList.register(observer);
} catch (Throwable e) {
// Ignore
}
}
@Override
public void unregisterObserver(IAppObserver observer) {
try {
mRemoteCallbackList.unregister(observer);
} catch (Throwable e) {
// Ignore
}
}
public AppSetting findAppInfo(String pkg) {
synchronized (PackageCache.class) {
if (pkg != null) {
PackageParser.Package p = PackageCache.get(pkg);
if (p != null) {
return (AppSetting) p.mExtras;
}
}
return null;
}
}
public int getAppId(String pkg) {
AppSetting setting = findAppInfo(pkg);
return setting != null ? setting.appId : -1;
}
}
|
gpl-3.0
|
Ekleog/toboggan
|
src/posix.rs
|
16404
|
/*
* Copyright (C) 2016 Leo Gaspard
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use std::{ffi, fs, mem::{self, MaybeUninit}, path, str};
use std::io::Write;
use std::process::{Command, Stdio};
use libc::*;
#[allow(unused_imports)] // Rustc seems to wrongly detect Error as unused. TODO: remove when fixed?
use serde::{de, Deserialize, Deserializer, Error, Serialize, Serializer};
use serde_json;
use syscalls;
use syscalls::Syscall;
const PTRACE_EVENT_EXEC: c_int = 4;
const PTRACE_EVENT_SECCOMP: c_int = 7;
pub fn exec(prog: &str, argv: &[&str]) {
let prog = ffi::CString::new(prog).unwrap();
let mut args: Vec<*const c_char> = Vec::new();
for arg in argv {
args.push(ffi::CString::new(arg.clone()).unwrap().into_raw());
}
args.push(0 as *const c_char);
// TODO: allow to block environment passing?
unsafe {
execvp(prog.as_ptr(), args.as_ptr());
}
panic!("Unable to exec: {}", unsafe { *__errno_location() });
}
extern {
fn sigprocmask(how: c_int, set: *const sigset_t, oldset: *mut sigset_t);
}
fn usr1set() -> sigset_t {
unsafe {
let mut set: MaybeUninit<sigset_t> = MaybeUninit::uninit();
sigemptyset(set.as_mut_ptr());
sigaddset(set.as_mut_ptr(), SIGUSR1);
set.assume_init()
}
}
pub fn blockusr1() -> sigset_t {
let set = usr1set();
unsafe {
let mut oldset: MaybeUninit<sigset_t> = MaybeUninit::uninit();
sigprocmask(SIG_BLOCK, &set, oldset.as_mut_ptr());
oldset.assume_init()
}
}
pub fn setsigmask(m: sigset_t) {
unsafe {
sigprocmask(SIG_SETMASK, &m, 0 as *mut sigset_t);
}
}
fn waitforcont() {
let set = usr1set();
unsafe {
let mut sig: MaybeUninit<c_int> = MaybeUninit::uninit();
blockusr1(); // This should already have been done, but safe function...
sigwait(&set, sig.as_mut_ptr());
}
}
fn sendcont(pid: pid_t) {
unsafe {
kill(pid, SIGUSR1);
}
}
fn killit(pid: pid_t) {
unsafe {
kill(pid, SIGSYS);
kill(pid, SIGKILL); // In case the first one was blocked
}
}
pub fn ptraceme() {
waitforcont();
}
pub fn waitit(pid: pid_t) -> PtraceStop {
unsafe {
let mut status: MaybeUninit<c_int> = MaybeUninit::uninit();
waitpid(pid, status.as_mut_ptr(), 0);
stop_type(status.assume_init())
}
}
fn continueit(pid: pid_t) {
unsafe {
ptrace(PTRACE_CONT, pid, 0, 0);
}
}
#[derive(Debug)]
pub enum Action {
Allow,
Kill,
// TODO: Add an Ignore target
}
struct ActionVisitor;
impl de::Visitor for ActionVisitor {
type Value = Action;
fn visit_str<E: de::Error>(&mut self, v: &str) -> Result<Action, E> {
match v {
"allow" => Ok(Action::Allow),
"kill" => Ok(Action::Kill),
_ => Err(E::invalid_value(&format!("Invalid value for action: {}", v))),
}
}
}
// TODO: replace with auto-derive when it lands on stable
impl Deserialize for Action {
fn deserialize<D: Deserializer>(d: &mut D) -> Result<Action, D::Error> {
d.deserialize(ActionVisitor)
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum PtraceStop {
Exec,
Exit,
Seccomp,
Unknown(c_int),
}
fn stop_type(status: c_int) -> PtraceStop {
if status & 0x7f == 0
|| (((status & 0x7f) + 1) as i8 >> 1) > 0 {
return PtraceStop::Exit
}
if (status >> 8) & 0xff != SIGTRAP {
return PtraceStop::Unknown(status)
}
match status >> 16 {
PTRACE_EVENT_SECCOMP => PtraceStop::Seccomp,
PTRACE_EVENT_EXEC => PtraceStop::Exec,
_ => PtraceStop::Unknown(status),
}
}
pub fn ptracehim<F>(pid: pid_t, cb: F) where F: Fn(SyscallInfo) -> Action {
// Attach
if unsafe { ptrace(PTRACE_ATTACH, pid, 0, 0) } != 0 {
panic!("unable to ptrace child!");
}
// Wait for the process to receive the SIGSTOP
waitit(pid);
// Set ptrace options
// TODO: Make sure forks are ptraced
let options = PTRACE_O_EXITKILL | PTRACE_O_TRACESECCOMP | PTRACE_O_TRACEEXEC;
if unsafe { ptrace(PTRACE_SETOPTIONS, pid, 0, options) } != 0 {
panic!("unable to trace seccomp on child: {}", unsafe { *__errno_location() });
}
// Start the process
continueit(pid);
sendcont(pid);
// Wait for execve to succeed
loop {
let status = waitit(pid);
match status {
// Skip execve's
PtraceStop::Seccomp => {
if let Ok(syscall) = syscall_info(pid) {
if syscall.syscall == Syscall::execve {
continueit(pid);
continue
}
}
panic!("Unexpected syscall before exec succeed");
},
// And stop skipping syscalls on exec
PtraceStop::Exec => break,
// Anything else is abnormal
_ => panic!("Unknown ptrace stop before exec succeed"),
}
}
continueit(pid);
// And monitor the exec'ed process
loop {
// TODO: manage multiprocess
let status = waitit(pid);
match status {
PtraceStop::Seccomp => {
if let Ok(syscall) = syscall_info(pid) {
match cb(syscall) {
Action::Allow => (),
Action::Kill => killit(pid),
}
} else {
killit(pid); // Kill if we can't decode the syscall
}
}
PtraceStop::Exit => break, // Process just exited
PtraceStop::Exec => (), // Do nothing
PtraceStop::Unknown(s) => panic!("Out of waitit with unknown status 0x{:08x}", s),
// TODO: do not panic in release builds
}
continueit(pid);
}
}
#[derive(Debug)]
pub struct SyscallInfo {
pub syscall: Syscall,
pub args: [u64; 6],
pub path: String,
pub realpath: String,
}
// TODO: remove when auto-derive is ready?
impl Serialize for SyscallInfo {
fn serialize<S: Serializer>(&self, s: &mut S) -> Result<(), S::Error> {
serialize_map!(s, {
"syscall" => self.syscall,
"args" => &self.args,
"path" => &self.path,
"realpath" => &self.realpath
})
}
}
// TODO: also handle files like "test" (neither starting with "." nor with "/")
fn canonicalize(p: &str) -> path::PathBuf {
let mut path = path::PathBuf::new();
path.push(p);
let mut append = path::PathBuf::new();
loop {
if let Ok(res) = fs::canonicalize(&path) {
let mut tmp = res;
tmp.push(append);
return tmp;
}
if let Some(file) = path.clone().file_name() {
let mut tmp = path::PathBuf::new();
tmp.push(file);
tmp.push(append);
append = tmp;
path.pop();
} else {
return path::PathBuf::new();
}
}
}
impl SyscallInfo {
fn new(pid: pid_t, syscall: Syscall, args: [u64; 6]) -> Result<SyscallInfo, PosixError> {
let path = match syscall {
Syscall::open => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::creat => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::unlink => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::execve => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::chdir => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::mknod => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::chmod => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::lchown => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::stat => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::access => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::mkdir => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::rmdir => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::mount => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::chroot => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::lstat => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::readlink => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::uselib => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::swapon => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::truncate => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::statfs => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::swapoff => read_str(pid, args[0], PATH_MAX as usize)?,
Syscall::quotactl => read_str(pid, args[1], PATH_MAX as usize)?,
Syscall::chown => read_str(pid, args[1], PATH_MAX as usize)?,
_ => String::new(),
};
// TODO: compute realpath correctly for *at syscalls, and check all syscalls in @file are covered
// TODO: add IP/port for @network-io syscalls
// TODO: reduce information leakage in @default (uname, sysinfo...)
match canonicalize(&path).into_os_string().into_string() {
Ok(realpath) =>
Ok(SyscallInfo {
syscall: syscall,
args: args,
path: path,
realpath: realpath,
}),
Err(path) => Err(PosixError::InvalidUtf8(path)),
}
}
}
#[repr(C)]
struct user_regs {
r15: u64,
r14: u64,
r13: u64,
r12: u64,
rbp: u64,
rbx: u64,
r11: u64,
r10: u64,
r9: u64,
r8: u64,
rax: u64,
rcx: u64,
rdx: u64,
rsi: u64,
rdi: u64,
orig_rax: u64,
rip: u64,
cs: u64,
eflags: u64,
rsp: u64,
ss: u64,
fs_base: u64,
gs_base: u64,
ds: u64,
es: u64,
fs: u64,
gs: u64,
}
#[derive(Debug)]
pub enum PosixError {
Utf8Error(str::Utf8Error),
PTraceError(i32),
TooLong,
UnknownSyscall(u64),
InvalidUtf8(ffi::OsString),
}
impl From<str::Utf8Error> for PosixError {
fn from(err: str::Utf8Error) -> PosixError {
PosixError::Utf8Error(err)
}
}
fn syscall_info(pid: pid_t) -> Result<SyscallInfo, PosixError> {
let regs: user_regs = unsafe {
let mut regs = MaybeUninit::uninit();
if ptrace(PTRACE_GETREGS, pid, 0, regs.as_mut_ptr()) != 0 {
panic!("Unable to getregs: {}", *__errno_location()); // TODO: Remove this and cleanly handle error
}
regs.assume_init()
};
if let Some(sysc) = syscalls::from(regs.orig_rax) {
SyscallInfo::new(
pid,
sysc,
[regs.rdi, regs.rsi, regs.rdx, regs.r10, regs.r8, regs.r9],
)
} else {
Err(PosixError::UnknownSyscall(regs.orig_rax))
}
}
pub fn read_str(pid: pid_t, addr: u64, maxlen: usize) -> Result<String, PosixError> {
let mut res = String::with_capacity(maxlen + 8);
let mut tmp: i64;
let mut buf: [u8; 8];
loop {
unsafe {
*__errno_location() = 0;
tmp = ptrace(PTRACE_PEEKDATA, pid, addr + (res.len() as u64), 0);
if *__errno_location() != 0 {
return Err(PosixError::PTraceError(*__errno_location()));
}
buf = mem::transmute(tmp);
}
let zero = buf.iter().position(|&x| x == 0);
res.push_str(str::from_utf8(&buf[0..zero.unwrap_or(buf.len())])?);
if res.len() > maxlen {
return Err(PosixError::TooLong);
}
if zero != None {
break;
}
}
res.shrink_to_fit();
Ok(res)
}
#[derive(Debug)]
struct ScriptResult {
decision: Action,
}
struct ScriptResultVisitor;
impl de::Visitor for ScriptResultVisitor {
type Value = ScriptResult;
fn visit_map<M: de::MapVisitor>(&mut self, mut v: M) -> Result<ScriptResult, M::Error> {
let mut decision = None;
while let Some(k) = v.visit_key::<String>()? {
match k.as_ref() {
"decision" => get_if_unset!(v, decision, "decision" ; Action),
_ => return Err(M::Error::unknown_field(&k)),
}
}
v.end()?;
if !decision.is_some() {
return Err(M::Error::missing_field("decision"));
}
Ok(ScriptResult {
decision: decision.unwrap(),
})
}
}
// TODO: Remove when auto-derive lands on stable
impl Deserialize for ScriptResult {
fn deserialize<D: Deserializer>(d: &mut D) -> Result<ScriptResult, D::Error> {
d.deserialize(ScriptResultVisitor)
}
}
pub fn call_script(s: &str, sys: &SyscallInfo) -> Action {
let cmd = Command::new(s)
.arg(serde_json::to_string(&sys).unwrap())
.stderr(Stdio::inherit())
.output()
.expect(&format!("failed to execute script {}", s));
if !cmd.status.success() {
println_stderr!("toboggan: Script '{}' failed!", s);
return Action::Kill
}
let stdout = str::from_utf8(&cmd.stdout);
if stdout.is_err() {
println_stderr!("toboggan: Script '{}' wrote invalid UTF-8 output!", s);
return Action::Kill
}
let res = serde_json::from_str(stdout.unwrap());
if res.is_err() {
// TODO: cleanly display error
println_stderr!("toboggan: Unable to parse output of script '{}' ({}):", s, res.unwrap_err());
println_stderr!("{}", stdout.unwrap());
return Action::Kill
}
let res: ScriptResult = res.unwrap();
res.decision
}
#[cfg(test)]
mod tests {
use super::*;
use super::{waitforcont, sendcont, continueit, killit, canonicalize};
use libc;
use std::{thread, time, path};
use serde_json;
use syscalls::Syscall;
// TODO: find a way to test exec
// TODO: find a way to test ptracehim
#[test]
fn wait_and_cont() {
let oldset = blockusr1();
let pid = unsafe { libc::fork() };
if pid == 0 {
thread::sleep(time::Duration::from_millis(100));
waitforcont();
unsafe { libc::exit(0) }
}
sendcont(pid);
assert_eq!(waitit(pid), PtraceStop::Exit);
continueit(pid);
let pid = unsafe { libc::fork() };
if pid == 0 {
ptraceme();
unsafe { libc::exit(0) }
}
thread::sleep(time::Duration::from_millis(100));
sendcont(pid);
assert_eq!(waitit(pid), PtraceStop::Exit);
continueit(pid);
setsigmask(oldset);
}
#[test]
fn test_kill() {
let pid = unsafe { libc::fork() };
if pid == 0 {
loop { }
}
killit(pid);
waitit(pid);
}
#[test]
fn syscallinfo_serialize() {
assert_eq!(serde_json::to_string_pretty(&SyscallInfo {
syscall: Syscall::read,
args: [0, 5, 32, 79, 12, 51],
path: String::from("/foo/bar/baz"),
realpath: String::from("/quux/baz"),
}).unwrap(), r#"{
"syscall": "read",
"args": [
0,
5,
32,
79,
12,
51
],
"path": "/foo/bar/baz",
"realpath": "/quux/baz"
}"#);
}
#[test]
fn test_canonicalize() {
// TODO: This assumes /var/run is a symlink to /run, find a way to make this env-agnostic
assert_eq!(canonicalize("/var/run/thisdoesnotexist/bar/baz"),
path::PathBuf::from("/run/thisdoesnotexist/bar/baz"));
}
// TODO: Find a way to test SyscallInfo::new, syscall_info, read_str
}
|
gpl-3.0
|
ZhenanLee/greenhouse2016
|
php/review_data.php
|
2435
|
<?php
// Start MySQL Connection
include('dbconnect.php');
?>
<html>
<head>
<title>Arduino Temperature Log</title>
<style type="text/css">
.table_titles, .table_cells_odd, .table_cells_even {
padding-right: 20px;
padding-left: 20px;
color: #000;
}
.table_titles {
color: #FFF;
background-color: #666;
}
.table_cells_odd {
background-color: #CCC;
}
.table_cells_even {
background-color: #FAFAFA;
}
table {
border: 2px solid #333;
}
body { font-family: "Trebuchet MS", Arial; }
</style>
</head>
<body>
<h1>Arduino Parameter Log</h1>
<table border="0" cellspacing="0" cellpadding="4">
<tr>
<td class="table_titles">ID</td>
<td class="table_titles">Date</td>
<td class="table_titles">Temperature</td>
<td class="table_titles">Humidity</td>
<td class="table_titles">Moisture</td>
</tr>
<?php
// Retrieve all records and display them
$query = "SELECT * FROM parameters ";
$query .= "ORDER BY ";
$query .= "id ASC";
//resource
$result = mysqli_query($connection, $query);
//test if there is a query error
//if result is true and successful row update(id)
/*
if($result && mysqli_affected_rows($connection) == 1){
//Success
// redirect_to("somepage.php");
echo "Success!";
}else{
//Failure
// $message = "Subject update failed";
die("Database query failed! " . mysqli_error($connection));
}
*/
// Used for row color toggle
$oddrow = true;
// process every record
while( $row = mysqli_fetch_array($result) )
{
if ($oddrow)
{
$css_class=' class="table_cells_odd"';
}
else
{
$css_class=' class="table_cells_even"';
}
$oddrow = !$oddrow;
echo '<tr>';
echo ' <td'.$css_class.'>'.$row["id"].'</td>';
echo ' <td'.$css_class.'>'.$row["date"].'</td>';
echo ' <td'.$css_class.'>'.$row["tVal"].'</td>';
echo ' <td'.$css_class.'>'.$row["hVal"].'</td>';
echo ' <td'.$css_class.'>'.$row["mVal"].'</td>';
echo '</tr>';
}
?>
</table>
</body>
</html>
|
gpl-3.0
|
rorosaurus/tf2-bot
|
src/ui/ScrapPanel.java
|
6806
|
/******************************************************************************
* This file is part of tf2-bot. *
* *
* tf2-bot is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* tf2-bot 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 General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with tf2-bot. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************/
package ui;
import pojos.Metal;
import pojos.PointPlace;
import pojos.Settings;
import providers.PointProvider;
import providers.SettingsProvider;
import robots.ScrapBot;
import robots.TradeBot;
import system.Outputter;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ScrapPanel extends JPanel {
private SettingsProvider settingsProvider;
private PointProvider pointProvider;
private Outputter outputter;
public ScrapPanel(SettingsProvider provider, PointProvider pProvider, Outputter out) throws Exception {
super();
settingsProvider = provider;
pointProvider = pProvider;
outputter = out;
init();
}
private void init() throws Exception {
JPanel scrapPanel = new JPanel();
scrapPanel.setLayout(new BoxLayout(scrapPanel, BoxLayout.Y_AXIS));
JPanel scrapAllPanel = new JPanel();
scrapAllPanel.setLayout(new BoxLayout(scrapAllPanel, BoxLayout.X_AXIS));
final JCheckBox simulateBox = new JCheckBox("Simulate");
simulateBox.setSelected(true);
if(settingsProvider.getSetting(Settings.simulate) != null){
simulateBox.setSelected(Boolean.parseBoolean(settingsProvider.getSetting(Settings.simulate)));
}
final ScrapButton scrapAllButton = new ScrapButton("Scrap All Weapons", settingsProvider);
simulateBox.addItemListener(scrapAllButton);
scrapAllButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if(hasAllPoints()){
try {
if(scrapAllButton.getSimulate()){
outputter.output("Simulating scrapping...");
}
else{
outputter.output("Scrapping items in 3 seconds...");
Thread.sleep(3000);
}
Thread botThread = new Thread(new Runnable() {
public void run() {
try {
ScrapBot robbie = new ScrapBot(pointProvider, settingsProvider, outputter);
robbie.scrapWeapons(true, scrapAllButton.getSimulate());
if(!scrapAllButton.getSimulate()) outputter.output(robbie.getNumOfLeftClicks() + " clicks saved.");
} catch (Exception e) {
e.printStackTrace();
}
}
});
botThread.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
scrapAllPanel.add(scrapAllButton);
scrapAllPanel.add(simulateBox);
scrapPanel.add(scrapAllPanel);
Button combineMetalsButton = new Button("Combine All Metals");
combineMetalsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if(hasAllPoints()){
try {
outputter.output("Combining metal in 3 seconds...");
Thread.sleep(3000);
ScrapBot robbie = new ScrapBot(pointProvider, settingsProvider, outputter);
robbie.combineMetal(Metal.SCRAP);
robbie.combineMetal(Metal.RECLAIMED);
outputter.output(robbie.getNumOfLeftClicks() + " clicks saved.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
scrapPanel.add(combineMetalsButton);
Button scrapCombineSortButton = new Button("Scrap, Combine, and Sort");
scrapCombineSortButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if(hasAllPoints()){
try {
outputter.output("Scrapping, Combining, and Sorting in 3 seconds...");
Thread.sleep(3000);
ScrapBot robbie = new ScrapBot(pointProvider, settingsProvider, outputter);
robbie.scrapWeapons(true, false);
robbie.combineMetal(Metal.SCRAP);
robbie.combineMetal(Metal.RECLAIMED);
robbie.sortBackpack();
outputter.output(robbie.getNumOfLeftClicks() + " clicks saved.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
scrapPanel.add(scrapCombineSortButton);
add(scrapPanel);
}
private boolean hasAllPoints(){
boolean hasEveryPoint = true;
for(PointPlace place : PointPlace.values()){
if(pointProvider.getPoint(place) == null){
hasEveryPoint = false;
outputter.output("Missing point '" + place.toString() + "'.");
}
}
if(!hasEveryPoint) outputter.output("Cannot proceed until points are configured.");
return hasEveryPoint;
}
}
|
gpl-3.0
|
fletch0098/TripToGo
|
wp-content/themes/hestia-pro/ti-about-page/class-themeisle-about-page.php
|
42571
|
<?php
/**
* ThemeIsle - About page class
*
* Example of config array with all parameters ( This needs to be defined in the theme's functions.php:
*
* TI About page register example.
*
* $config = array(
* // Menu name under Appearance.
* 'menu_name' => __( 'About Flymag', 'flymag' ),
* // Page title.
* 'page_name' => __( 'About Flymag', 'flymag' ),
* // Main welcome title
* 'welcome_title' => sprintf( __( 'Welcome to %s! - Version ', 'flymag' ), 'FlyMag' ),
* // Main welcome content
* 'welcome_content' => sprintf( __( '%1$s is now installed and ready to use! Get ready to build something beautiful. We hope you enjoy it! We want to make sure you have the best experience using %2$s and that is why we gathered here all the necessary information for you. We hope you will enjoy using %3$s, as much as we enjoy creating great products.','flymag' ), 'FlyMag', 'FlyMag', 'FlyMag' ),
* //Tabs array.
* //
* // The key needs to be ONLY consisted from letters and underscores. If we want to define outside the class a function to render the tab,
* // the will be the name of the function which will be used to render the tab content.
* 'tabs' => array(
* 'getting_started' => __( 'Getting Started', 'flymag' ),
* 'recommended_actions' => __( 'Recommended Actions', 'flymag' ),
* 'recommended_plugins' => __( 'Recommended Plugins', 'flymag' ),
* 'child_themes' => __( 'Child themes', 'flymag' ),
* 'support' => __( 'Support', 'flymag' ),
* 'changelog' => __( 'Changelog', 'flymag' ),
* 'free_pro' => __( 'Free vs PRO', 'flymag' ),
* ),
* // Support content tab.
* 'support_content' => array(
* 'first' => array (
* 'title' => esc_html__( 'Contact Support','flymag' ),
* 'icon' => 'dashicons dashicons-sos',
* 'text' => esc_html__( 'We offer excellent support through our advanced ticketing system. Make sure to register your purchase before contacting support!','flymag' ),
* 'button_label' => esc_html__( 'Contact Support','flymag' ),
* 'button_link' => esc_url( 'https://themeisle.com/contact/' ),
* 'is_button' => true,
* 'is_new_tab' => false
* ),
* ),
* // Getting started tab content.
* 'getting_started' => array(
* 'first_step' => array (
* 'title' => esc_html__( 'Step 1 - Implement recommended actions','flymag' ),
* 'text' => esc_html__( 'We have compiled a list of steps for you to take so we can ensure that the experience you have using one of our products is very easy to follow.','flymag' ),
* 'button_label' => esc_html__( 'Check recommended actions','flymag' ),
* 'button_link' => esc_url( admin_url( 'themes.php?page=flymag-welcome&tab=recommended_actions' ) ),
* 'is_button' => false,
* 'recommended_actions' => true
* ),
* ),
* // Child themes array.
* 'child_themes' => array(
* 'download_button_label' => 'Download',
* 'preview_button_label' => 'Live preview',
* 'content' => array(
* array(
* 'title' => 'Flymag child theme 1',
* 'image' => 'https://github.com/Codeinwp/zerif-lite/blob/production/inc/admin/welcome-screen/img/zblackbeard.jpg?raw=true',
* 'image_alt' => 'Image of the child theme',
* 'description' => 'Description',
* 'download_link' => 'Download link',
* 'preview_link' => 'Preview link',
* ),
* array(
* 'title' => 'Flymag child theme 2',
* 'image' => 'https://github.com/Codeinwp/zerif-lite/blob/production/inc/admin/welcome-screen/img/zblackbeard.jpg?raw=true',
* 'image_alt' => 'Image of the child theme',
* 'description' => 'Description',
* 'download_link' => 'Download link',
* 'preview_link' => 'Preview link',
* ),
* ),
* ),
* // Free vs PRO array.
* 'free_pro' => array(
* 'free_theme_name' => 'FlyMag',
* 'pro_theme_name' => 'FlyMag PRO',
* 'pro_theme_link' => 'https://themeisle.com/themes/flymag-pro/',
* 'get_pro_theme_label' => sprintf( __( 'Get %s now!', 'flymag' ), 'FlyMag Pro' ),
* 'features' => array(
* array(
* 'title' => __( 'Mobile friendly', 'flymag' ),
* 'description' => __( 'Responsive layout. Works on every device.', 'flymag' ),
* 'is_in_lite' => 'true',
* 'is_in_pro' => 'true',
* ),
* array(
* 'title' => __( 'Unlimited color option', 'flymag' ),
* 'description' => __( 'You can change the colors of each section. You have unlimited options.', 'flymag' ),
* 'is_in_lite' => 'true',
* 'is_in_pro' => 'true',
* ),
* array(
* 'title' => __( 'Background image', 'flymag' ),
* 'description' => __( 'You can use any background image you want.', 'flymag' ),
* 'is_in_lite' => 'true',
* 'is_in_pro' => 'true',
* ),
* array(
* 'title' => __( 'Featured Area', 'flymag' ),
* 'description' => __( 'Have access to a new featured area.', 'flymag' ),
* 'is_in_lite' => 'false',
* 'is_in_pro' => 'true',
* ),
* array(
* 'title' => __( 'Footer credits', 'flymag' ),
* 'description' => '',
* 'is_in_lite' => 'false',
* 'is_in_pro' => 'true',
* ),
* array(
* 'title' => __( 'Extra widgets areas', 'flymag' ),
* 'description' => __( 'More widgets areas for your theme.', 'flymag' ),
* 'is_in_lite' => 'false',
* 'is_in_pro' => 'true',
* ),
* array(
* 'title' => __( 'Support', 'flymag' ),
* 'description' => __( 'You will benefit of our full support for any issues you have with the theme.', 'flymag' ),
* 'is_in_lite' => 'false',
* 'is_in_pro' => 'true',
* ),
* ),
* ),
* // Recommended plugins tab.
* 'recommended_plugins' => array(
* 'already_activated_message' => esc_html__( 'Already activated', 'flymag' ),
* 'version_label' => esc_html__( 'Version: ', 'flymag' ),
* 'install_label' => esc_html__( 'Install', 'flymag' ),
* 'activate_label' => esc_html__( 'Activate', 'flymag' ),
* 'deactivate_label' => esc_html__( 'Deactivate', 'flymag' ),
* 'content' => array(
* array(
* 'slug' => 'pirate-forms',
* ),
* array(
* 'link' => 'http://themeisle.com/plugins/easy-content-types/',
* ),
* array(
* 'slug' => 'siteorigin-panels',
* ),
* array(
* 'slug' => 'intergeo-maps',
* ),
* ),
* ),
* // Required actions array.
* 'recommended_actions' => array(
* 'install_label' => esc_html__( 'Install', 'flymag' ),
* 'activate_label' => esc_html__( 'Activate', 'flymag' ),
* 'deactivate_label' => esc_html__( 'Deactivate', 'flymag' ),
* 'content' => array(
* 'pirate-forms' => array(
* 'title' => __( 'Pirate Forms', 'flymag' ),
* 'description' => __( 'Makes your contact page more engaging by creating a good-looking contact form on your website. The interaction with your visitors was never easier.', 'flymag' ),
* 'link_label' => __( 'Install Pirate Forms', 'flymag' ),
* 'check' => defined( 'PIRATE_FORMS_VERSION' ),
* 'id' => 'pirate-forms',
* 'plugin_slug' => 'pirate-forms'
* ),
* ),
* ),
* );
* Themeisle_About_Page::init( $config );
*
* @package Themeisle
* @subpackage Admin
* @since 1.0.0
*/
if ( ! class_exists( 'Themeisle_About_Page' ) ) {
/**
* Singleton class used for generating the about page of the theme.
*/
class Themeisle_About_Page {
/**
* Define the version of the class.
*
* @var string $version The Themeisle_About_Page class version.
*/
private $version = '1.0.0';
/**
* Used for loading the texts and setup the actions inside the page.
*
* @var array $config The configuration array for the theme used.
*/
private $config;
/**
* Get the theme name using wp_get_theme.
*
* @var string $theme_name The theme name.
*/
private $theme_name;
/**
* Get the theme slug ( theme folder name ).
*
* @var string $theme_slug The theme slug.
*/
private $theme_slug;
/**
* The current theme object.
*
* @var WP_Theme $theme The current theme.
*/
private $theme;
/**
* Holds the theme version.
*
* @var string $theme_version The theme version.
*/
private $theme_version;
/**
* Define the menu item name for the page.
*
* @var string $menu_name The name of the menu name under Appearance settings.
*/
private $menu_name;
/**
* Define the page title name.
*
* @var string $page_name The title of the About page.
*/
private $page_name;
/**
* Define the page tabs.
*
* @var array $tabs The page tabs.
*/
private $tabs;
/**
* Define the html notification content displayed upon activation.
*
* @var string $notification The html notification content.
*/
private $notification;
/**
* The single instance of Themeisle_About_Page
*
* @var Themeisle_About_Page $instance The Themeisle_About_Page instance.
*/
private static $instance;
/**
* The Main Themeisle_About_Page instance.
*
* We make sure that only one instance of Themeisle_About_Page exists in the memory at one time.
*
* @param array $config The configuration array.
*/
public static function init( $config ) {
if ( ! isset( self::$instance ) && ! ( self::$instance instanceof Themeisle_About_Page ) ) {
self::$instance = new Themeisle_About_Page;
if ( ! empty( $config ) && is_array( $config ) ) {
self::$instance->config = $config;
self::$instance->setup_config();
self::$instance->setup_actions();
}
}
}
/**
* Setup the class props based on the config array.
*/
public function setup_config() {
$theme = wp_get_theme();
if ( is_child_theme() ) {
$this->theme_name = $theme->parent()->get( 'Name' );
$this->theme = $theme->parent();
} else {
$this->theme_name = $theme->get( 'Name' );
$this->theme = $theme->parent();
}
$this->theme_version = $theme->get( 'Version' );
$this->theme_slug = $theme->get_template();
$this->menu_name = isset( $this->config['menu_name'] ) ? $this->config['menu_name'] : 'About ' . $this->theme_name;
$this->page_name = isset( $this->config['page_name'] ) ? $this->config['page_name'] : 'About ' . $this->theme_name;
$this->notification = isset( $this->config['notification'] ) ? $this->config['notification'] : ( '<p>' . sprintf( 'Welcome! Thank you for choosing %1$s! To fully take advantage of the best our theme can offer please make sure you visit our %2$swelcome page%3$s.', $this->theme_name, '<a href="' . esc_url( admin_url( 'themes.php?page=' . $this->theme_slug . '-welcome' ) ) . '">', '</a>' ) . '</p><p><a href="' . esc_url( admin_url( 'themes.php?page=' . $this->theme_slug . '-welcome' ) ) . '" class="button" style="text-decoration: none;">' . sprintf( 'Get started with %s', $this->theme_name ) . '</a></p>' );
$this->tabs = isset( $this->config['tabs'] ) ? $this->config['tabs'] : array();
}
/**
* Setup the actions used for this page.
*/
public function setup_actions() {
add_action( 'admin_menu', array( $this, 'register' ) );
/* activation notice */
add_action( 'load-themes.php', array( $this, 'activation_admin_notice' ) );
/* enqueue script and style for about page */
add_action( 'admin_enqueue_scripts', array( $this, 'style_and_scripts' ) );
/* ajax callback for dismissable required actions */
add_action( 'wp_ajax_ti_about_page_dismiss_required_action', array( $this, 'dismiss_required_action_callback' ) );
add_action( 'wp_ajax_nopriv_ti_about_page_dismiss_required_action', array( $this, 'dismiss_required_action_callback' ) );
}
/**
* Hide required tab if no actions present.
*
* @return bool Either hide the tab or not.
*/
public function hide_required( $value, $tab ) {
if ( $tab != 'recommended_actions' ) {
return $value;
}
$required = $this->get_required_actions();
if ( count( $required ) == 0 ) {
return false;
} else {
return true;
}
}
/**
* Register the menu page under Appearance menu.
*/
function register() {
if ( ! empty( $this->menu_name ) && ! empty( $this->page_name ) ) {
$count = 0;
$actions_count = $this->get_required_actions();
if ( ! empty( $actions_count ) ) {
$count = count( $actions_count );
}
$title = $count > 0 ? $this->page_name . '<span class="badge-action-count">' . esc_html( $count ) . '</span>' : $this->page_name;
add_theme_page( $this->menu_name, $title, 'activate_plugins', $this->theme_slug . '-welcome', array(
$this,
'themeisle_about_page_render',
) );
}
}
/**
* Adds an admin notice upon successful activation.
*/
public function activation_admin_notice() {
global $pagenow;
if ( is_admin() && ( 'themes.php' == $pagenow ) && isset( $_GET['activated'] ) ) {
add_action( 'admin_notices', array( $this, 'themeisle_about_page_welcome_admin_notice' ), 99 );
}
}
/**
* Display an admin notice linking to the about page
*/
public function themeisle_about_page_welcome_admin_notice() {
if ( ! empty( $this->notification ) ) {
echo '<div class="updated notice is-dismissible">';
echo wp_kses_post( $this->notification );
echo '</div>';
}
}
/**
* Render the main content page.
*/
public function themeisle_about_page_render() {
if ( ! empty( $this->config['welcome_title'] ) ) {
$welcome_title = $this->config['welcome_title'];
}
if ( ! empty( $this->config['welcome_content'] ) ) {
$welcome_content = $this->config['welcome_content'];
}
if ( ! empty( $welcome_title ) || ! empty( $welcome_content ) || ! empty( $this->tabs ) ) {
echo '<div class="wrap about-wrap epsilon-wrap">';
if ( ! empty( $welcome_title ) ) {
echo '<h1>';
echo esc_html( $welcome_title );
if ( ! empty( $this->theme_version ) ) {
echo esc_html( $this->theme_version ) . ' </sup>';
}
echo '</h1>';
}
if ( ! empty( $welcome_content ) ) {
echo '<div class="about-text">' . wp_kses_post( $welcome_content ) . '</div>';
}
echo '<a href="https://themeisle.com/" target="_blank" class="wp-badge epsilon-welcome-logo"></a>';
/* Display tabs */
if ( ! empty( $this->tabs ) ) {
$active_tab = isset( $_GET['tab'] ) ? wp_unslash( $_GET['tab'] ) : 'getting_started';
echo '<h2 class="nav-tab-wrapper wp-clearfix">';
$actions_count = $this->get_required_actions();
$count = 0;
if ( ! empty( $actions_count ) ) {
$count = count( $actions_count );
}
foreach ( $this->tabs as $tab_key => $tab_name ) {
if ( ( $tab_key != 'changelog' ) || ( ( $tab_key == 'changelog' ) && isset( $_GET['show'] ) && ( $_GET['show'] == 'yes' ) ) ) {
if ( ( $count == 0 ) && ( $tab_key == 'recommended_actions' ) ) {
continue;
}
echo '<a href="' . esc_url( admin_url( 'themes.php?page=' . $this->theme_slug . '-welcome' ) ) . '&tab=' . $tab_key . '" class="nav-tab ' . ( $active_tab == $tab_key ? 'nav-tab-active' : '' ) . '" role="tab" data-toggle="tab">';
echo esc_html( $tab_name );
if ( $tab_key == 'recommended_actions' ) {
$count = 0;
$actions_count = $this->get_required_actions();
if ( ! empty( $actions_count ) ) {
$count = count( $actions_count );
}
if ( $count > 0 ) {
echo '<span class="badge-action-count">' . esc_html( $count ) . '</span>';
}
}
echo '</a>';
}
}
echo '</h2>';
/* Display content for current tab */
if ( method_exists( $this, $active_tab ) ) {
$this->$active_tab();
}
}// End if().
echo '</div><!--/.wrap.about-wrap-->';
}// End if().
}
/**
* Call plugin api
*/
public function call_plugin_api( $slug ) {
include_once( ABSPATH . 'wp-admin/includes/plugin-install.php' );
$call_api = get_transient( 'ti_about_plugin_info_' . $slug );
if ( false === $call_api ) {
$call_api = plugins_api( 'plugin_information', array(
'slug' => $slug,
'fields' => array(
'downloaded' => false,
'rating' => false,
'description' => false,
'short_description' => true,
'donate_link' => false,
'tags' => false,
'sections' => true,
'homepage' => true,
'added' => false,
'last_updated' => false,
'compatibility' => false,
'tested' => false,
'requires' => false,
'downloadlink' => false,
'icons' => true,
),
) );
set_transient( 'ti_about_plugin_info_' . $slug, $call_api, 30 * MINUTE_IN_SECONDS );
}
return $call_api;
}
/**
* Check if plugin is active
*
* @param plugin-slug $slug the plugin slug.
* @return array
*/
public function check_if_plugin_active( $slug ) {
if ( ( $slug == 'intergeo-maps' ) || ( $slug == 'visualizer' ) ) {
$plugin_root_file = 'index';
} elseif ( $slug == 'adblock-notify-by-bweb' ) {
$plugin_root_file = 'adblock-notify';
} else {
$plugin_root_file = $slug;
}
$path = WPMU_PLUGIN_DIR . '/' . $slug . '/' . $plugin_root_file . '.php';
if ( ! file_exists( $path ) ) {
$path = WP_PLUGIN_DIR . '/' . $slug . '/' . $plugin_root_file . '.php';
if ( ! file_exists( $path ) ) {
$path = false;
}
}
if ( file_exists( $path ) ) {
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
$needs = is_plugin_active( $slug . '/' . $plugin_root_file . '.php' ) ? 'deactivate' : 'activate';
return array(
'status' => is_plugin_active( $slug . '/' . $plugin_root_file . '.php' ),
'needs' => $needs,
);
}
return array(
'status' => false,
'needs' => 'install',
);
}
/**
* Get icon of wordpress.org plugin
*
* @param array $arr array of image formats.
*
* @return mixed
*/
public function get_plugin_icon( $arr ) {
if ( ! empty( $arr['svg'] ) ) {
$plugin_icon_url = $arr['svg'];
} elseif ( ! empty( $arr['2x'] ) ) {
$plugin_icon_url = $arr['2x'];
} elseif ( ! empty( $arr['1x'] ) ) {
$plugin_icon_url = $arr['1x'];
} else {
$plugin_icon_url = get_template_directory_uri() . '/ti-about-page/images/placeholder_plugin.png';
}
return $plugin_icon_url;
}
/**
* Function that crates the action link for install/activate/deactivate.
*
* @param Plugin-state $state the plugin state (uninstalled/active/inactive).
* @param Plugin-slug $slug the plugin slug.
*
* @return string
*/
public function create_action_link( $state, $slug ) {
if ( ( $slug == 'intergeo-maps' ) || ( $slug == 'visualizer' ) ) {
$plugin_root_file = 'index';
} elseif ( $slug == 'adblock-notify-by-bweb' ) {
$plugin_root_file = 'adblock-notify';
} else {
$plugin_root_file = $slug;
}
switch ( $state ) {
case 'install':
return wp_nonce_url(
add_query_arg(
array(
'action' => 'install-plugin',
'plugin' => $slug,
),
network_admin_url( 'update.php' )
),
'install-plugin_' . $slug
);
break;
case 'deactivate':
return add_query_arg( array(
'action' => 'deactivate',
'plugin' => rawurlencode( $slug . '/' . $plugin_root_file . '.php' ),
'plugin_status' => 'all',
'paged' => '1',
'_wpnonce' => wp_create_nonce( 'deactivate-plugin_' . $slug . '/' . $plugin_root_file . '.php' ),
), network_admin_url( 'plugins.php' ) );
break;
case 'activate':
return add_query_arg( array(
'action' => 'activate',
'plugin' => rawurlencode( $slug . '/' . $plugin_root_file . '.php' ),
'plugin_status' => 'all',
'paged' => '1',
'_wpnonce' => wp_create_nonce( 'activate-plugin_' . $slug . '/' . $plugin_root_file . '.php' ),
), network_admin_url( 'plugins.php' ) );
break;
}
}
/**
* Getting started tab
*/
public function getting_started() {
if ( ! empty( $this->config['getting_started'] ) ) {
$getting_started = $this->config['getting_started'];
if ( ! empty( $getting_started ) ) {
echo '<div class="feature-section three-col">';
foreach ( $getting_started as $getting_started_item ) {
echo '<div class="col">';
if ( ! empty( $getting_started_item['title'] ) ) {
echo '<h3>' . $getting_started_item['title'] . '</h3>';
}
if ( ! empty( $getting_started_item['text'] ) ) {
echo '<p>' . $getting_started_item['text'] . '</p>';
}
if ( ! empty( $getting_started_item['button_link'] ) && ! empty( $getting_started_item['button_label'] ) ) {
echo '<p>';
$button_class = '';
if ( $getting_started_item['is_button'] ) {
$button_class = 'button button-primary';
}
$count = 0;
$actions_count = $this->get_required_actions();
if ( ! empty( $actions_count ) ) {
$count = count( $actions_count );
}
if ( $getting_started_item['recommended_actions'] && isset( $count ) ) {
if ( $count == 0 ) {
echo '<span class="dashicons dashicons-yes"></span>';
} else {
echo '<span class="dashicons dashicons-no-alt"></span>';
}
}
$button_new_tab = '_self';
if ( isset( $getting_started_item['is_new_tab'] ) ) {
if ( $getting_started_item['is_new_tab'] ) {
$button_new_tab = '_blank';
}
}
echo '<a target="' . $button_new_tab . '" href="' . $getting_started_item['button_link'] . '"class="' . $button_class . '">' . $getting_started_item['button_label'] . '</a>';
echo '</p>';
}
echo '</div><!-- .col -->';
}// End foreach().
echo '</div><!-- .feature-section three-col -->';
}// End if().
}// End if().
}
/**
* Recommended Actions tab
*/
public function recommended_actions() {
$recommended_actions = isset( $this->config['recommended_actions'] ) ? $this->config['recommended_actions'] : array();
if ( ! empty( $recommended_actions ) ) {
echo '<div class="feature-section action-required demo-import-boxed" id="plugin-filter">';
$actions = array();
$req_actions = isset( $this->config['recommended_actions'] ) ? $this->config['recommended_actions'] : array();
foreach ( $req_actions['content'] as $req_action ) {
$actions[] = $req_action;
}
if ( ! empty( $actions ) && is_array( $actions ) ) {
$ti_about_page_show_required_actions = get_option( $this->theme_slug . '_required_actions' );
$hooray = true;
foreach ( $actions as $action_key => $action_value ) {
$hidden = false;
if ( $ti_about_page_show_required_actions[ $action_value['id'] ] === false ) {
$hidden = true;
}
if ( $action_value['check'] ) {
continue;
}
echo '<div class="ti-about-page-action-required-box">';
if ( ! $hidden ) {
echo '<span data-action="dismiss" class="dashicons dashicons-visibility ti-about-page-required-action-button" id="' . esc_attr( $action_value['id'] ) . '"></span>';
} else {
echo '<span data-action="add" class="dashicons dashicons-hidden ti-about-page-required-action-button" id="' . esc_attr( $action_value['id'] ) . '"></span>';
}
if ( ! empty( $action_value['title'] ) ) {
echo '<h3>' . wp_kses_post( $action_value['title'] ) . '</h3>';
}
if ( ! empty( $action_value['description'] ) ) {
echo '<p>' . wp_kses_post( $action_value['description'] ) . '</p>';
}
if ( ! empty( $action_value['plugin_slug'] ) ) {
$active = $this->check_if_plugin_active( $action_value['plugin_slug'] );
$url = $this->create_action_link( $active['needs'], $action_value['plugin_slug'] );
$label = '';
switch ( $active['needs'] ) {
case 'install':
$class = 'install-now button';
if ( ! empty( $this->config['recommended_actions']['install_label'] ) ) {
$label = $this->config['recommended_actions']['install_label'];
}
break;
case 'activate':
$class = 'activate-now button button-primary';
if ( ! empty( $this->config['recommended_actions']['activate_label'] ) ) {
$label = $this->config['recommended_actions']['activate_label'];
}
break;
case 'deactivate':
$class = 'deactivate-now button';
if ( ! empty( $this->config['recommended_actions']['deactivate_label'] ) ) {
$label = $this->config['recommended_actions']['deactivate_label'];
}
break;
}
?>
<p class="plugin-card-<?php echo esc_attr( $action_value['plugin_slug'] ) ?> action_button <?php echo ( $active['needs'] !== 'install' && $active['status'] ) ? 'active' : '' ?>">
<a data-slug="<?php echo esc_attr( $action_value['plugin_slug'] ) ?>"
class="<?php echo esc_attr( $class ); ?>"
href="<?php echo esc_url( $url ) ?>"> <?php echo esc_html( $label ) ?> </a>
</p>
<?php
}// End if().
echo '</div>';
}// End foreach().
}// End if().
echo '</div>';
}// End if().
}
/**
* Recommended plugins tab
*/
public function recommended_plugins() {
$recommended_plugins = $this->config['recommended_plugins'];
if ( ! empty( $recommended_plugins ) ) {
if ( ! empty( $recommended_plugins['content'] ) && is_array( $recommended_plugins['content'] ) ) {
echo '<div class="feature-section recommended-plugins three-col demo-import-boxed" id="plugin-filter">';
foreach ( $recommended_plugins['content'] as $recommended_plugins_item ) {
if ( ! empty( $recommended_plugins_item['slug'] ) ) {
$info = $this->call_plugin_api( $recommended_plugins_item['slug'] );
if ( ! empty( $info->icons ) ) {
$icon = $this->get_plugin_icon( $info->icons );
}
$active = $this->check_if_plugin_active( $recommended_plugins_item['slug'] );
if ( ! empty( $active['needs'] ) ) {
$url = $this->create_action_link( $active['needs'], $recommended_plugins_item['slug'] );
}
echo '<div class="col plugin_box">';
if ( ! empty( $icon ) ) {
echo '<img src="' . esc_url( $icon ) . '" alt="plugin box image">';
}
if ( ! empty( $info->version ) ) {
echo '<span class="version">' . ( ! empty( $this->config['recommended_plugins']['version_label'] ) ? esc_html( $this->config['recommended_plugins']['version_label'] ) : '' ) . esc_html( $info->version ) . '</span>';
}
if ( ! empty( $info->author ) ) {
echo '<span class="separator"> | </span>' . wp_kses_post( $info->author );
}
if ( ! empty( $info->name ) && ! empty( $active ) ) {
echo '<div class="action_bar ' . ( ( $active['needs'] !== 'install' && $active['status'] ) ? 'active' : '' ) . '">';
echo '<span class="plugin_name">' . ( ( $active['needs'] !== 'install' && $active['status'] ) ? 'Active: ' : '' ) . esc_html( $info->name ) . '</span>';
echo '</div>';
$label = '';
switch ( $active['needs'] ) {
case 'install':
$class = 'install-now button';
if ( ! empty( $this->config['recommended_plugins']['install_label'] ) ) {
$label = $this->config['recommended_plugins']['install_label'];
}
break;
case 'activate':
$class = 'activate-now button button-primary';
if ( ! empty( $this->config['recommended_plugins']['activate_label'] ) ) {
$label = $this->config['recommended_plugins']['activate_label'];
}
break;
case 'deactivate':
$class = 'deactivate-now button';
if ( ! empty( $this->config['recommended_plugins']['deactivate_label'] ) ) {
$label = $this->config['recommended_plugins']['deactivate_label'];
}
break;
}
echo '<span class="plugin-card-' . esc_attr( $recommended_plugins_item['slug'] ) . ' action_button ' . ( ( $active['needs'] !== 'install' && $active['status'] ) ? 'active' : '' ) . '">';
echo '<a data-slug="' . esc_attr( $recommended_plugins_item['slug'] ) . '" class="' . esc_attr( $class ) . '" href="' . esc_url( $url ) . '">' . esc_html( $label ) . '</a>';
echo '</span>';
}
echo '</div><!-- .col.plugin_box -->';
}// End if().
}// End foreach().
echo '</div><!-- .recommended-plugins -->';
}// End if().
}// End if().
}
/**
* Child themes
*/
public function child_themes() {
echo '<div id="child-themes" class="ti-about-page-tab-pane">';
$child_themes = isset( $this->config['child_themes'] ) ? $this->config['child_themes'] : array();
if ( ! empty( $child_themes ) ) {
if ( ! empty( $child_themes['content'] ) && is_array( $child_themes['content'] ) ) {
echo '<div class="ti-about-row">';
for ( $i = 0; $i < count( $child_themes['content'] ); $i ++ ) {
if ( ( $i !== 0 ) && ( $i / 3 === 0 ) ) {
echo '</div>';
echo '<div class="ti-about-row">';
}
$child = $child_themes['content'][ $i ];
if ( ! empty( $child['image'] ) ) {
echo '<div class="ti-about-child-theme">';
echo '<div class="ti-about-page-child-theme-image">';
echo '<img src="' . esc_url( $child['image'] ) . '" alt="' . ( ! empty( $child['image_alt'] ) ? esc_html( $child['image_alt'] ) : '' ) . '" />';
if ( ! empty( $child['title'] ) ) {
echo '<div class="ti-about-page-child-theme-details">';
if ( $child['title'] != $this->theme_name ) {
echo '<div class="theme-details">';
echo '<span class="theme-name">' . $child['title'] . '</span>';
if ( ! empty( $child['download_link'] ) && ! empty( $child_themes['download_button_label'] ) ) {
echo '<a href="' . esc_url( $child['download_link'] ) . '" class="button button-primary install right">' . esc_html( $child_themes['download_button_label'] ) . '</a>';
}
if ( ! empty( $child['preview_link'] ) && ! empty( $child_themes['preview_button_label'] ) ) {
echo '<a class="button button-secondary preview right" target="_blank" href="' . $child['preview_link'] . '">' . esc_html( $child_themes['preview_button_label'] ) . '</a>';
}
echo '</div>';
}
echo '</div>';
}
echo '</div><!--ti-about-page-child-theme-image-->';
echo '</div><!--ti-about-child-theme-->';
}// End if().
}// End for().
echo '</div>';
}// End if().
}// End if().
echo '</div>';
}
/**
* Support tab
*/
public function support() {
echo '<div class="feature-section three-col">';
if ( ! empty( $this->config['support_content'] ) ) {
$support_steps = $this->config['support_content'];
if ( ! empty( $support_steps ) ) {
foreach ( $support_steps as $support_step ) {
echo '<div class="col">';
if ( ! empty( $support_step['title'] ) ) {
echo '<h3>';
if ( ! empty( $support_step['icon'] ) ) {
echo '<i class="' . $support_step['icon'] . '"></i>';
}
echo $support_step['title'];
echo '</h3>';
}
if ( ! empty( $support_step['text'] ) ) {
echo '<p><i>' . $support_step['text'] . '</i></p>';
}
if ( ! empty( $support_step['button_link'] ) && ! empty( $support_step['button_label'] ) ) {
echo '<p>';
$button_class = '';
if ( $support_step['is_button'] ) {
$button_class = 'button button-primary';
}
$button_new_tab = '_self';
if ( isset( $support_step['is_new_tab'] ) ) {
if ( $support_step['is_new_tab'] ) {
$button_new_tab = '_blank';
}
}
echo '<a target="' . $button_new_tab . '" href="' . $support_step['button_link'] . '"class="' . $button_class . '">' . $support_step['button_label'] . '</a>';
echo '</p>';
}
echo '</div>';
}// End foreach().
}// End if().
}// End if().
echo '</div>';
}
/**
* Changelog tab
*/
public function changelog() {
$changelog = $this->parse_changelog();
if ( ! empty( $changelog ) ) {
echo '<div class="featured-section changelog">';
foreach ( $changelog as $release ) {
if ( ! empty( $release['title'] ) ) {
echo '<h2>' . $release['title'] . ' </h2 > ';
}
if ( ! empty( $release['changes'] ) ) {
echo implode( '<br/>', $release['changes'] );
}
}
echo '</div><!-- .featured-section.changelog -->';
}
}
/**
* Return the releases changes array.
*
* @return array The releases array.
*/
private function parse_changelog() {
WP_Filesystem();
global $wp_filesystem;
$changelog = $wp_filesystem->get_contents( get_template_directory() . '/CHANGELOG.md' );
if ( is_wp_error( $changelog ) ) {
$changelog = '';
}
$changelog = explode( PHP_EOL, $changelog );
$releases = array();
foreach ( $changelog as $changelog_line ) {
if ( strpos( $changelog_line, '**Changes:**' ) !== false || empty( $changelog_line ) ) {
continue;
}
if ( substr( $changelog_line, 0, 3 ) === '###' ) {
if ( isset( $release ) ) {
$releases[] = $release;
}
$release = array(
'title' => substr( $changelog_line, 3 ),
'changes' => array(),
);
} else {
$release['changes'][] = $changelog_line;
}
}
return $releases;
}
/**
* Free vs PRO tab
*/
public function free_pro() {
$free_pro = isset( $this->config['free_pro'] ) ? $this->config['free_pro'] : array();
if ( ! empty( $free_pro ) ) {
if ( ! empty( $free_pro['free_theme_name'] ) && ! empty( $free_pro['pro_theme_name'] ) && ! empty( $free_pro['features'] ) && is_array( $free_pro['features'] ) ) {
echo '<div class="feature-section">';
echo '<div id="free_pro" class="ti-about-page-tab-pane ti-about-page-fre-pro">';
echo '<table class="free-pro-table">';
echo '<thead>';
echo '<tr>';
echo '<th></th>';
echo '<th>' . esc_html( $free_pro['free_theme_name'] ) . '</th>';
echo '<th>' . esc_html( $free_pro['pro_theme_name'] ) . '</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
foreach ( $free_pro['features'] as $feature ) {
echo '<tr>';
if ( ! empty( $feature['title'] ) || ! empty( $feature['description'] ) ) {
echo '<td>';
if ( ! empty( $feature['title'] ) ) {
echo '<h3>' . wp_kses_post( $feature['title'] ) . '</h3>';
}
if ( ! empty( $feature['description'] ) ) {
echo '<p>' . wp_kses_post( $feature['description'] ) . '</p>';
}
echo '</td>';
}
if ( ! empty( $feature['is_in_lite'] ) && ( $feature['is_in_lite'] == 'true' ) ) {
echo '<td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td>';
} else {
echo '<td class="only-pro"><span class="dashicons-before dashicons-no-alt"></span></td>';
}
if ( ! empty( $feature['is_in_pro'] ) && ( $feature['is_in_pro'] == 'true' ) ) {
echo '<td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td>';
} else {
echo '<td class="only-pro"><span class="dashicons-before dashicons-no-alt"></span></td>';
}
echo '</tr>';
}
if ( ! empty( $free_pro['pro_theme_link'] ) && ! empty( $free_pro['get_pro_theme_label'] ) ) {
echo '<tr class="ti-about-page-text-center">';
echo '<td></td>';
echo '<td colspan="2"><a href="' . esc_url( $free_pro['pro_theme_link'] ) . '" target="_blank" class="button button-primary button-hero">' . wp_kses_post( $free_pro['get_pro_theme_label'] ) . '</a></td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
echo '</div>';
echo '</div>';
}// End if().
}// End if().
}
/**
* Load css and scripts for the about page
*/
public function style_and_scripts( $hook_suffix ) {
// this is needed on all admin pages, not just the about page, for the badge action count in the wordpress main sidebar
wp_enqueue_style( 'ti-about-page-css', get_template_directory_uri() . '/ti-about-page/css/ti_about_page_css.css', array(), HESTIA_VERSION );
if ( 'appearance_page_' . $this->theme_slug . '-welcome' == $hook_suffix ) {
wp_enqueue_script( 'ti-about-page-js', get_template_directory_uri() . '/ti-about-page/js/ti_about_page_scripts.js', array( 'jquery' ), HESTIA_VERSION );
wp_enqueue_style( 'plugin-install' );
wp_enqueue_script( 'plugin-install' );
wp_enqueue_script( 'updates' );
$recommended_actions = isset( $this->config['recommended_actions'] ) ? $this->config['recommended_actions'] : array();
$required_actions = $this->get_required_actions();
wp_localize_script( 'ti-about-page-js', 'tiAboutPageObject', array(
'nr_actions_required' => count( $required_actions ),
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'template_directory' => get_template_directory_uri(),
'activating_string' => esc_html__( 'Activating', 'hestia-pro' ),
) );
}
}
/**
* Return the valid array of required actions.
*
* @return array The valid array of required actions.
*/
private function get_required_actions() {
$saved_actions = get_option( $this->theme_slug . '_required_actions' );
if ( ! is_array( $saved_actions ) ) {
$saved_actions = array();
}
$req_actions = isset( $this->config['recommended_actions'] ) ? $this->config['recommended_actions'] : array();
$valid = array();
foreach ( $req_actions['content'] as $req_action ) {
if ( ( ! isset( $req_action['check'] ) || ( isset( $req_action['check'] ) && ( $req_action['check'] == false ) ) ) && ( ! isset( $saved_actions[ $req_action['id'] ] ) ) ) {
$valid[] = $req_action;
}
}
return $valid;
}
/**
* Dismiss required actions
*/
public function dismiss_required_action_callback() {
$recommended_actions = array();
$req_actions = isset( $this->config['recommended_actions'] ) ? $this->config['recommended_actions'] : array();
foreach ( $req_actions['content'] as $req_action ) {
$recommended_actions[] = $req_action;
}
$action_id = ( isset( $_GET['id'] ) ) ? $_GET['id'] : 0;
echo esc_html( wp_unslash( $action_id ) ); /* this is needed and it's the id of the dismissable required action */
if ( ! empty( $action_id ) ) {
/* if the option exists, update the record for the specified id */
if ( get_option( $this->theme_slug . '_required_actions' ) ) {
$ti_about_page_show_required_actions = get_option( $this->theme_slug . '_required_actions' );
switch ( esc_html( $_GET['todo'] ) ) {
case 'add';
$ti_about_page_show_required_actions[ absint( $action_id ) ] = true;
break;
case 'dismiss';
$ti_about_page_show_required_actions[ absint( $action_id ) ] = false;
break;
}
update_option( $this->theme_slug . '_required_actions', $ti_about_page_show_required_actions );
/* create the new option,with false for the specified id */
} else {
$ti_about_page_show_required_actions_new = array();
if ( ! empty( $recommended_actions ) ) {
foreach ( $recommended_actions as $ti_about_page_required_action ) {
if ( $ti_about_page_required_action['id'] == $action_id ) {
$ti_about_page_show_required_actions_new[ $ti_about_page_required_action['id'] ] = false;
} else {
$ti_about_page_show_required_actions_new[ $ti_about_page_required_action['id'] ] = true;
}
}
update_option( $this->theme_slug . '_required_actions', $ti_about_page_show_required_actions_new );
}
}
}// End if().
}
}
}// End if().
|
gpl-3.0
|
czertbytes/tierheimdb
|
piggybank/shelter.go
|
2754
|
package piggybank
import (
"fmt"
"time"
)
func PutShelters(shelters []*Shelter) (Ids, error) {
ids := Ids{}
for _, s := range shelters {
if err := PutShelter(s); err != nil {
return nil, err
}
ids = append(ids, s.Id)
}
return ids, nil
}
func PutShelter(s *Shelter) error {
s.Created = time.Now().Format(time.RFC3339)
return RedisPersistShelter(fmt.Sprintf(REDIS_SHELTER, s.Id), s)
}
func GetAllShelters() (Shelters, error) {
keys, err := RedisGetIndexKeys(REDIS_SHELTERS)
if err != nil {
return nil, err
}
return RedisGetShelters(keys)
}
func GetEnabledShelters() (Shelters, error) {
keys, err := RedisGetIndexKeys(fmt.Sprintf(REDIS_SHELTERS_ENABLED))
if err != nil {
return nil, err
}
return RedisGetShelters(keys)
}
func sheltersWithAnimalType(shelters Shelters, animalType string) Shelters {
if len(animalType) > 0 {
sheltersWithType := Shelters{}
for _, s := range shelters {
if s.HasAnimalType(animalType) {
sheltersWithType = append(sheltersWithType, s)
}
}
shelters = sheltersWithType
}
return shelters
}
func sheltersNear(shelters Shelters, latLon string) (Shelters, error) {
if len(latLon) > 0 {
lat, lon, err := parseLatLon(latLon)
if err != nil {
return nil, err
}
sheltersNear := Shelters{}
for _, s := range shelters {
sLat, sLon, err := parseLatLon(s.LatLon)
if err != nil {
return nil, err
}
distance := haversineFormula(lat, lon, sLat, sLon)
if distance < 50.0 {
sheltersNear = append(sheltersNear, s)
}
}
shelters = sheltersNear
}
return shelters, nil
}
func GetShelters(latLon, animalType string, pagination Pagination) (Shelters, error) {
shelters, err := GetEnabledShelters()
if err != nil {
return nil, err
}
shelters = sheltersWithAnimalType(shelters, animalType)
shelters, err = sheltersNear(shelters, latLon)
if err != nil {
return nil, err
}
return shelters.Paginate(pagination), nil
}
func GetShelter(id string) (Shelter, error) {
if len(id) == 0 {
return Shelter{}, fmt.Errorf("Getting Shelter failed! ShelterId not set!")
}
k := fmt.Sprintf(REDIS_SHELTER, id)
shelters, err := RedisGetShelters(Keys{k})
if err != nil {
return Shelter{}, err
}
if len(shelters) == 0 {
return Shelter{}, fmt.Errorf("Getting Shelter failed! ShelterId '%s' not found!", k)
}
return shelters[0], nil
}
func DeleteEnabledShelters(latLon, animalType string, pagination Pagination) error {
shelters, err := GetShelters(latLon, animalType, pagination)
if err != nil {
return err
}
for _, s := range shelters {
if err := DeleteShelter(s.Id); err != nil {
return err
}
}
return nil
}
func DeleteShelter(id string) error {
return RedisDeleteShelter(fmt.Sprintf(REDIS_SHELTER, id), id)
}
|
gpl-3.0
|
TravelModellingGroup/XTMF
|
Code/NetworkEstimation/Properties/AssemblyInfo.cs
|
2170
|
/*
Copyright 2014 Travel Modelling Group, Department of Civil Engineering, University of Toronto
This file is part of XTMF.
XTMF is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
XTMF 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with XTMF. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle( "NetworkEstimation" )]
[assembly: AssemblyDescription( "" )]
[assembly: AssemblyConfiguration( "" )]
[assembly: AssemblyCompany( "Microsoft" )]
[assembly: AssemblyProduct( "NetworkEstimation" )]
[assembly: AssemblyCopyright( "Copyright © Microsoft 2011" )]
[assembly: AssemblyTrademark( "" )]
[assembly: AssemblyCulture( "" )]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible( false )]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid( "ec5d4ffc-7bda-465a-a729-ab827707869d" )]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion( "1.0.0.0" )]
[assembly: AssemblyFileVersion( "1.0.0.0" )]
|
gpl-3.0
|
acutesoftware/AIKIF
|
aikif/.z_prototype/dataTools.py
|
12997
|
# -*- coding: utf-8 -*-
# dataTools.py written by Duncan Murray 9/4/2014
# Module to manage and process datasets - basically a wrapper
# around existing lists, with added documentation and logging
# for AIKIF and commonly used functions for simple data processing
#
#
# Functions
# Transform columns to new tables
# Generate SQL for imports
# Import and convert CSV to XLS
# uses (?replaces?) most of aspytk data.py
# Usage:
# from AIKIF import dataTools as ds
# ds = dat.DataSet(?C_COUNTRY.XLS?) #existing table (your source file)
# dsOutput = dat.DataSet(?FACT_FILE.XLS?) #output table after processing
# cols = ds.IntentifyColumns() # returns a dict with detailed estimates of col types
# mapping = ds.MapTo(dsOutput)
# mapping.col(?country code?, ?FACT_COUNTRY_ID?)
# mapping.col(?country name?, ?FACT_COUNTRY_DESC?)
# countryRules = bus.DatasetRules(ds) # define rules for this dataset
# countryRules.Add(?China (excl Mongolia)?, ?China?)
# countryRules.Add(?AUSTRALIA?, ?Australia?)
# mapping.Process() # does the work moving data from file 1 to file 2 with column mappings
# countryRules.Apply(dsOutput) # apply rules on which file you want
# dsOutput.Export()
import os
import sys
import csv
import string
try:
import xlrd as xl # NOTE - xlrd imports fine from python shell, but this line cant find it
except:
print('you need to install xlrd')
fldr = '..//..//data//temp//'
root_folder = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + os.sep + ".." + os.sep + ".." + os.sep + "data" + os.sep + "temp")
print(root_folder)
def TEST():
print('Data tools test...')
url = 'http://www.abs.gov.au/AUSSTATS/subscriber.nsf/log?openagent&standard australian classification of countries, 2011, version 2.2.xls&1269.0&Data Cubes&EE21444EE8F2C99CCA257BF30012B66F&0&2011&01.10.2013&Latest'
fname = fldr + 'test.xlsx'
dl_fname = fldr + 'test-download.xlsx'
#DownloadFile(url, dl_fname)
#csv_from_excel(fname , os.getcwd())
testFile = fldr + 'test.csv'
CreateRandomCSVFile(testFile)
GenerateSQL(testFile, 'MY_TABLE', testFile + '.SQL', headerRow=1)
CreateRandomIndentedCSVFile(fldr + 'indented.csv')
# ExtractTable(f, tmpFile, extractList[1]['colList'], 8, 1, 52, 9)
AutoFillCSV(fldr + 'indented.csv', fldr + 'indented-fixed.csv', ['grouping', 'code', 'desc'], ['grouping']) # autofill FIRST col based on prev values
RemoveBlankRecs(fldr + 'indented-fixed.csv', fldr + 'indented-fixed-and-no-blanks.csv', 2)
def delete_file(f):
try:
os.remove(f)
except:
pass
def csv_from_excel(excel_file, pth):
opFname = ''
print('converting file ' + excel_file + ' to folder ' + pth)
workbook = xl.open_workbook(pth + '\\' + excel_file)
all_worksheets = workbook.sheet_names()
for worksheet_name in all_worksheets:
if worksheet_name != 'Pivot':
print('converting - ' + worksheet_name)
worksheet = workbook.sheet_by_name(worksheet_name)
opFname = pth + '\\' + os.path.splitext(excel_file)[0] + '_' + worksheet_name + '.csv'
print('SAVING - ' + opFname)
csv_file = open(opFname, 'wb')
#csv_file = open(pth + ''.join([worksheet_name,'.csv']), 'wb')
wr = csv.writer(csv_file, quoting=csv.QUOTE_ALL)
for rownum in xrange(worksheet.nrows):
wr.writerow([unicode(entry).encode("utf-8") for entry in worksheet.row_values(rownum)])
csv_file.close()
else:
print('ignoring tab - ' + worksheet_name)
def DownloadFile(url, fname):
# bug here - you need to wait for download to finish
net.DownloadFile(url, fname)
def addSampleData(fname, content):
wr = csv.writer(open(fname, 'at'), quoting=csv.QUOTE_ALL, lineterminator='\n')
wr.writerow(content)
def CreateRandomCSVFile(fname):
delete_file(fname)
content = [['id', 'code', 'desc'], ['1', 'S', 'AAA'], ['2', 'B', 'BBB'], ['3', 'X', 'Long description']]
for row in content:
addSampleData(fname, row)
def CreateRandomIndentedCSVFile(fname):
delete_file(fname)
content = [['grouping', 'code', 'desc'], ['1', 'S', 'AAA'], [' ', 'T', 'BBB'], ['3', 'X', 'Long description'], ['', 'Y', 'Long description']]
for row in content:
addSampleData(fname, row)
def IntentifyColumns(fname):
# returns a dict with detailed estimates of col types
print('IntentifyColumns(' + fname + '):')
def DataSet(fname):
# defines a dataset
print('dataset defined = ' + fname)
def MapTo(opFile):
pass
def GetColumnList(csvFile):
with open(csvFile, 'rt') as inf:
inrd = csv.reader(inf)
names = next(inrd)
inf.close()
return names
def GetCountUniqueValues(fname, colNum, colText, topN_values, opFile):
cols = collections.Counter()
with open(fname) as input_file:
for row in csv.reader(input_file, delimiter=','):
cols[row[colNum]] += 1
print (colText, Dict2String(cols.most_common()[0:topN_values]))
addSampleData(opFile, colText + ',' + Dict2String(cols.most_common()[0:topN_values]))
def AnalyseCSV_File(datafile, opFolder):
baseName = opFolder + '\\' + os.path.basename(datafile).split('.')[0]
tmpfile = baseName + '.txt'
colHeaders = dat.GetColumnList(datafile)
colNum = 0
for col in colHeaders:
colText = "".join(map(str,col)) #prints JUST the column name in the list item
print(colText)
dat.GetCountUniqueValues(datafile, colNum, colText, 10, baseName + '_COL_VALUES.csv')
dat.GetColumnCounts(datafile, colNum, colText, baseName + '_COL_COUNTS.csv')
colNum = colNum + 1
def split_CSV_by_Column_names(inputfilename): # TOK
with open(inputfilename, 'rb') as inf:
inrd = csv.reader(inf)
names = next(inrd)
outfiles = [open(n+'.csv', 'wb') for n in names]
ouwr = [csv.writer(w) for w in outfiles]
for w, n in zip(ouwr, names):
w.writerow([n])
for row in inrd:
for w, r in zip(ouwr, row):
w.writerow([r])
for o in outfiles: o.close()
def split_CSV_by_Column_Values(ipFile, colName):
with open(ipFile, 'rb') as inf:
inrd = csv.reader(inf)
names = next(inrd)
for row in csv.reader(inf):
opName = os.path.basename(ipFile)[:-4] + '_' + row[colName] + '.csv'
if not os.path.exists(opName):
createSampleFile(opName, names)
#print("Appending to ", opName)
addSampleData(opName, row)
def ExtractTable(fname, opFile, opCols, startRow=1, startCol=1, endRow=5, endCol=5):
print('Extracting ' + os.path.basename(fname) + ' to ' + opFile)
curRow = 1
curCol = 1
cols = collections.Counter()
csv_file = open(opFile, 'wb')
#wr = csv.writer(csv_file, quoting=csv.QUOTE_ALL)
with open(fname) as input_file:
for hdr in opCols:
csv_file.write('"' + hdr + '",')
csv_file.write('\n')
for row in csv.reader(input_file, delimiter=','):
if curRow >= startRow:
if curRow <= endRow:
curCol = 0
for col in row:
curCol = curCol + 1
if curCol >= startCol:
if curCol <= endCol:
colText = "".join(map(str,col)).strip('"').strip() #prints JUST the column name in the list item
csv_file.write('"' + colText + '",')
#wr.writerow(row)
csv_file.write('\n')
curRow = curRow + 1
csv_file.close()
def AutoFillCSV(fname, opFile, colList, autoFillCols):
# Converts sub total style data to a flat list, e.g. changes:
# 3 HEADING
# 31 data 1
# 32 data 2
print('\nAutoFilling ' + os.path.basename(fname) + ' to ' + opFile)
curCol = 1
lastValues = []
for c in colList:
lastValues.append(c)
print(lastValues)
csv_file = open(opFile, 'w')
with open(fname) as input_file:
for row in csv.reader(input_file, delimiter=','):
for curCol, col in enumerate(row):
colText = "".join(map(str,col)).strip('"').strip() #prints JUST the column name in the list item
if curCol in autoFillCols:
if colText == "":
colText = lastValues[curCol]
else:
lastValues[curCol] = colText
csv_file.write('"' + colText + '",')
csv_file.write('\n')
csv_file.close()
def RemoveBlankRecs(fname, opFile, masterCol):
# removes lines where col number 'masterCol' is blank
print('cleaning ' + os.path.basename(fname) )
curCol = 1
rowText = ''
csv_file = open(opFile, 'w')
with open(fname) as input_file:
for row in csv.reader(input_file, delimiter=','):
keepRow = True
rowText = ''
for curCol, col in enumerate(row):
colText = "".join(map(str,col)).strip('"').strip() #prints JUST the column name in the list item
if curCol == masterCol:
if colText == "":
keepRow = False
rowText = rowText + '"' + colText + '",'
rowText = rowText + '\n'
if keepRow:
csv_file.write(rowText)
csv_file.close()
def GenerateSQL(csvFile, tblName, opFile, headerRow=1):
""" Generates the SQL command to create the table and
insert the data. Output of test.csv.sql is below:
DROP TABLE MY_TABLE CASCADE CONSTRAINTS;
CREATE TABLE MY_TABLE (
ID VARCHAR2(2000),
CODE VARCHAR2(2000),
DESC VARCHAR2(2000),
UPDATE_DATE DATE
);
INSERT INTO MY_TABLE (ID, CODE, DESC, UPDATE_DATE) VALUES (
'id', 'code', 'desc', sysdate );
INSERT INTO MY_TABLE (ID, CODE, DESC, UPDATE_DATE) VALUES (
'1', 'S', 'AAA', sysdate );
INSERT INTO MY_TABLE (ID, CODE, DESC, UPDATE_DATE) VALUES (
'2', 'B', 'BBB', sysdate );
INSERT INTO MY_TABLE (ID, CODE, DESC, UPDATE_DATE) VALUES (
'3', 'X', 'Long description', sysdate );
COMMIT;
"""
import re
if tblName == '':
tbl = str(os.path.basename(csvFile).split('.')[0])
else:
tbl = tblName
if opFile == '':
opFile = str(os.path.basename(csvFile).split('.')[0] + '.SQL')
print("Generating SQL for table " + tbl + " via " + opFile)
# read in the CSV file header
cols = []
SQL_file = open(opFile, 'w') # Note - with one version of Python this needs wb
with open(csvFile) as input_file:
rowNum = 0
for row in csv.reader(input_file, delimiter=','):
rowNum = rowNum + 1
if rowNum == headerRow:
for col in row:
cols.append(clean_column_heading(col))
sql = GenerateSQL_CreateTable(tbl, cols)
#print(tbl, cols, sql)
SQL_file.write(sql)
# now generate the inserts
with open(csvFile) as input_file:
for row in csv.reader(input_file, delimiter=','):
SQL_file.write(GenerateSQL_Insert(tbl, row, cols))
SQL_file.write('COMMIT;')
def clean_column_heading(txt):
""" make the column clean for databases """
clean_text = ''
for char in txt.strip().strip('_'):
if char in '!@#$%^&*()_+=-`~;:",./?>< ':
clean_text += '_'
else:
clean_text += char.upper()
return clean_text.strip('_')
def GenerateSQL_CreateTable(tbl, cols):
txt = 'DROP TABLE ' + tbl + ' CASCADE CONSTRAINTS;\n'
txt = txt + 'CREATE TABLE ' + tbl + ' ( \n'
for c in cols:
if c != '':
txt = txt + ' ' + c + ' VARCHAR2(2000), \n'
txt = txt + ' UPDATE_DATE DATE\n);\n\n'
#print (txt)
return txt
def GenerateSQL_Insert(tbl, row, cols):
txt = 'INSERT INTO ' + tbl + ' ('
for c in cols:
if c != '':
txt = txt + c + ', '
txt = txt + 'UPDATE_DATE) VALUES (\n'
for d in row:
if 'Rahman, M.M.' in row:
print (d)
if d != '':
txt = txt + '\'' + d[0:1999].strip().replace('\'','\'\'').replace('"', '') + '\'' + ', '
else:
txt = txt + 'NULL, '
txt = txt + ' sysdate ); \n'
return txt
def head(fip, fop, numRows):
""" extract the first numLines from fin to fop """
with open(fip, "r") as fin:
with open(fop, "w") as fop:
for lines in range(1, numRows):
fop.write(fin.readline())
if __name__ == '__main__':
TEST()
pass
|
gpl-3.0
|
wandora-team/wandora
|
src/org/wandora/utils/swing/treetable/TreeTable.java
|
3938
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.wandora.utils.swing.treetable;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.awt.*;
import java.util.*;
/**
*
* @author olli
*/
public class TreeTable extends JTable {
protected TreeTableCellRenderer tree;
public TreeTable(TreeTableModel treeTableModel){
super();
tree=new TreeTableCellRenderer(treeTableModel);
super.setModel(new TreeTableModelAdapter(treeTableModel, tree));
tree.setSelectionModel(new DefaultTreeSelectionModel() {
{
setSelectionModel(listSelectionModel);
}
});
tree.setRowHeight(getRowHeight());
setDefaultRenderer(TreeTableModel.class, tree);
setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor());
// setShowGrid(false);
// setIntercellSpacing(new Dimension(0,0));
}
public JTree getTree(){
return tree;
}
public Object getValueForRow(int row){
TreePath path=tree.getPathForRow(row);
if(path==null) return null;
return path.getLastPathComponent();
}
@Override
public int getEditingRow(){
return (getColumnClass(editingColumn) == TreeTableModel.class) ? -1 : editingRow;
}
public class TreeTableCellRenderer extends JTree implements TableCellRenderer {
protected int visibleRow;
public TreeTableCellRenderer(TreeModel model) {
super(model);
}
@Override
public void setBounds(int x, int y, int w, int h) {
super.setBounds(x, 0, w, TreeTable.this.getHeight());
}
@Override
public void paint(Graphics g) {
g.translate(0, -visibleRow * getRowHeight());
super.paint(g);
}
public Component getTableCellRendererComponent(JTable table,Object value,
boolean isSelected,boolean hasFocus,int row, int column) {
if(isSelected) setBackground(table.getSelectionBackground());
else setBackground(table.getBackground());
visibleRow = row;
return this;
}
}
public class TreeTableCellEditor implements TableCellEditor {
protected EventListenerList listeners;
public TreeTableCellEditor(){
listeners=new EventListenerList();
}
public Object getCellEditorValue() { return null; }
public boolean isCellEditable(EventObject e) { return true; }
public boolean shouldSelectCell(EventObject anEvent) { return false; }
public boolean stopCellEditing() { return true; }
public void cancelCellEditing() {}
public void addCellEditorListener(CellEditorListener l) {
listeners.add(CellEditorListener.class, l);
}
public void removeCellEditorListener(CellEditorListener l) {
listeners.remove(CellEditorListener.class, l);
}
protected void fireEditingStopped() {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==CellEditorListener.class) {
((CellEditorListener)listeners[i+1]).editingStopped(new ChangeEvent(this));
}
}
}
protected void fireEditingCanceled() {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==CellEditorListener.class) {
((CellEditorListener)listeners[i+1]).editingCanceled(new ChangeEvent(this));
}
}
}
public Component getTableCellEditorComponent(JTable table, Object value,boolean isSelected, int r, int c) {
return tree;
}
}
}
|
gpl-3.0
|
nicolas-petit/clouder
|
clouder_website_payment/controller/form_controller_extend.py
|
7004
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Yannick Buron, Nicolas Petit
# Copyright 2015, TODAY Clouder SASU
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License with Attribution
# clause as published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License with
# Attribution clause along with this program. If not, see
# <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import http, _, fields
from openerp.http import request
from openerp.addons.clouder_website.controller.form_controller import FormController
import json
import logging
_logger = logging.getLogger(__name__)
HEADERS = [('Access-Control-Allow-Origin', '*')]
class FormControllerExtend(FormController):
"""
Extends clouder_website's HTTP controller to add payment capabilities
"""
def hook_next(self, data):
"""
Returns the payment form after the basic form was submitted
"""
orm_clws = request.env['clouder.web.session'].sudo()
orm_acq = request.env['payment.acquirer'].sudo()
session = orm_clws.browse([data['result']['clws_id']])[0]
company = request.env.ref('base.main_company')
# Saving reference and amount
session.write({
'reference': "{0}_{1}".format(session.name, fields.Date.today()),
'amount': session.application_id.initial_invoice_amount
})
# If instance creation is free, we just get to the creation process
if not session.amount:
return super(FormControllerExtend, self).hook_next(data)
# Setting acquirer buttons
acquirers = []
render_ctx = dict(request.context, submit_class='btn btn-primary', submit_txt=_('Pay Now'))
for acquirer in orm_acq.search([('website_published', '=', True), ('company_id', '=', company.id)]):
acquirer.button = acquirer.with_context(**render_ctx).render(
session.reference,
session.amount,
company.currency_id.id,
partner_id=session.partner_id.id,
tx_values={
'return_url': '/clouder_form/payment_complete',
'cancel_url': '/clouder_form/payment_cancel'
}
)[0]
acquirers.append(acquirer)
# Render the form
qweb_context = {
'acquirers': acquirers,
'hostname': request.httprequest.url_root
}
html = request.env.ref('clouder_website_payment.payment_buttons').render(
qweb_context,
engine='ir.qweb',
context=request.context
)
# Send response
resp = {
'clws_id': session.id,
'html': html,
'div_id': 'CL_payment',
'js': [
'clouder_website_payment/static/src/js/clouder_website_payment.js'
]
}
return request.make_response(json.dumps(resp), headers=HEADERS)
@http.route('/clouder_form/payment_complete', type='http', auth='public', methods=['GET'])
def payment_complete(self, **post):
"""
Redirect page after a successful payment
"""
# Check parameters
lang = 'en_US'
if 'lang' in post:
lang = post['lang']
request.env = self.env_with_context({'lang': lang})
html = request.env.ref('clouder_website_payment.payment_success').render(
{},
engine='ir.qweb',
context=request.context
)
return request.make_response(html, headers=HEADERS)
@http.route('/clouder_form/payment_cancel', type='http', auth='public', methods=['GET'])
def payment_cancel(self, **post):
"""
Redirect page after a cancelled payment
"""
# Check parameters
lang = 'en_US'
if 'lang' in post:
lang = post['lang']
request.env = self.env_with_context({'lang': lang})
html = request.env.ref('clouder_website_payment.payment_cancel').render(
{},
engine='ir.qweb',
context=request.context
)
return request.make_response(html, headers=HEADERS)
@http.route('/clouder_form/payment_popup_wait', type='http', auth='public', methods=['GET'])
def payment_cancel(self, **post):
"""
Redirect page after a cancelled payment
"""
# Check parameters
lang = 'en_US'
if 'lang' in post:
lang = post['lang']
request.env = self.env_with_context({'lang': lang})
html = request.env.ref('clouder_website_payment.payment_popup').render(
{},
engine='ir.qweb',
context=request.context
)
return request.make_response(html, headers=HEADERS)
@http.route('/clouder_form/submit_acquirer', type='http', auth='public', methods=['POST'])
def submit_acquirer(self, **post):
"""
Fetches and returns the HTML base form
"""
# Check parameters
lang = 'en_US'
if 'lang' in post:
lang = post['lang']
request.env = self.env_with_context({'lang': lang})
if 'clws_id' not in post or 'acquirer_id' not in post:
return self.bad_request("Bad request")
else:
post['clws_id'] = int(post['clws_id'])
post['acquirer_id'] = int(post['acquirer_id'])
orm_clws = request.env['clouder.web.session'].sudo()
session = orm_clws.browse([post['clws_id']])[0]
company = request.env.ref('base.main_company')
# Make the payment transaction
orm_paytr = request.env['payment.transaction'].sudo()
orm_paytr.create({
'acquirer_id': post['acquirer_id'],
'type': 'form',
'amount': session.amount,
'currency_id': company.currency_id.id,
'partner_id': session.partner_id.id,
'partner_country_id': session.partner_id.country_id.id,
'reference': session.reference,
})
html = request.env.ref('clouder_website_payment.payment_form_popup_message').render(
{},
engine='ir.qweb',
context=request.context
)
resp = {
'html': html,
'js': [],
'div_id': 'CL_payment_popup'
}
return request.make_response(json.dumps(resp), headers=HEADERS)
|
gpl-3.0
|
mgoral/airball
|
src/Application.cpp
|
3887
|
/**
* Copyright (C) Michal Goral, 2014
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
#include <thread>
#include <chrono>
#include <memory>
#include <SDL2/SDL.h>
#include "Application.hpp"
#include "states/GameState.hpp"
#include "detail/Translate.hpp"
namespace airball
{
Application::Application() : logger_(airball::LogCategoryApplication), stopApp_(false)
{
const unsigned subsystemsToInit =
SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_EVENTS;
if (0 != SDL_Init(subsystemsToInit))
{
throw ApplicationError(_("Could not initialize SDL!"));
}
}
Application::~Application()
{
logger_.debug(_("Performing a clean application exit."));
SDL_Quit();
}
int Application::run()
{
logger_.debug(_("Running Airball"));
airball::Screen screen(100, 100);
states::StateStack stateStack;
std::unique_ptr<states::IState> initialState(new states::GameState());
stateStack.push(std::move(initialState));
const unsigned fpsCap = 50; // TODO: read from config file
const unsigned maxFrameSkip = 10;
std::chrono::nanoseconds timePerUpdate(1000000000 / fpsCap);
std::chrono::nanoseconds lag(0);
auto previousTime = std::chrono::system_clock::now();
bool saveCpu = true; // TODO: read from config file
unsigned loopCount = 0;
// We will render as fast as possible, but the game will be updated only 'fpsCap' times per
// second. We can also sleep (if we have time for that) to reduce CPU usage.
while (!stopApp_)
{
auto currentTime = std::chrono::system_clock::now();
auto elapsedTime = currentTime - previousTime;
previousTime = currentTime;
lag += std::chrono::duration_cast<std::chrono::nanoseconds>(elapsedTime);
loopCount = 0;
while (lag >= timePerUpdate && loopCount < maxFrameSkip)
{
handleInput(stateStack);
stateStack.update();
lag -= timePerUpdate;
++loopCount;
}
// TODO: add interpolation -- screen.setInterpolation(interpolation); (useful during
// animations.
// If object has set Animation (new class consisting vector of Frames), then Screen should
// display instead its Animation
// http://www.koonsolo.com/news/dewitters-gameloop/
stateStack.draw(screen);
// Sleep for a certain amount of time in case we want to save CPU usage.
// Note that in fact it takes into consideration previous frame, not the current one.
if (saveCpu && elapsedTime < timePerUpdate)
{
std::this_thread::sleep_for(timePerUpdate - elapsedTime);
}
}
return 0; // end of program, in fact
}
void Application::handleInput(airball::states::StateStack& stateStack)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
stopApp_ = true;
// TODO: clear stateStack
// maybe add it after main loop (i.e. when while (!stopApp_) finishes, call OnExit
// on all states and pop them
break;
default:
stateStack.handleEvent(event);
}
}
}
} // namespace airball
|
gpl-3.0
|
mriedel/TransFile
|
src/net/sourceforge/transfile/network/BilateralConnector.java
|
11302
|
/*
* Copyright © 2010 Martin Riedel
*
* This file is part of TransFile.
*
* TransFile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TransFile 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TransFile. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sourceforge.transfile.network;
import static net.sourceforge.jenerics.Tools.getLoggerForThisMethod;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.channels.IllegalBlockingModeException;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.logging.Level;
import net.sourceforge.transfile.exceptions.LogicError;
import net.sourceforge.transfile.network.exceptions.BilateralConnectException;
import net.sourceforge.transfile.network.exceptions.ConnectException;
import net.sourceforge.transfile.network.exceptions.ConnectSocketConfigException;
import net.sourceforge.transfile.network.exceptions.ConnectIOException;
import net.sourceforge.transfile.network.exceptions.ConnectSecurityException;
import net.sourceforge.transfile.network.exceptions.ConnectSocketFailedToCloseException;
import net.sourceforge.transfile.network.exceptions.ConnectTimeoutException;
import net.sourceforge.transfile.network.exceptions.ServerException;
import net.sourceforge.transfile.network.exceptions.ServerFailedToBindException;
import net.sourceforge.transfile.network.exceptions.ServerFailedToCloseException;
/**
* TODO doc
*
* @author Martin Riedel
*
*/
public class BilateralConnector extends AbstractConnector {
private final FutureTask<Connection> inboundConnectionAcceptor;
private Exception outboundConnectionError = null;
private Exception inboundConnectionError = null;
/**
*
* Constructs a new instance
* TODO doc
* @param localPeer
* @param remotePeer
*/
public BilateralConnector(final Peer localPeer, final Peer remotePeer) {
super(localPeer, remotePeer);
this.inboundConnectionAcceptor = new FutureTask<Connection>(new ListenerTask(localPeer, remotePeer));
}
/**
* {@inheritDoc}
*/
@Override
public Connection _connect() throws BilateralConnectException, InterruptedException {
Connection outboundConnection = null;
Connection inboundConnection = null;
(new Thread(this.inboundConnectionAcceptor)).start();
try {
outboundConnection = establishOutboundConnection();
} catch (final InterruptedException e) {
// if establishing a Link to the peer has been interrupted, make sure to interrupt
// both connection attempts (both outgoing and incoming) by interrupting connectionFromPeer
this.inboundConnectionAcceptor.cancel(true);
throw e;
} catch (final ConnectException e) {
this.outboundConnectionError = e;
}
try {
inboundConnection = this.inboundConnectionAcceptor.get();
} catch (final CancellationException e) {
throw new InterruptedException();
} catch (final ExecutionException e) {
// listening for an incoming connection from the peer failed
final Throwable cause = e.getCause();
if (cause instanceof ConnectException) {
this.inboundConnectionError = (Exception) cause;
} else if (cause instanceof ServerException) {
this.inboundConnectionError = (Exception) cause;
} else if (cause instanceof InterruptedException) {
// ignore
//TODO safe?
} else {
//TODO handle
}
}
return selectConnection(outboundConnection, inboundConnection);
}
/**
* {@inheritDoc}
*/
@Override
public BilateralConnector clone() {
return new BilateralConnector(getLocalPeer(), getRemotePeer());
}
/**
*
* TODO doc
* @return
* @throws ConnectException
* @throws InterruptedException
*/
private Connection establishOutboundConnection() throws ConnectException, InterruptedException {
final Socket socket = new Socket();
final InetSocketAddress peerAddr = getRemotePeer().toInetSocketAddress();
final long startTime = System.currentTimeMillis();
try {
try {
socket.setReuseAddress(true);
} catch (final SocketException e) {
throw new ConnectSocketConfigException(e);
}
// attempt to connect for a maximum of connectMaxIntervals times
while (true) {
try {
// attempt to connect, timing out after connectIntervalTimeout milliseconds to check for thread interruption
socket.connect(peerAddr, CONNECT_INTERVAL_TIMEOUT);
} catch (SocketTimeoutException e) {
if (Thread.interrupted())
throw new InterruptedException();
} catch (IOException e) {
throw new ConnectIOException(e);
} catch (IllegalBlockingModeException e) {
throw new LogicError(e);
} catch (IllegalArgumentException e) {
throw new LogicError(e);
}
// check if a connection has been established
if (socket.isConnected())
break;
if (System.currentTimeMillis() - startTime >= CONNECT_TIMEOUT)
throw new ConnectTimeoutException();
}
return new Connection(socket, getLocalPeer(), getRemotePeer());
} finally {
// unless the connection was successfully established, close the socket if it exists
if (!socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
throw new ConnectSocketFailedToCloseException(e);
}
}
}
}
/**
* TODO doc
*
* @return
*/
private Connection selectConnection(final Connection c1, final Connection c2)
throws BilateralConnectException {
// if both connections have failed...
if (!isEstablished(c1) && !isEstablished(c2))
throw new BilateralConnectException(this.outboundConnectionError, this.inboundConnectionError);
// if c1 has been established but c2 has failed...
if (isEstablished(c1) && !isEstablished(c2))
return c1;
// if c2 has been established but c1 has failed...
if (!isEstablished(c1) && isEstablished(c2))
return c2;
// both connections have been established, negotiate the selection with the remote peer
//TODO implement
return c1;
}
/**
* TODO doc
*
* @param c
* <br />The {@code Connection} to check
* <br />May be null
* @return
* <br />{@code true} iff the {@code Connection} is established/connected
*/
private static boolean isEstablished(final Connection c) {
return c != null && c.isConnected();
}
/**
* TODO ...
*
* author Martin Riedel
*
*/
//TODO extract as a listener service
private static class ListenerTask implements Callable<Connection> {
/*
* The local port the ServerThread will bind to
*/
private final Peer localPeer;
/*
* The peer who's expected to connect to the local host
*/
private final Peer remotePeer;
/*
* The ServerSocket used to listen for incoming connections
*/
private ServerSocket serverSocket = null;
/*
* The socket representing the connection accepted from the peer
*/
private Socket clientSocket = null;
/**
* Creates a new listener binding to the provided local port. Only connections
* from the specified peer will be accepted.
*
* @param port the local port that the ServerThread will bind to
* @param remotePeer the peer to accept connections from
*/
//TODO properly bind to the entire local address, not just the port
public ListenerTask(final Peer localPeer, final Peer remotePeer) {
this.localPeer = localPeer;
this.remotePeer = remotePeer;
}
/**
* TODO ...
*
*/
@Override
public Connection call()
throws ConnectException, ServerException, InterruptedException {
return acceptConnection();
}
private Connection acceptConnection()
throws ConnectException, ServerException, InterruptedException {
try {
final long startTime = System.currentTimeMillis();
// start listening
//TODO bind to the specific address selected via the GUI, not just any/all
this.serverSocket = new ServerSocket(this.localPeer.getPort());
// set the timeout in milliseconds after which serverSocket.accept() will stop blocking
// so that we can check for thread interruption
this.serverSocket.setSoTimeout(CONNECT_INTERVAL_TIMEOUT);
this.serverSocket.setReuseAddress(true);
// attempt to receive a connection for a maximum of connectMaxIntervals times
while (true) {
try {
this.clientSocket = this.serverSocket.accept();
} catch (final SocketTimeoutException e) {
// accept timed out as requested - check for thread interruption and abort if present, otherwise retry
if (Thread.interrupted())
throw new InterruptedException();
} catch (final IOException e) {
throw new ConnectIOException(e);
} catch (final SecurityException e) {
throw new ConnectSecurityException(e);
} catch (final IllegalBlockingModeException e) {
throw new LogicError(e);
}
// check if a connection has been established
if (this.clientSocket != null && this.clientSocket.isConnected()) {
// check if the connection originates from the expected peer
if (this.clientSocket.getInetAddress().equals(this.remotePeer.getInetAddress()))
// if so, break the loop -> connection established
break;
// if not, discard the connection and keep going
getLoggerForThisMethod().log(Level.WARNING, "dropped connection from remote host " + this.clientSocket.getInetAddress().toString() + ": host is not the expected peer");
this.clientSocket = null;
}
if (System.currentTimeMillis() - startTime >= CONNECT_TIMEOUT)
throw new ConnectTimeoutException();
}
// if the flow reaches this point, a connection from the correct peer has been accepted
return new Connection(this.clientSocket, this.localPeer, this.remotePeer);
} catch (SocketException e) {
throw new ConnectSocketConfigException(e);
} catch (IOException e) {
throw new ServerFailedToBindException(this.localPeer.getPort(), e);
} catch (SecurityException e) {
throw new ServerFailedToBindException(this.localPeer.getPort(), e);
} finally {
// whatever happened, close the server socket if it exists
if (this.serverSocket != null) {
try {
this.serverSocket.close();
} catch (IOException e) {
throw new ServerFailedToCloseException(e);
}
}
// unless the connection has been established successfully, close the client socket if it exists
if (this.clientSocket != null && !this.clientSocket.isConnected()) {
try {
this.clientSocket.close();
} catch (IOException e) {
throw new ConnectSocketFailedToCloseException(e);
}
}
}
}
}
}
|
gpl-3.0
|
Yarilo/dandelion-platform
|
server/util/mongodb.js
|
14218
|
'use strict';
require('prototypes');
var mongodb = require('mongodb');
var db;
var Users =[];
var Resources =[];
var testing = require('testing');
var async = require('async');
var path = require('path');
exports.init = function(callback)
{
mongodb.connect("mongodb://127.0.0.1:27017/dandelion", function(error, database)
{
if (error)
{
console.log("Could not stablish a connection to MongoDB", error);
return callback;
}
db = database;
Users = db.collection('users');
Users.find({}).toArray(function(error, userArray)
{
if(error)
{
return callback(error);
}
userArray.forEach(function(user)
{
createResourcesUserCollection(user.name);
});
createIndexes(userArray, callback);
});
});
};
function createIndexes(userArray, callback)
{
var tasks = [];
Users.createIndex({name:1},{unique:true}, function(error)
{
if(error)
{
return callback(error);
}
Users.createIndex({email:1},{unique:true}, function(error)
{
if(error)
{
return callback(error);
}
userArray.forEach(function(user)
{
tasks.push(getIndexCreator(user.name));
});
async.series(tasks, callback);
});
});
}
function getIndexCreator(user)
{
return function(callback)
{
Resources[user].createIndex({locations:1},{unique:true, sparse:true}, callback);
};
}
function createResourcesUserCollection(username)
{
var collectionName = 'resources.' + username;
Resources[username] = db.collection(collectionName);
}
//Create the user if not already there
exports.createUser = function(user, callback)
{
Users.insert(user, {safe:true}, function(error)
{
if(error)
{
return callback(error);
}
createResourcesUserCollection(user.name);
return callback(null);
});
};
exports.updateUser = function (query,modifications, callback)
{
Users.update(query,{$set:modifications}, {upsert:true, safe:true}, callback);
};
exports.deleteFields = function (query, fields, callback)
{
Users.update(query,{$unset:fields}, {safe:true}, callback);
};
exports.deleteUser = function(username, callback)
{
Users.remove({name:username}, 1, callback);
};
exports.deleteResourcesUserCollection = function(username, callback)
{
exports.getAllUserResources(username, function(error, results)
{
if(error)
{
return callback(error);
}
if(results.length < 1)
{
return callback(null);
}
Resources[username].drop(callback);
});
};
exports.getUser = function (username, callback)
{
Users.findOne({'$or': [{name:username},{email:username}]}, callback);
};
exports.findUsers = function(query, callback)
{
Users.find(query).toArray(callback);
};
/*
CRUD operations
*/
exports.createResource = function(resource,username, callback)
{
Resources[username].insert(resource, {safe:true}, callback);
};
exports.updateResource = function(resourceId, username, modifications, callback)
{
var newLocations = [];
if(modifications.hasOwnProperty('locations'))
{
newLocations = modifications.locations;
delete modifications.locations;
}
Resources[username].update({_id:mongodb.ObjectID(resourceId)},
{
$set: modifications,
$addToSet: {locations: {$each:newLocations}}
},
{upsert: true, safe:true}, function(error, result)
{
return callback(error, result);
});
};
exports.initialUpdate = function(resourceId,username, modifications, callback)
{
var newLocations = [];
if(modifications.hasOwnProperty('locations'))
{
newLocations = modifications.locations;
delete modifications.locations;
}
Resources[username].update({_id:resourceId},
{
$set: modifications,
$addToSet: {locations: {$each:newLocations}},
},
{upsert: true, safe:true}, callback);
};
exports.getChildren = function(parentId,username, callback)
{
Resources[username].find({parent_id: mongodb.ObjectID(parentId)}).toArray(callback);
};
exports.getAllChildren = function(parentName,username, callback)
{
parentName = parentName + "/";
Resources[username].find({name:{$regex: parentName}}).toArray(callback);
};
exports.getAllUserResources = function(username, callback)
{
Resources[username].find({}).toArray(callback);
};
exports.getResources = function(query, username, callback)
{
Resources[username].find(query).toArray(callback);
};
exports.getAllResources = function (query, callback)
{
var resources = [];
exports.findUsers({}, function(error, userArray)
{
if(error)
{
return callback(error, []);
}
userArray.forEach(function(user)
{
Resources[user.name].find(query).toArray(function(error, result)
{
if(error)
{
return callback(error, null);
}
resources.push(result);
});
});
return callback(null,resources);
});
};
exports.removeResource = function(query, username, callback)
{
Resources[username].findOne(query, function(error, resource)
{
if(error)
{
return callback(error);
}
if (!resource)
{
return callback("Resource with query: %j, not found", query);
}
Resources[username].remove(query, 1, function(error, result)
{
if (error)
{
return callback(error);
}
if (resource.resource_kind === 'directory') //If folder, delete children folders
{
var parentName = path.join(resource.name, "/");
return Resources[username].remove({name:{$regex: parentName}},callback);
}
return callback(null);
});
});
};
exports.can = function(query, username, permissionToCheck, callback)
{
Resources[username].findOne(query,function(error,result)
{
if(error)
{
return callback(error, false);
}
if(!result)
{
return callback(null, false);
}
var itCan = false;
var isOwner = result.owner === username;
var canEdit = result.edit && result.edit.contains(username);
var canView = result.view && result.view.contains(username);
if(permissionToCheck == "view" && (isOwner || canEdit || canView))
{
itCan = true;
}
else if(permissionToCheck == "edit" && (isOwner || canEdit))
{
itCan = true;
}
return callback(null, itCan);
});
};
exports.addPermission = function(resourceId, username, permission, users, callback)
{
var newPerm = {};
newPerm[permission]= {$each: users};
Resources[username].update({_id:mongodb.ObjectID(resourceId)},{$addToSet: newPerm},{safe:true}, callback);
};
exports.deletePermission = function(resourceId, username, permission, users, callback)
{
var newPerm = {};
newPerm[permission] = {$in: users};
Resources[username].update({_id:mongodb.ObjectID(resourceId)},{$pull: newPerm},{safe:true}, callback);
};
exports.addLocations = function(resourceId,username, locationArray, callback)
{
Resources[username].update({_id:mongodb.ObjectID(resourceId)},{$addToSet: {locations: {$each:locationArray}}},{safe:true}, callback);
};
exports.deleteLocations = function(resourceId, username, locationArray, callback)
{
Resources[username].update({_id:mongodb.ObjectID(resourceId)},{$pull: {locations: {$in: locationArray }}},{safe:true}, callback);
};
exports.getResourceId = function(fullPath,username, callback)
{
Resources[username].findOne({locations:fullPath},{_id:true}, function(error, result)
{
if(error)
{
return callback(error,null);
}
if(!result)
{
return callback(null, mongodb.ObjectID());
}
return callback(null,result._id);
});
};
var testId = "55c78e4f8edc26b9c878ab20";
var testUser = "batman";
function testCreateUsers(callback)
{
var batman =
{
name: "batman",
password: "test"
};
var joker =
{
name: "joker",
password: "test"
};
var harley =
{
name: "harley",
password: "test"
};
exports.createUser(batman, function(error)
{
testing.check(error,'Error creating user', callback);
exports.createUser(joker, function(error)
{
testing.check(error,'Error creating user', callback);
exports.createUser(harley, function(error)
{
testing.check(error,'Error creating user', callback);
testing.success(callback);
});
});
});
}
function testCreateResource(callback)
{
var resource =
{
'_id': mongodb.ObjectID(testId),
'name': 'test',
'resource_kind': 'file',
'owner': "batman",
'mtime': Date.now(),
'size': "test",
'parent':"",
'edit':['batman'],
'locations':['sample/location/1','sample/location/2']
};
exports.createResource(resource,testUser, function(error)
{
testing.check(error,'Error creating resource', callback);
testing.success(callback);
});
}
function testUpdateResource(callback)
{
var modifications =
{
'name': 'testmodificado',
'size': "flejote",
};
exports.updateResource(testId,testUser, modifications, function(error)
{
testing.check(error,'Error updating resource', callback);
testing.success(callback);
});
}
function testAddPermission(callback)
{
exports.addPermission(testId,testUser, "edit", ["joker", "harley", "gordon"], function(error, result)
{
testing.check(error, 'Error adding permission resource', callback);
testing.success(callback);
});
}
function testDeletePermission(callback)
{
exports.deletePermission(testId,testUser, "edit", ["harley","gordon"], function(error, result)
{
testing.check(error, 'Error adding permission resource', callback);
testing.success(callback);
});
}
function testAddLocation(callback)
{
exports.addLocations(testId,testUser, ['/another/location/1', '/another/location/2'], function(error, result)
{
testing.check(error, 'Error adding permission resource', callback);
testing.success(callback);
});
}
function testDeleteLocation(callback)
{
exports.deleteLocations(testId,testUser, ['sample/location/1'], function(error, result)
{
testing.check(error, 'Error adding permission resource', callback);
testing.success(callback);
});
}
function testGetResourceId(callback)
{
exports.getResourceId("sample/location/2", testUser, function(error, result)
{
testing.check(error,'Error getting resource ID', callback);
testing.assertEquals(result,testId,'No resources found1', callback);
exports.getResourceId([ 'sample/location/2','/another/location/1','/another/location/2' ],testUser, function(error, result)
{
testing.check(error,'Error getting resource ID', callback);
testing.assertEquals(result,testId,'No resources found2', callback);
//If we pass and array, it must match completely all locations, otherwise should fail.
exports.getResourceId([ 'sample/location/2','/another/location/1'], testUser, function(error, result)
{
testing.check(error,'Error getting resource ID', callback);
testing.assertNotEquals(result,testId,'No resources found3', callback);
testing.success(callback);
});
});
});
}
function testGetUserResources(callback)
{
exports.getAllUserResources(testUser, function(error, result)
{
testing.check(error,'Error getting all resources', callback);
testing.assert(result,'No resources found', callback);
testing.success(callback);
});
}
function testGetAllResources(callback)
{
exports.getAllResources({},function(error, result)
{
testing.check(error,'Error getting all resources', callback);
testing.assert(result,'No resources found', callback);
testing.success(callback);
});
}
function testRemoveResource(callback)
{
exports.removeResource({_id: mongodb.ObjectID(testId)},testUser, function(error, result)
{
testing.check(error, 'Error removing resource', callback);
testing.assertEquals(result, null, 'Should have removed one element', callback);
testing.success(callback);
});
}
function testCan(callback)
{
exports.can({_id:mongodb.ObjectID(testId)},"joker","edit", function(error, result)
{
testing.check(error, 'Error checking can edit', callback);
testing.assertEquals(result,false,"Joker can edit fails",callback);
exports.can({_id:mongodb.ObjectID(testId)},"harley","edit", function(error, result)
{
testing.check(error, 'Error checking can edit', callback);
testing.assertEquals(result,false,"harley can edit fails", callback);
exports.can({_id:mongodb.ObjectID(testId)},"batman","view", function(error, result)
{
testing.check(error, 'Error checking can view', callback);
testing.assertEquals(result,true, "batman can view fails", callback);
exports.can({_id:mongodb.ObjectID(testId)},"harley","view", function(error, result)
{
testing.check(error, 'Error checking can view', callback);
testing.assertEquals(result,false,"harley can view fails", callback);
testing.success(callback);
});
});
});
});
}
function testDeleteUsers(callback)
{
exports.deleteUser("batman", function(error)
{
testing.check(error,'Error deleting user', callback);
exports.deleteUser("joker", function(error)
{
testing.check(error,'Error deleting user', callback);
exports.deleteUser("harley", function(error)
{
testing.check(error,'Error deleting user', callback);
testing.success(callback);
});
});
});
}
function testDeleteResourcesUserCollection(callback)
{
exports.deleteResourcesUserCollection("batman", function(error)
{
testing.check(error,'Error deleting user resources collection', callback);
exports.deleteResourcesUserCollection("joker", function(error)
{
testing.check(error,'Error deleting user resources collection', callback);
exports.deleteResourcesUserCollection("harley", function(error)
{
testing.check(error,'Error deleting user resources collection', callback);
testing.success(callback);
});
});
});
}
exports.test = function(callback)
{
var tests = [
testCreateUsers,
testCreateResource,
testUpdateResource,
testAddPermission,
testDeletePermission,
testAddLocation,
testDeleteLocation,
testGetResourceId,
testGetUserResources,
testGetAllResources,
testCan,
testRemoveResource,
testDeleteUsers,
testDeleteResourcesUserCollection,
];
exports.init(function(error)
{
if(error)
{
return callback(error);
}
testing.run(tests,callback);
});
};
//Execute tests if running directly
if (__filename == process.argv[1])
{
exports.test(function(error)
{
if(error)
{
console.log("Error executing tests", error);
}
else
{
console.log("Database tests OK");
}
});
}
exports.init(function(error)
{
if(error)
{
console.log("Error stablishing connection to database: " + error);
return;
}
console.log("Connection to database stablished");
return;
});
|
gpl-3.0
|
ZephyrRaine/LD39
|
Assets/Scripts/Part.cs
|
378
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum PART_CATEGORY
{
HUMAN,
ANIMAL,
FISH,
TREE,
CACTUS,
OTHER,
PART_COUNT
}
[CreateAssetMenu(fileName = "Part", menuName = "Plant/Part", order = 1)]
public class Part : ScriptableObject
{
public string naming;
public PART_CATEGORY category;
public Sprite sprite;
}
|
gpl-3.0
|
eric-lemesre/OpenConcerto
|
OpenConcerto/src/org/openconcerto/ui/FormLayouter.java
|
8163
|
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.ui;
import org.openconcerto.utils.CollectionUtils;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.Collections;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.CellConstraints.Alignment;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;
/**
* Permet de disposer des champs avec labels en colonnes. Exemple : <img
* src="doc-files/FormLayouter.png"/>.<br/>
*
* Les champs sont placés grace aux add*().
*
* @author ILM Informatique 2 sept. 2004
*/
public class FormLayouter {
// Label, gap, Field, gap
private static final int CELL_WIDTH = 4;
// row, gap
private static final int CELL_HEIGHT = 2;
private static final String BORDER_GAP = "3dlu";
private static final String ROW_GAP = BORDER_GAP;
private static String ROW_HEIGHT;
public static final void setDefaultRowAlign(Alignment align) {
ROW_HEIGHT = align.abbreviation() + ":p";
}
static {
// that way labels are aligned with JTextComponents' content
setDefaultRowAlign(CellConstraints.CENTER);
}
private final Container co;
// le nombre de colonnes
private final int width;
// le nombre de colonnes par défaut
private final int defaultWidth;
// le layout
private final FormLayout layout;
private final CellConstraints constraints;
private Alignment rowAlign;
// les coordonnées de la prochaine cellule
private int x, y;
public FormLayouter(Container co, int width) {
this(co, width, 1);
}
public FormLayouter(Container co, int width, int defaultWidth) {
if (width < 1)
throw new IllegalArgumentException("width must be at least 1 : " + width);
this.x = 0;
this.y = 0;
this.constraints = new CellConstraints();
// i.e. from ROW_HEIGHT
this.rowAlign = CellConstraints.DEFAULT;
this.co = co;
this.width = width;
this.defaultWidth = defaultWidth;
final String colSpec = BORDER_GAP + ", " + CollectionUtils.join(Collections.nCopies(width, "max(25dlu;p), 5dlu, d:g"), ", 5dlu, ") + ", " + BORDER_GAP;
final String rowSpec = BORDER_GAP + ", " + ROW_HEIGHT + ", " + BORDER_GAP;
// tous les fields ont une taille égale
final int[] colGroups = new int[width];
for (int i = 0; i < width; i++) {
colGroups[i] = CELL_WIDTH * (i + 1);
}
this.layout = new FormLayout(colSpec, rowSpec);
this.layout.setColumnGroups(new int[][] { colGroups });
co.setLayout(this.layout);
}
public final void setRowAlign(Alignment rowAlign) {
this.rowAlign = rowAlign;
}
public final Alignment getRowAlign() {
return this.rowAlign;
}
/**
* Ajout un composant sur une ligne avec la description passee en parametre. Si comp est null,
* un titre est créé.
*
* @param desc le label du champ
* @param comp le composant graphique d'edition ou null si titre
* @return the created label.
*/
public JLabel add(String desc, Component comp) {
if (comp != null) {
return this.add(desc, comp, this.defaultWidth);
} else {
this.newLine();
final JLabel lab = new JLabel(desc);
lab.setFont(lab.getFont().deriveFont(Font.BOLD, 15));
this.layout.setRowSpec(this.getY() - 1, new RowSpec("10dlu"));
this.co.add(lab, this.constraints.xyw(this.getLabelX(), this.getY(), this.width * CELL_WIDTH - 1));
this.endLine();
return lab;
}
}
/**
* Ajout un composant sur une ligne Si comp est null, un titre est créé.
*
* @param desc le label du champ.
* @param comp le composant graphique d'edition.
* @param w la largeur, entre 1 et la largeur de ce layout, ou 0 pour toute la largeur.
* @return the created label.
* @throws NullPointerException if comp is <code>null</code>.
* @throws IllegalArgumentException if w is less than 1.
*/
public JLabel add(String desc, Component comp, int w) {
w = this.checkArgs(comp, w);
final int realWidth = this.getRealFieldWidth(w);
// Guillaume : right alignment like the Mac
final JLabel lab = new JLabel(desc);
this.co.add(lab, this.constraints.xy(this.getLabelX(), this.getY(), CellConstraints.RIGHT, this.getRowAlign()));
this.co.add(comp, this.constraints.xyw(this.getFieldX(), this.getY(), realWidth, CellConstraints.DEFAULT, this.getRowAlign()));
this.x += w;
return lab;
}
// assure that comp & w are valid, and do a newLine if necessary
private int checkArgs(Component comp, int w) {
if (comp == null)
throw new NullPointerException();
if (w < 0 || w > this.width)
throw new IllegalArgumentException("w must be between 0 and " + this.width + " but is : " + w);
int res = w == 0 ? w = this.width : w;
if (this.x + res - 1 >= this.width) {
this.newLine();
}
return res;
}
public JPanel addBordered(String desc, Component comp) {
return this.addBordered(desc, comp, this.defaultWidth);
}
public JPanel addBordered(String desc, Component comp, int w) {
w = this.checkArgs(comp, w);
final int realWidth = w * CELL_WIDTH - 1;
JPanel p = new JPanel();
p.setOpaque(false);
p.setLayout(new GridLayout());
p.setBorder(BorderFactory.createTitledBorder(desc));
p.add(comp);
this.co.add(p, this.constraints.xyw(this.getLabelX(), this.getY(), realWidth, CellConstraints.DEFAULT, this.getRowAlign()));
this.x += w;
return p;
}
private final int getRealFieldWidth(int w) {
return (w - 1) * CELL_WIDTH + 1;
}
private final int getY() {
// +1 pour le premier gap, et +1 car formLayout indexé a partir de 1
return this.y * CELL_HEIGHT + 2;
}
private final int getLabelX() {
return this.x * CELL_WIDTH + 2;
}
private final int getFieldX() {
return this.getLabelX() + 2;
}
// next line
public final void newLine() {
// only append => remove the BORDER_GAP
this.layout.removeRow(this.getY() + 1);
this.layout.appendRow(new RowSpec(ROW_GAP));
this.layout.appendRow(new RowSpec(ROW_HEIGHT));
this.layout.appendRow(new RowSpec(BORDER_GAP));
this.y++;
this.x = 0;
}
/** Finit la ligne actuelle */
private void endLine() {
this.x = this.width;
}
public JLabel addRight(String desc, Component comp) {
this.newLine();
this.x = this.width - 1;
final JLabel res = this.add(desc, comp);
this.endLine();
return res;
}
public void add(JButton btn) {
this.addRight("", btn);
}
public final Container getComponent() {
return this.co;
}
public final int getWidth() {
return this.width;
}
}
|
gpl-3.0
|
gammalgris/jmul
|
Utilities/Math/src/jmul/math/notation/comparators/NumberComparatorBase.java
|
2059
|
/*
* SPDX-License-Identifier: GPL-3.0
*
*
* (J)ava (M)iscellaneous (U)tilities (L)ibrary
*
* JMUL is a central repository for utilities which are used in my
* other public and private repositories.
*
* Copyright (C) 2019 Kristian Kutin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* e-mail: kristian.kutin@arcor.de
*/
/*
* This section contains meta informations.
*
* $Id$
*/
package jmul.math.notation.comparators;
import jmul.math.notation.NotationHelper;
import jmul.math.notation.NotationProperties;
/**
* A base implementation of a comparator.
*
* @author Kristian Kutin
*/
abstract class NumberComparatorBase implements NumberComparator {
/**
* The default constructor.
*/
public NumberComparatorBase() {
super();
}
/**
* A comparison according to the specified parameters is made.
*
* @param firstNumber
* the first number as string
* @param secondNumber
* the second number as string
*
* @return <code>true</code> if the statement is true, else <code>false</code>
*/
@Override
public boolean compare(String firstNumber, String secondNumber) {
NotationProperties firstProperties = NotationHelper.checkString(firstNumber);
NotationProperties secondProperties = NotationHelper.checkString(secondNumber);
return compare(firstNumber, firstProperties, secondNumber, secondProperties);
}
}
|
gpl-3.0
|
andry-tino/Rosetta
|
test/renderers/ASTWalker.Renderings.Tests/archetypes/classes/ClassWithMethodExpression.ts
|
1148
|
class MyClass {
public constructor() {
var initVariable1 : string = 'Hello';
}
public Method1() : void {
var initVariable1 : string = 'Hello';
}
Method2() : void {
var initVariable1 : int = 1 + 4;
var initVariable2 : int = 2 * 4 + (3 / 2);
}
private Method3() : void {
var initVariable1 : bool = !false;
var initVariable2 : bool = !true;
}
private Method4() : void {
var initVariable1 : int = 1++;
var initVariable2 : int = ++1;
var initVariable1 : int = 1--;
var initVariable2 : int = --1;
}
private Method5() : void {
var initVariable1 : int = (1);
}
Method6() : void {
var initVariable1 : bool = true == false;
var initVariable2 : bool = true != false;
var initVariable3 : bool = 1 == 2;
var initVariable4 : bool = 1 != 2;
var initVariable5 : bool = 'hello' == 'Hello';
var initVariable6 : bool = 'hello' != 'Hello';
}
private Method7() : void {
var initVariable1 : bool = true;
initVariable1 = false;
var initVariable2 : int = 1;
initVariable2 = 0;
var initVariable3 : string = 'hello';
initVariable3 = 'hello!';
}
}
|
gpl-3.0
|
modsim/CADET-semi-analytic
|
ThirdParty/cppad/cppad/local/sin_op.hpp
|
6581
|
# ifndef CPPAD_LOCAL_SIN_OP_HPP
# define CPPAD_LOCAL_SIN_OP_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
GNU General Public License Version 3.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
namespace CppAD { namespace local { // BEGIN_CPPAD_LOCAL_NAMESPACE
/*!
\file sin_op.hpp
Forward and reverse mode calculations for z = sin(x).
*/
/*!
Compute forward mode Taylor coefficient for result of op = SinOp.
The C++ source code corresponding to this operation is
\verbatim
z = sin(x)
\endverbatim
The auxillary result is
\verbatim
y = cos(x)
\endverbatim
The value of y, and its derivatives, are computed along with the value
and derivatives of z.
\copydetails CppAD::local::forward_unary2_op
*/
template <class Base>
inline void forward_sin_op(
size_t p ,
size_t q ,
size_t i_z ,
size_t i_x ,
size_t cap_order ,
Base* taylor )
{
// check assumptions
CPPAD_ASSERT_UNKNOWN( NumArg(SinOp) == 1 );
CPPAD_ASSERT_UNKNOWN( NumRes(SinOp) == 2 );
CPPAD_ASSERT_UNKNOWN( q < cap_order );
CPPAD_ASSERT_UNKNOWN( p <= q );
// Taylor coefficients corresponding to argument and result
Base* x = taylor + i_x * cap_order;
Base* s = taylor + i_z * cap_order;
Base* c = s - cap_order;
// rest of this routine is identical for the following cases:
// forward_sin_op, forward_cos_op, forward_sinh_op, forward_cosh_op.
// (except that there is a sign difference for the hyperbolic case).
size_t k;
if( p == 0 )
{ s[0] = sin( x[0] );
c[0] = cos( x[0] );
p++;
}
for(size_t j = p; j <= q; j++)
{
s[j] = Base(0.0);
c[j] = Base(0.0);
for(k = 1; k <= j; k++)
{ s[j] += Base(double(k)) * x[k] * c[j-k];
c[j] -= Base(double(k)) * x[k] * s[j-k];
}
s[j] /= Base(double(j));
c[j] /= Base(double(j));
}
}
/*!
Compute forward mode Taylor coefficient for result of op = SinOp.
The C++ source code corresponding to this operation is
\verbatim
z = sin(x)
\endverbatim
The auxillary result is
\verbatim
y = cos(x)
\endverbatim
The value of y, and its derivatives, are computed along with the value
and derivatives of z.
\copydetails CppAD::local::forward_unary2_op_dir
*/
template <class Base>
inline void forward_sin_op_dir(
size_t q ,
size_t r ,
size_t i_z ,
size_t i_x ,
size_t cap_order ,
Base* taylor )
{
// check assumptions
CPPAD_ASSERT_UNKNOWN( NumArg(SinOp) == 1 );
CPPAD_ASSERT_UNKNOWN( NumRes(SinOp) == 2 );
CPPAD_ASSERT_UNKNOWN( 0 < q );
CPPAD_ASSERT_UNKNOWN( q < cap_order );
// Taylor coefficients corresponding to argument and result
size_t num_taylor_per_var = (cap_order-1) * r + 1;
Base* x = taylor + i_x * num_taylor_per_var;
Base* s = taylor + i_z * num_taylor_per_var;
Base* c = s - num_taylor_per_var;
// rest of this routine is identical for the following cases:
// forward_sin_op, forward_cos_op, forward_sinh_op, forward_cosh_op
// (except that there is a sign difference for the hyperbolic case).
size_t m = (q-1) * r + 1;
for(size_t ell = 0; ell < r; ell++)
{ s[m+ell] = Base(double(q)) * x[m + ell] * c[0];
c[m+ell] = - Base(double(q)) * x[m + ell] * s[0];
for(size_t k = 1; k < q; k++)
{ s[m+ell] += Base(double(k)) * x[(k-1)*r+1+ell] * c[(q-k-1)*r+1+ell];
c[m+ell] -= Base(double(k)) * x[(k-1)*r+1+ell] * s[(q-k-1)*r+1+ell];
}
s[m+ell] /= Base(double(q));
c[m+ell] /= Base(double(q));
}
}
/*!
Compute zero order forward mode Taylor coefficient for result of op = SinOp.
The C++ source code corresponding to this operation is
\verbatim
z = sin(x)
\endverbatim
The auxillary result is
\verbatim
y = cos(x)
\endverbatim
The value of y is computed along with the value of z.
\copydetails CppAD::local::forward_unary2_op_0
*/
template <class Base>
inline void forward_sin_op_0(
size_t i_z ,
size_t i_x ,
size_t cap_order ,
Base* taylor )
{
// check assumptions
CPPAD_ASSERT_UNKNOWN( NumArg(SinOp) == 1 );
CPPAD_ASSERT_UNKNOWN( NumRes(SinOp) == 2 );
CPPAD_ASSERT_UNKNOWN( 0 < cap_order );
// Taylor coefficients corresponding to argument and result
Base* x = taylor + i_x * cap_order;
Base* s = taylor + i_z * cap_order; // called z in documentation
Base* c = s - cap_order; // called y in documentation
s[0] = sin( x[0] );
c[0] = cos( x[0] );
}
/*!
Compute reverse mode partial derivatives for result of op = SinOp.
The C++ source code corresponding to this operation is
\verbatim
z = sin(x)
\endverbatim
The auxillary result is
\verbatim
y = cos(x)
\endverbatim
The value of y is computed along with the value of z.
\copydetails CppAD::local::reverse_unary2_op
*/
template <class Base>
inline void reverse_sin_op(
size_t d ,
size_t i_z ,
size_t i_x ,
size_t cap_order ,
const Base* taylor ,
size_t nc_partial ,
Base* partial )
{
// check assumptions
CPPAD_ASSERT_UNKNOWN( NumArg(SinOp) == 1 );
CPPAD_ASSERT_UNKNOWN( NumRes(SinOp) == 2 );
CPPAD_ASSERT_UNKNOWN( d < cap_order );
CPPAD_ASSERT_UNKNOWN( d < nc_partial );
// Taylor coefficients and partials corresponding to argument
const Base* x = taylor + i_x * cap_order;
Base* px = partial + i_x * nc_partial;
// Taylor coefficients and partials corresponding to first result
const Base* s = taylor + i_z * cap_order; // called z in doc
Base* ps = partial + i_z * nc_partial;
// Taylor coefficients and partials corresponding to auxillary result
const Base* c = s - cap_order; // called y in documentation
Base* pc = ps - nc_partial;
// rest of this routine is identical for the following cases:
// reverse_sin_op, reverse_cos_op, reverse_sinh_op, reverse_cosh_op.
size_t j = d;
size_t k;
while(j)
{
ps[j] /= Base(double(j));
pc[j] /= Base(double(j));
for(k = 1; k <= j; k++)
{
px[k] += Base(double(k)) * azmul(ps[j], c[j-k]);
px[k] -= Base(double(k)) * azmul(pc[j], s[j-k]);
ps[j-k] -= Base(double(k)) * azmul(pc[j], x[k]);
pc[j-k] += Base(double(k)) * azmul(ps[j], x[k]);
}
--j;
}
px[0] += azmul(ps[0], c[0]);
px[0] -= azmul(pc[0], s[0]);
}
} } // END_CPPAD_LOCAL_NAMESPACE
# endif
|
gpl-3.0
|
sergioArgerey/alfresco-sane-zonal-ocr
|
sane-zonal-ocr-module-alfresco/src/main/java/au/com/southsky/jfreesane/SaneEnums.java
|
2501
|
package au.com.southsky.jfreesane;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* Utilities for dealing with instances of {@link SaneEnum}.
*
* @author James Ring (sjr@jdns.org)
*/
public final class SaneEnums {
private static Map<Class<?>, Map<Integer, ?>> cachedTypeMaps = Maps.newHashMap();
// no public constructor
private SaneEnums() {
}
@SuppressWarnings("unchecked")
private static synchronized <T extends Enum<T> & SaneEnum> Map<Integer, T> mapForType(
Class<T> enumType) {
if (cachedTypeMaps.containsKey(enumType)) {
return (Map<Integer, T>) cachedTypeMaps.get(enumType);
}
ImmutableMap.Builder<Integer, T> mapBuilder = ImmutableMap.builder();
for (T value : enumType.getEnumConstants()) {
mapBuilder.put(value.getWireValue(), value);
}
Map<Integer, T> result = mapBuilder.build();
cachedTypeMaps.put(enumType, result);
return result;
}
/**
* Returns a set of {@code T} obtained by treating {@code wireValue} as a bit vector whose bits
* represent the wire values of the enum constants of the given {@code enumType}.
*/
public static <T extends Enum<T> & SaneEnum> Set<T> enumSet(Class<T> enumType, int wireValue) {
T[] enumConstants = enumType.getEnumConstants();
List<T> values = Lists.newArrayListWithCapacity(enumConstants.length);
for (T value : enumConstants) {
if ((wireValue & value.getWireValue()) != 0) {
values.add(value);
}
}
return Sets.immutableEnumSet(values);
}
/**
* Returns the result of bitwise-ORing the wire values of the given {@code SaneEnum} set. This
* method does not check to make sure the result is sensible: the caller must ensure that the set
* contains members whose wire values can be ORed together in a logically correct fashion.
*/
public static <T extends SaneEnum> int wireValue(Set<T> values) {
int result = 0;
for (T value : values) {
result |= value.getWireValue();
}
return result;
}
public static <T extends Enum<T> & SaneEnum> T valueOf(Class<T> enumType, int valueType) {
return mapForType(enumType).get(valueType);
}
public static <T extends Enum<T> & SaneEnum> T valueOf(Class<T> enumType, SaneWord value) {
return valueOf(enumType, value.integerValue());
}
}
|
gpl-3.0
|
jesusc/eclectic
|
plugins/org.eclectic.frontend.syntax.mappings.ui/src/org/eclectic/frontend/ui/labeling/MappingsLabelProvider.java
|
731
|
/*
* generated by Xtext
*/
package org.eclectic.frontend.ui.labeling;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.xtext.ui.label.DefaultEObjectLabelProvider;
import com.google.inject.Inject;
/**
* Provides labels for a EObjects.
*
* see http://www.eclipse.org/Xtext/documentation/latest/xtext.html#labelProvider
*/
public class MappingsLabelProvider extends DefaultEObjectLabelProvider {
@Inject
public MappingsLabelProvider(AdapterFactoryLabelProvider delegate) {
super(delegate);
}
/*
//Labels and icons can be computed like this:
String text(MyModel ele) {
return "my "+ele.getName();
}
String image(MyModel ele) {
return "MyModel.gif";
}
*/
}
|
gpl-3.0
|
shamoxiaoniqiu2008/jeecg-framework
|
src/main/java/org/jeecgframework/poi/excel/entity/ExcelCollectionParams.java
|
891
|
package org.jeecgframework.poi.excel.entity;
import java.util.Map;
/**
* Excel 对于的 Collection
*
* @author JueYue
* @date 2013-9-26
* @version 1.0
*/
public class ExcelCollectionParams {
/**
* 集合对应的名称
*/
private String name;
/**
* 实体对象
*/
private Class<?> type;
/**
* 这个list下面的参数集合实体对象
*/
private Map<String, ExcelImportEntity> excelParams;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Class<?> getType() {
return type;
}
public void setType(Class<?> type) {
this.type = type;
}
public Map<String, ExcelImportEntity> getExcelParams() {
return excelParams;
}
public void setExcelParams(Map<String, ExcelImportEntity> excelParams) {
this.excelParams = excelParams;
}
}
|
gpl-3.0
|
mizangl/twitter_puller
|
app/src/main/java/com/mz/twitterpuller/login/LoginActivity.java
|
1269
|
package com.mz.twitterpuller.login;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import com.mz.twitterpuller.R;
import com.mz.twitterpuller.util.BaseActivity;
import javax.inject.Inject;
public class LoginActivity extends BaseActivity {
@Inject LoginPresenter presenter;
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
LoginFragment loginFragment =
(LoginFragment) getSupportFragmentManager().findFragmentById(R.id.container);
if (loginFragment == null) {
loginFragment = LoginFragment.newInstance();
BaseActivity.addFragmentToActivity(getSupportFragmentManager(), loginFragment,
R.id.container);
}
DaggerLoginComponent.builder()
.applicationComponent(getApplicationComponent())
.loginModule(new LoginModule(loginFragment))
.build()
.inject(this);
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
presenter.onActivityResult(requestCode, resultCode, data);
}
}
|
gpl-3.0
|
soultek101/HammerMod
|
hammermod_common/konals/mods/hammermod/lib/Reference.java
|
515
|
package konals.mods.hammermod.lib;
public class Reference {
public static final String MOD_ID = "HammerMod";
public static final String MOD_NAME = "HammerMod";
public static final String VERSION_NUMBER = "1.3";
public static final String DEPENDENCIES = "required-after:Forge@[7.8.0.696,)";
public static final String SERVER_PROXY_CLASS = "konals.mods.hammermod.proxy.CommonProxy";
public static final String CLIENT_PROXY_CLASS = "konals.mods.hammermod.proxy.ClientProxy";
}
|
gpl-3.0
|
s3inlc/hashtopussy
|
src/inc/handlers/HashtypeHandler.class.php
|
891
|
<?php
class HashtypeHandler implements Handler {
public function __construct($hashtypeId = null) {
//we need nothing to load
}
public function handle($action) {
try {
switch ($action) {
case DHashtypeAction::DELETE_HASHTYPE:
HashtypeUtils::deleteHashtype($_POST['type']);
UI::addMessage(UI::SUCCESS, "Hashtype was deleted successfully!");
break;
case DHashtypeAction::ADD_HASHTYPE:
HashtypeUtils::addHashtype($_POST['id'], $_POST['description'], $_POST['isSalted'], $_POST['isSlowHash'], Login::getInstance()->getUser());
UI::addMessage(UI::SUCCESS, "New hashtype created successfully!");
break;
default:
UI::addMessage(UI::ERROR, "Invalid action!");
break;
}
}
catch (HTException $e) {
UI::addMessage(UI::ERROR, $e->getMessage());
}
}
}
|
gpl-3.0
|
haddowg/phproommaster
|
PHPRM_IQWebCls.php
|
2731
|
<?php
namespace haddowg\phproommaster;
/**
* @package PHPRoomMaster
* @author Gregory Haddow
* @copyright Copyright (c) 2014, Gregory Haddow, http://www.greghaddow.co.uk/
* @license http://opensource.org/licenses/gpl-3.0.html The GPL-3 License with additional attribution clause as detailed below.
* @version 0.1
* @link http://www.greghaddow.co.uk/
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program has the following attribution requirement (GPL Section 7):
* - you agree to retain in PHPRoomMaster and any modifications to PHPRoomMaster the copyright, author attribution and
* URL information as provided in this notice and repeated in the licence.txt document provided with this program.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
use COM;
final class PHPRM_IQWebCls{
private static $instance = null;
private static $com;
private static $util;
final public static function getInstance(){
if(null !== self::$instance){
return self::$instance;
}
static::$instance = new PHPRM_IQWebCls();
return self::$instance;
}
protected function __construct()
{
self::$com = new COM("IQWebWiz.IQWebCls") or die('Failed to Initialize IQWebWiz.IQWebCls COM object');
self::$util = new COM("MSScriptControl.ScriptControl");
self::$util->Language = 'VBScript';
self::$util->AllowUI = false;
self::$util->AddCode('
Function getArrayVal(arr, indexX, indexY)
getArrayVal = arr(indexX, indexY)
End Function
');
}
public function GetMessage($mgsID, $numMsgs){
$messages =array();
$message= self::$com->GetMessage($mgsID,$numMsgs);
for ($x=0; $x < count($message); $x++) {
for($y=0;$y < $numMsgs; $y++) {
$messages[] = self::$util->Run('getArrayVal', $message, $x, $y);
}
}
return $messages;
}
private function __clone()
{
}
private function __wakeup()
{
}
}
|
gpl-3.0
|
RailTracker/OpenRA
|
OpenRA.Mods.Common/Activities/Air/ResupplyAircraft.cs
|
1394
|
#region Copyright & License Information
/*
* Copyright 2007-2016 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System.Linq;
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Activities
{
public class ResupplyAircraft : Activity
{
readonly Aircraft aircraft;
public ResupplyAircraft(Actor self)
{
aircraft = self.Trait<Aircraft>();
}
public override Activity Tick(Actor self)
{
var host = aircraft.GetActorBelow();
if (host == null)
return NextActivity;
if (aircraft.IsPlane)
return ActivityUtils.SequenceActivities(
aircraft.GetResupplyActivities(host)
.Append(new CallFunc(() => aircraft.UnReserve()))
.Append(new WaitFor(() => NextActivity != null || Reservable.IsReserved(host)))
.Append(new TakeOff(self))
.Append(NextActivity).ToArray());
// If is helicopter move away as soon as the resupply ends
return ActivityUtils.SequenceActivities(
aircraft.GetResupplyActivities(host).Append(new TakeOff(self)).Append(NextActivity).ToArray());
}
}
}
|
gpl-3.0
|
neutrondave/pico-os
|
docs/html/search/variables_6b.js
|
1343
|
var searchData=
[
['k_5floop_5flist',['k_loop_list',['../group__pico.html#ga1415910309be4683779840db827a8a25',1,'pico.c']]],
['k_5fready_5flist',['k_ready_list',['../group__pico.html#gad75376ff0ad4fa4a60ad59b4955d0f70',1,'k_ready_list(): pico.c'],['../_cortex_m3_2portable_8c.html#a9b27e6fa20d8f0f543dd4a7e02303d8f',1,'k_ready_list(): portable.c'],['../ds_p_i_c_2portable_8c.html#a9b27e6fa20d8f0f543dd4a7e02303d8f',1,'k_ready_list(): portable.c'],['../_p_i_c24e_2portable_8c.html#a9b27e6fa20d8f0f543dd4a7e02303d8f',1,'k_ready_list(): portable.c'],['../_p_i_c32_m_x_2portable_8c.html#a9b27e6fa20d8f0f543dd4a7e02303d8f',1,'k_ready_list(): portable.c']]],
['k_5fthook_5flist',['k_thook_list',['../group__pico.html#ga7c961835da58173c5a40f2dd6df0684b',1,'pico.c']]],
['k_5fwait_5flist',['k_wait_list',['../group__pico.html#ga61a273c37c97c587af5aa7efa1408ffc',1,'k_wait_list(): pico.c'],['../_cortex_m3_2portable_8c.html#a116faf1e128c5c17b83ac525a3aaa21d',1,'k_wait_list(): portable.c'],['../ds_p_i_c_2portable_8c.html#a116faf1e128c5c17b83ac525a3aaa21d',1,'k_wait_list(): portable.c'],['../_p_i_c24e_2portable_8c.html#a116faf1e128c5c17b83ac525a3aaa21d',1,'k_wait_list(): portable.c'],['../_p_i_c32_m_x_2portable_8c.html#a116faf1e128c5c17b83ac525a3aaa21d',1,'k_wait_list(): portable.c']]]
];
|
gpl-3.0
|
nahumrosillo/Torni-Juegos
|
Torni-Juegos/src/app/app.module.ts
|
2920
|
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppRouting } from './app.routing';
import { AppComponent } from './app.component';
import { UserManagerComponent } from './manager/user-manager/user-manager.component';
import { LoginManagerComponent } from './manager/login-manager/login-manager.component';
import { BDService } from './manager/bd.service';
import { UserLoggedService } from './manager/userLogged.service';
import { RegisterUserManagerComponent } from './manager/register-user-manager/register-user-manager.component';
import { NewAdminComponent } from './manager/user-manager/new-admin/new-admin.component';
import { DeleteAdminComponent } from './manager/user-manager/delete-admin/delete-admin.component';
import { NewSponsorComponent } from './manager/user-manager/new-sponsor/new-sponsor.component';
import { DeleteSponsorComponent } from './manager/user-manager/delete-sponsor/delete-sponsor.component';
import { EditProfileComponent } from './manager/user-manager/edit-profile/edit-profile.component';
import { NewGameComponent } from './manager/user-manager/new-game/new-game.component';
import { DeleteGameComponent } from './manager/user-manager/delete-game/delete-game.component';
import { GameManagerComponent } from './manager/game-manager/game-manager.component';
import { GamePanelComponent } from './manager/game-manager/game-panel.component';
import { TournamentManagerComponent } from './manager/tournament-manager/tournament-manager.component';
import { TournamentPanelComponent } from './manager/tournament-manager/tournament-panel.component';
import { NewTournamentComponent } from './manager/tournament-manager/new-tournament/new-tournament.component';
import { MatchManagerComponent } from './manager/match-manager/match-manager.component';
import { MatchPanelComponent } from './manager/match-manager/match-panel.component';
import { ViewRankingComponent } from './manager/tournament-manager/view-ranking/view-ranking.component';
import { MongoAPIService } from './bd/mongoapi.service';
@NgModule({
declarations: [
AppComponent,
UserManagerComponent,
LoginManagerComponent,
RegisterUserManagerComponent,
NewAdminComponent,
DeleteAdminComponent,
NewSponsorComponent,
DeleteSponsorComponent,
EditProfileComponent,
GameManagerComponent,
NewGameComponent,
DeleteGameComponent,
GamePanelComponent,
TournamentManagerComponent,
TournamentPanelComponent,
NewTournamentComponent,
MatchManagerComponent,
MatchPanelComponent,
ViewRankingComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRouting
],
providers: [BDService, UserLoggedService, MongoAPIService],
bootstrap: [AppComponent]
})
export class AppModule { }
|
gpl-3.0
|
Xol/SoHairyItsScary
|
SoHairyItsScary/Assets/Scripts/GameField.cs
|
498
|
using UnityEngine;
// ------------------------------------------------------------------------------
// Represents a 1x1 tile in an GameArea
// ------------------------------------------------------------------------------
public abstract class GameField
{
private bool canBeSteppedOn;
public GameField() {
this.canBeSteppedOn = true;
}
public GameField(bool canBeSteppedOn) {
this.canBeSteppedOn = canBeSteppedOn;
}
public bool CanBeSteppedOn() {
return this.canBeSteppedOn;
}
}
|
gpl-3.0
|
yamstudio/leetcode
|
java/522.longest-uncommon-subsequence-ii.java
|
1624
|
/*
* @lc app=leetcode id=522 lang=java
*
* [522] Longest Uncommon Subsequence II
*
* autogenerated using scripts/convert.py
*/
import java.util.HashSet;
import java.util.Comparator;
import java.util.Arrays;
class Solution {
public int findLUSlength(String[] strs) {
HashSet<String> set = new HashSet<String>();
int i, j;
boolean flag;
String curr;
Arrays.sort(strs, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
int len1 = s1.length(), len2 = s2.length();
if (len1 == len2)
return s1.compareTo(s2);
return len2 - len1;
}
});
for (i = 0; i < strs.length; ++i) {
curr = strs[i];
if (i == strs.length - 1 || ! curr.equals(strs[i + 1])) {
flag = true;
for (String added : set) {
j = 0;
for (char c : added.toCharArray()) {
if (c == curr.charAt(j))
++j;
if (j == curr.length())
break;
}
if (j == curr.length()) {
flag = false;
break;
}
}
if (flag)
return curr.length();
}
set.add(curr);
}
return -1;
}
}
|
gpl-3.0
|
EidrianGM/FromBed2NetPipeLine
|
gff3s_manager.py
|
2550
|
#!bin/usr/python
# -*- coding: utf-8 -*-.
# Adrian Garcia Moreno
import io
import re as re
import os
import subprocess
import sys
def ncbi_formatter(source):
output = subprocess.check_output("grep ^NC "+source+"_raw.gff3 | cut -f1 | sort -u", shell=True)
contigs = output.split("\n")
if contigs[-1] == "":
contigs = contigs[:-1]
ncbicontig_chr_dict = {}
for contig in contigs:
contig_chr = int(contig.split(".")[0].split("_")[1])
if contig_chr == 23:
chro = "chrX"
elif contig_chr == 24:
chro = "chrY"
elif len(str(contig_chr)) > 2:
chro = "chrM"
else:
chro = "chr"+str(contig_chr)
ncbicontig_chr_dict[contig] = chro
original_ncbigff3 = open(source+"_raw.gff3", "r")
new_ncbigff3 = open(source+".gff3", "w")
for line in original_ncbigff3:
tabed_elements = line.split("\t")
if tabed_elements[0] in ncbicontig_chr_dict:
bed_str = ncbicontig_chr_dict[tabed_elements[0]]+"\t"+"\t".join(tabed_elements[1:10])
new_ncbigff3.write(bed_str)
else:
continue
original_ncbigff3.close()
new_ncbigff3.close()
def gff3_download(source):
# https://www.gencodegenes.org/releases/(19,20).html
# ftp://ftp.ncbi.nih.gov/genomes/Homo_sapiens/
if source == "gcode_hg19":
os.system("wget ftp://ftp.sanger.ac.uk/pub/gencode/Gencode_human/release_19/gencode.v19.annotation.gff3.gz")
print "Downloaded, time to gunzip"
os.system("gunzip -c gencode.v19.annotation.gff3.gz > gcode_hg19.gff3")
if source == "gcode_hg20":
os.system("wget ftp://ftp.sanger.ac.uk/pub/gencode/Gencode_human/release_20/gencode.v20.annotation.gff3.gz")
print "Downloaded, time to gunzip"
os.system("gunzip -c gencode.v20.annotation.gff3.gz > gcode_hg20.gff3")
if source == "ncbi_hg19":
os.system("wget ftp://ftp.ncbi.nih.gov/genomes/Homo_sapiens/GRCh37.p13_interim_annotation/interim_GRCh37.p13_top_level_2017-01-13.gff3.gz")
print "Downloaded, time to gunzip"
os.system("gunzip -c interim_GRCh37.p13_top_level_2017-01-13.gff3.gz > ncbi_hg19_raw.gff3")
ncbi_formatter(source)
if source == "ncbi_hg20":
os.system("wget ftp://ftp.ncbi.nih.gov/genomes/Homo_sapiens/GFF/ref_GRCh38.p7_top_level.gff3.gz")
print "Downloaded, time to gunzip"
os.system("gunzip -c ref_GRCh38.p7_top_level.gff3.gz > ncbi_hg20_raw.gff3")
ncbi_formatter(source)
|
gpl-3.0
|
JeanJoskin/Traffique
|
src/settings.py
|
811
|
# Traffique: live visitor statistics on App Engine
# Copyright (C) 2011 Jean Joskin <jeanjoskin.com>
#
# Traffique is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Traffique 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Traffique. If not, see <http://www.gnu.org/licenses/>.
IPINFO_API_KEY = 'd1c6f7f3397da4ec327d192207066ccefcbe05de28e350dd6185828b186fd893'
|
gpl-3.0
|
UpshiftOne/upshift
|
spec/support/helpers/features_helper.rb
|
337
|
# frozen_string_literal: true
# Features helper methods
module FeaturesHelper
# signs in the account
def sign_in_as(account)
visit '/login'
fill_in 'Email', with: account.email
fill_in 'Password', with: account.password
click_on 'Log in'
end
# signs out the account
def sign_out
visit '/logout'
end
end
|
gpl-3.0
|
Atizar/RapidCFD-dev
|
src/OpenFOAM/primitives/SymmTensor/SymmTensorI.H
|
15105
|
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2013 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM 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 General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "Vector.H"
#include "Tensor.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
template<class Cmpt>
__HOST____DEVICE__
inline SymmTensor<Cmpt>::SymmTensor()
{}
template<class Cmpt>
template<class Cmpt2>
__HOST____DEVICE__
inline SymmTensor<Cmpt>::SymmTensor
(
const VectorSpace<SymmTensor<Cmpt2>, Cmpt2, 6>& vs
)
:
VectorSpace<SymmTensor<Cmpt>, Cmpt, 6>(vs)
{}
template<class Cmpt>
__HOST____DEVICE__
inline SymmTensor<Cmpt>::SymmTensor(const SphericalTensor<Cmpt>& st)
{
this->v_[XX] = st.ii(); this->v_[XY] = 0; this->v_[XZ] = 0;
this->v_[YY] = st.ii(); this->v_[YZ] = 0;
this->v_[ZZ] = st.ii();
}
template<class Cmpt>
__HOST____DEVICE__
inline SymmTensor<Cmpt>::SymmTensor
(
const Cmpt txx, const Cmpt txy, const Cmpt txz,
const Cmpt tyy, const Cmpt tyz,
const Cmpt tzz
)
{
this->v_[XX] = txx; this->v_[XY] = txy; this->v_[XZ] = txz;
this->v_[YY] = tyy; this->v_[YZ] = tyz;
this->v_[ZZ] = tzz;
}
template<class Cmpt>
inline SymmTensor<Cmpt>::SymmTensor(Istream& is)
:
VectorSpace<SymmTensor<Cmpt>, Cmpt, 6>(is)
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class Cmpt>
__HOST____DEVICE__
inline const Cmpt& SymmTensor<Cmpt>::xx() const
{
return this->v_[XX];
}
template<class Cmpt>
__HOST____DEVICE__
inline const Cmpt& SymmTensor<Cmpt>::xy() const
{
return this->v_[XY];
}
template<class Cmpt>
__HOST____DEVICE__
inline const Cmpt& SymmTensor<Cmpt>::xz() const
{
return this->v_[XZ];
}
template<class Cmpt>
__HOST____DEVICE__
inline const Cmpt& SymmTensor<Cmpt>::yy() const
{
return this->v_[YY];
}
template<class Cmpt>
__HOST____DEVICE__
inline const Cmpt& SymmTensor<Cmpt>::yz() const
{
return this->v_[YZ];
}
template<class Cmpt>
__HOST____DEVICE__
inline const Cmpt& SymmTensor<Cmpt>::zz() const
{
return this->v_[ZZ];
}
template<class Cmpt>
__HOST____DEVICE__
inline Cmpt& SymmTensor<Cmpt>::xx()
{
return this->v_[XX];
}
template<class Cmpt>
__HOST____DEVICE__
inline Cmpt& SymmTensor<Cmpt>::xy()
{
return this->v_[XY];
}
template<class Cmpt>
__HOST____DEVICE__
inline Cmpt& SymmTensor<Cmpt>::xz()
{
return this->v_[XZ];
}
template<class Cmpt>
__HOST____DEVICE__
inline Cmpt& SymmTensor<Cmpt>::yy()
{
return this->v_[YY];
}
template<class Cmpt>
__HOST____DEVICE__
inline Cmpt& SymmTensor<Cmpt>::yz()
{
return this->v_[YZ];
}
template<class Cmpt>
__HOST____DEVICE__
inline Cmpt& SymmTensor<Cmpt>::zz()
{
return this->v_[ZZ];
}
template<class Cmpt>
__HOST____DEVICE__
inline const SymmTensor<Cmpt>& SymmTensor<Cmpt>::T() const
{
return *this;
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class Cmpt>
__HOST____DEVICE__
inline void SymmTensor<Cmpt>::operator=(const SphericalTensor<Cmpt>& st)
{
this->v_[XX] = st.ii(); this->v_[XY] = 0; this->v_[XZ] = 0;
this->v_[YY] = st.ii(); this->v_[YZ] = 0;
this->v_[ZZ] = st.ii();
}
// * * * * * * * * * * * * * * * Global Operators * * * * * * * * * * * * * //
//- Hodge Dual operator (tensor -> vector)
template<class Cmpt>
__HOST____DEVICE__
inline Vector<Cmpt> operator*(const SymmTensor<Cmpt>& st)
{
return Vector<Cmpt>(st.yz(), -st.xz(), st.xy());
}
//- Inner-product between two symmetric tensors
template<class Cmpt>
__HOST____DEVICE__
inline Tensor<Cmpt>
operator&(const SymmTensor<Cmpt>& st1, const SymmTensor<Cmpt>& st2)
{
return Tensor<Cmpt>
(
st1.xx()*st2.xx() + st1.xy()*st2.xy() + st1.xz()*st2.xz(),
st1.xx()*st2.xy() + st1.xy()*st2.yy() + st1.xz()*st2.yz(),
st1.xx()*st2.xz() + st1.xy()*st2.yz() + st1.xz()*st2.zz(),
st1.xy()*st2.xx() + st1.yy()*st2.xy() + st1.yz()*st2.xz(),
st1.xy()*st2.xy() + st1.yy()*st2.yy() + st1.yz()*st2.yz(),
st1.xy()*st2.xz() + st1.yy()*st2.yz() + st1.yz()*st2.zz(),
st1.xz()*st2.xx() + st1.yz()*st2.xy() + st1.zz()*st2.xz(),
st1.xz()*st2.xy() + st1.yz()*st2.yy() + st1.zz()*st2.yz(),
st1.xz()*st2.xz() + st1.yz()*st2.yz() + st1.zz()*st2.zz()
);
}
//- Double-dot-product between a symmetric tensor and a symmetric tensor
template<class Cmpt>
__HOST____DEVICE__
inline Cmpt
operator&&(const SymmTensor<Cmpt>& st1, const SymmTensor<Cmpt>& st2)
{
return
(
st1.xx()*st2.xx() + 2*st1.xy()*st2.xy() + 2*st1.xz()*st2.xz()
+ st1.yy()*st2.yy() + 2*st1.yz()*st2.yz()
+ st1.zz()*st2.zz()
);
}
//- Inner-product between a symmetric tensor and a vector
template<class Cmpt>
__HOST____DEVICE__
inline Vector<Cmpt>
operator&(const SymmTensor<Cmpt>& st, const Vector<Cmpt>& v)
{
return Vector<Cmpt>
(
st.xx()*v.x() + st.xy()*v.y() + st.xz()*v.z(),
st.xy()*v.x() + st.yy()*v.y() + st.yz()*v.z(),
st.xz()*v.x() + st.yz()*v.y() + st.zz()*v.z()
);
}
//- Inner-product between a vector and a symmetric tensor
template<class Cmpt>
__HOST____DEVICE__
inline Vector<Cmpt>
operator&(const Vector<Cmpt>& v, const SymmTensor<Cmpt>& st)
{
return Vector<Cmpt>
(
v.x()*st.xx() + v.y()*st.xy() + v.z()*st.xz(),
v.x()*st.xy() + v.y()*st.yy() + v.z()*st.yz(),
v.x()*st.xz() + v.y()*st.yz() + v.z()*st.zz()
);
}
template<class Cmpt>
__HOST____DEVICE__
inline Cmpt magSqr(const SymmTensor<Cmpt>& st)
{
return
(
magSqr(st.xx()) + 2*magSqr(st.xy()) + 2*magSqr(st.xz())
+ magSqr(st.yy()) + 2*magSqr(st.yz())
+ magSqr(st.zz())
);
}
//- Return the trace of a symmetric tensor
template<class Cmpt>
__HOST____DEVICE__
inline Cmpt tr(const SymmTensor<Cmpt>& st)
{
return st.xx() + st.yy() + st.zz();
}
//- Return the spherical part of a symmetric tensor
template<class Cmpt>
__HOST____DEVICE__
inline SphericalTensor<Cmpt> sph(const SymmTensor<Cmpt>& st)
{
return (1.0/3.0)*tr(st);
}
//- Return the symmetric part of a symmetric tensor, i.e. itself
template<class Cmpt>
__HOST____DEVICE__
inline const SymmTensor<Cmpt>& symm(const SymmTensor<Cmpt>& st)
{
return st;
}
//- Return twice the symmetric part of a symmetric tensor
template<class Cmpt>
__HOST____DEVICE__
inline SymmTensor<Cmpt> twoSymm(const SymmTensor<Cmpt>& st)
{
return 2*st;
}
//- Return the deviatoric part of a symmetric tensor
template<class Cmpt>
__HOST____DEVICE__
inline SymmTensor<Cmpt> dev(const SymmTensor<Cmpt>& st)
{
return st - SphericalTensor<Cmpt>(1.0/3.0)*tr(st);
}
//- Return the deviatoric part of a symmetric tensor
template<class Cmpt>
__HOST____DEVICE__
inline SymmTensor<Cmpt> dev2(const SymmTensor<Cmpt>& st)
{
return st - SphericalTensor<Cmpt>(2.0/3.0)*tr(st);
}
//- Return the determinant of a symmetric tensor
template<class Cmpt>
__HOST____DEVICE__
inline Cmpt det(const SymmTensor<Cmpt>& st)
{
return
(
st.xx()*st.yy()*st.zz() + st.xy()*st.yz()*st.xz()
+ st.xz()*st.xy()*st.yz() - st.xx()*st.yz()*st.yz()
- st.xy()*st.xy()*st.zz() - st.xz()*st.yy()*st.xz()
);
}
//- Return the cofactor symmetric tensor of a symmetric tensor
template<class Cmpt>
__HOST____DEVICE__
inline SymmTensor<Cmpt> cof(const SymmTensor<Cmpt>& st)
{
return SymmTensor<Cmpt>
(
st.yy()*st.zz() - st.yz()*st.yz(),
st.xz()*st.yz() - st.xy()*st.zz(),
st.xy()*st.yz() - st.xz()*st.yy(),
st.xx()*st.zz() - st.xz()*st.xz(),
st.xy()*st.xz() - st.xx()*st.yz(),
st.xx()*st.yy() - st.xy()*st.xy()
);
}
//- Return the inverse of a symmetric tensor give the determinant
template<class Cmpt>
__HOST____DEVICE__
inline SymmTensor<Cmpt> inv(const SymmTensor<Cmpt>& st, const Cmpt detst)
{
return SymmTensor<Cmpt>
(
st.yy()*st.zz() - st.yz()*st.yz(),
st.xz()*st.yz() - st.xy()*st.zz(),
st.xy()*st.yz() - st.xz()*st.yy(),
st.xx()*st.zz() - st.xz()*st.xz(),
st.xy()*st.xz() - st.xx()*st.yz(),
st.xx()*st.yy() - st.xy()*st.xy()
)/detst;
}
//- Return the inverse of a symmetric tensor
template<class Cmpt>
__HOST____DEVICE__
inline SymmTensor<Cmpt> inv(const SymmTensor<Cmpt>& st)
{
return inv(st, det(st));
}
//- Return the 1st invariant of a symmetric tensor
template<class Cmpt>
__HOST____DEVICE__
inline Cmpt invariantI(const SymmTensor<Cmpt>& st)
{
return tr(st);
}
//- Return the 2nd invariant of a symmetric tensor
template<class Cmpt>
__HOST____DEVICE__
inline Cmpt invariantII(const SymmTensor<Cmpt>& st)
{
return
(
0.5*sqr(tr(st))
- 0.5*
(
st.xx()*st.xx() + st.xy()*st.xy() + st.xz()*st.xz()
+ st.xy()*st.xy() + st.yy()*st.yy() + st.yz()*st.yz()
+ st.xz()*st.xz() + st.yz()*st.yz() + st.zz()*st.zz()
)
);
}
//- Return the 3rd invariant of a symmetric tensor
template<class Cmpt>
__HOST____DEVICE__
inline Cmpt invariantIII(const SymmTensor<Cmpt>& st)
{
return det(st);
}
template<class Cmpt>
__HOST____DEVICE__
inline SymmTensor<Cmpt>
operator+(const SphericalTensor<Cmpt>& spt1, const SymmTensor<Cmpt>& st2)
{
return SymmTensor<Cmpt>
(
spt1.ii() + st2.xx(), st2.xy(), st2.xz(),
spt1.ii() + st2.yy(), st2.yz(),
spt1.ii() + st2.zz()
);
}
template<class Cmpt>
__HOST____DEVICE__
inline SymmTensor<Cmpt>
operator+(const SymmTensor<Cmpt>& st1, const SphericalTensor<Cmpt>& spt2)
{
return SymmTensor<Cmpt>
(
st1.xx() + spt2.ii(), st1.xy(), st1.xz(),
st1.yy() + spt2.ii(), st1.yz(),
st1.zz() + spt2.ii()
);
}
template<class Cmpt>
__HOST____DEVICE__
inline SymmTensor<Cmpt>
operator-(const SphericalTensor<Cmpt>& spt1, const SymmTensor<Cmpt>& st2)
{
return SymmTensor<Cmpt>
(
spt1.ii() - st2.xx(), -st2.xy(), -st2.xz(),
spt1.ii() - st2.yy(), -st2.yz(),
spt1.ii() - st2.zz()
);
}
template<class Cmpt>
__HOST____DEVICE__
inline SymmTensor<Cmpt>
operator-(const SymmTensor<Cmpt>& st1, const SphericalTensor<Cmpt>& spt2)
{
return SymmTensor<Cmpt>
(
st1.xx() - spt2.ii(), st1.xy(), st1.xz(),
st1.yy() - spt2.ii(), st1.yz(),
st1.zz() - spt2.ii()
);
}
//- Inner-product between a spherical symmetric tensor and a symmetric tensor
template<class Cmpt>
__HOST____DEVICE__
inline SymmTensor<Cmpt>
operator&(const SphericalTensor<Cmpt>& spt1, const SymmTensor<Cmpt>& st2)
{
return SymmTensor<Cmpt>
(
spt1.ii()*st2.xx(), spt1.ii()*st2.xy(), spt1.ii()*st2.xz(),
spt1.ii()*st2.yy(), spt1.ii()*st2.yz(),
spt1.ii()*st2.zz()
);
}
//- Inner-product between a tensor and a spherical tensor
template<class Cmpt>
__HOST____DEVICE__
inline SymmTensor<Cmpt>
operator&(const SymmTensor<Cmpt>& st1, const SphericalTensor<Cmpt>& spt2)
{
return SymmTensor<Cmpt>
(
st1.xx()*spt2.ii(), st1.xy()*spt2.ii(), st1.xz()*spt2.ii(),
st1.yy()*spt2.ii(), st1.yz()*spt2.ii(),
st1.zz()*spt2.ii()
);
}
//- Double-dot-product between a spherical tensor and a symmetric tensor
template<class Cmpt>
__HOST____DEVICE__
inline Cmpt
operator&&(const SphericalTensor<Cmpt>& spt1, const SymmTensor<Cmpt>& st2)
{
return(spt1.ii()*st2.xx() + spt1.ii()*st2.yy() + spt1.ii()*st2.zz());
}
//- Double-dot-product between a tensor and a spherical tensor
template<class Cmpt>
__HOST____DEVICE__
inline Cmpt
operator&&(const SymmTensor<Cmpt>& st1, const SphericalTensor<Cmpt>& spt2)
{
return(st1.xx()*spt2.ii() + st1.yy()*spt2.ii() + st1.zz()*spt2.ii());
}
template<class Cmpt>
__HOST____DEVICE__
inline SymmTensor<Cmpt> sqr(const Vector<Cmpt>& v)
{
return SymmTensor<Cmpt>
(
v.x()*v.x(), v.x()*v.y(), v.x()*v.z(),
v.y()*v.y(), v.y()*v.z(),
v.z()*v.z()
);
}
template<class Cmpt>
class outerProduct<SymmTensor<Cmpt>, Cmpt>
{
public:
typedef SymmTensor<Cmpt> type;
};
template<class Cmpt>
class outerProduct<Cmpt, SymmTensor<Cmpt> >
{
public:
typedef SymmTensor<Cmpt> type;
};
template<class Cmpt>
class innerProduct<SymmTensor<Cmpt>, SymmTensor<Cmpt> >
{
public:
typedef Tensor<Cmpt> type;
};
template<class Cmpt>
class innerProduct<SymmTensor<Cmpt>, Vector<Cmpt> >
{
public:
typedef Vector<Cmpt> type;
};
template<class Cmpt>
class innerProduct<Vector<Cmpt>, SymmTensor<Cmpt> >
{
public:
typedef Vector<Cmpt> type;
};
template<class Cmpt>
class typeOfSum<SphericalTensor<Cmpt>, SymmTensor<Cmpt> >
{
public:
typedef SymmTensor<Cmpt> type;
};
template<class Cmpt>
class typeOfSum<SymmTensor<Cmpt>, SphericalTensor<Cmpt> >
{
public:
typedef SymmTensor<Cmpt> type;
};
template<class Cmpt>
class innerProduct<SphericalTensor<Cmpt>, SymmTensor<Cmpt> >
{
public:
typedef SymmTensor<Cmpt> type;
};
template<class Cmpt>
class innerProduct<SymmTensor<Cmpt>, SphericalTensor<Cmpt> >
{
public:
typedef SymmTensor<Cmpt> type;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// ************************************************************************* //
|
gpl-3.0
|
ogata-lab/v_repExtRTC
|
src/SimulatorStub.cpp
|
674
|
// -*- C++ -*-
/*!
*
* THIS FILE IS GENERATED AUTOMATICALLY!! DO NOT EDIT!!
*
* @file SimulatorStub.cpp
* @brief Simulator client stub wrapper code
* @date Thu Sep 11 22:40:04 2014
*
*/
#include "SimulatorStub.h"
#if defined ORB_IS_TAO
# include "SimulatorC.cpp"
#elif defined ORB_IS_OMNIORB
# include "SimulatorSK.cc"
# include "SimulatorDynSK.cc"
#elif defined ORB_IS_MICO
# include "Simulator.cc"
#elif defined ORB_IS_ORBIT2
# include "Simulator-cpp-stubs.cc"
#elif defined ORB_IS_RTORB
# include "OpenRTM-aist-decls.h"
# include "Simulator-common.c"
# include "Simulator-stubs.c"
#else
# error "NO ORB defined"
#endif
// end of SimulatorStub.cpp
|
gpl-3.0
|
luutifa/starfield-demo
|
demo_timing.hpp
|
908
|
// Copyright 2015 Lauri Gustafsson
/*
This file is part of Low Quality is the Future.
Low Quality is the Future is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Low Quality is the Future 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with Low Quality is the Future, see COPYING. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DEMO_CONFIG_HPP
#define DEMO_CONFIG_HPP
extern int const PARTS;
extern float const PART_TIMES[];
#endif
|
gpl-3.0
|
victorfcm/laravel-gitscrum
|
app/Http/Middleware/RedirectIfAuthenticated.php
|
717
|
<?php
/**
* GitScrum v0.1.
*
* @author Renato Marinho <renato.marinho@s2move.com>
* @license http://opensource.org/licenses/GPL-3.0 GPLv3
*/
namespace GitScrum\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
*
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect()->route('user.dashboard');
}
return $next($request);
}
}
|
gpl-3.0
|
fabiencro/knmt
|
nmt_chainer/utilities/extract_processed_data.py
|
1715
|
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import codecs
import gzip
import logging
from nmt_chainer.dataprocessing import processors
logging.basicConfig()
log = logging.getLogger("rnns:utils:extract")
log.setLevel(logging.INFO)
def define_parser(parser):
parser.add_argument("datapath")
parser.add_argument("dest_fn")
def do_extract(args):
datapath, destination_fn = args.datapath, args.dest_fn
voc_fn = datapath + ".voc"
data_fn = datapath + ".data.json.gz"
log.info("extracting data from %s using processor in %s", data_fn, voc_fn)
data = json.load(gzip.open(data_fn, "rb"))
bi_pp = processors.load_pp_pair_from_file(voc_fn)
tgt_processor = bi_pp.tgt_processor()
for key in data:
src_fn = destination_fn + ".%s.src.txt"%key
tgt_fn = destination_fn + ".%s.tgt.txt"%key
tgt_swallow_fn = destination_fn + ".%s.tgt.swallow.txt"%key
log.info("extracting key %s into %s and %s and %s", key, src_fn, tgt_fn, tgt_swallow_fn)
src_f = codecs.open(src_fn, "w", encoding = "utf8")
tgt_f = codecs.open(tgt_fn, "w", encoding = "utf8")
tgt_swallow_f = codecs.open(tgt_swallow_fn, "w", encoding = "utf8")
for src, tgt in data[key]:
src_dec, tgt_dec = bi_pp.deconvert(src, tgt)
src_f.write(src_dec + "\n")
tgt_f.write(tgt_dec + "\n")
tgt_swallow = tgt_processor.deconvert_swallow(tgt)
tgt_swallow_string = " ".join(("[@%i]"%w if isinstance(w, int) else w) for w in tgt_swallow)
tgt_swallow_f.write(tgt_swallow_string + "\n")
|
gpl-3.0
|
Spoken-tutorial/spoken-website
|
youtube/backup/models.py
|
304
|
# Third Party Stuff
from django.contrib.auth.models import User
from django.db import models
from oauth2client.django_orm import CredentialsField
class CredentialsModel(models.Model):
id = models.OneToOneField(User, primary_key=True, on_delete=models.PROTECT )
credential = CredentialsField()
|
gpl-3.0
|
BetaCONCEPT/astroboa
|
astroboa-portal-commons/src/main/java/org/betaconceptframework/astroboa/portal/managedbean/PortalResourceLoader.java
|
2560
|
/*
* Copyright (C) 2005-2012 BetaCONCEPT Limited
*
* This file is part of Astroboa.
*
* Astroboa 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 3 of the License, or
* (at your option) any later version.
*
* Astroboa 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 Astroboa. If not, see <http://www.gnu.org/licenses/>.
*/
package org.betaconceptframework.astroboa.portal.managedbean;
import java.util.ResourceBundle;
import org.betaconceptframework.astroboa.portal.utility.PortalStringConstants;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Install;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.core.ResourceLoader;
/**
*
* Astroboa Resource Loader.
*
* <p>
* This loader overrides Seam Resource Loader and is responsible to instantiate
* {@link RepositoryResourceBundle} which loads resource bundles
* saved in appropriate taxonomies. For more info see at {@link RepositoryResourceBundle}.
* </p>
*
* <p>
* In order to activate {@link RepositoryResourceBundle}, you need to define
* bundle name {@link PortalStringConstants#REPOSITORY_RESOURCE_BUNDLE_NAME} inside components.xml
*
* <pre>
* <core:resource-loader>
* <core:bundle-names>
* <value>portal-commons-messages</value>
* <value>messages</value>
* <value>{@link PortalStringConstants#REPOSITORY_RESOURCE_BUNDLE_NAME}</value>
* </core:bundle-names>
* </core:resource-loader>
* </pre>
* </p>
* @author Gregory Chomatas (gchomatas@betaconcept.com)
* @author Savvas Triantafyllou (striantafyllou@betaconcept.com)
*
*/
@Scope(ScopeType.STATELESS)
@Install(precedence = Install.APPLICATION)
@Name("org.jboss.seam.core.resourceLoader")
public class PortalResourceLoader extends ResourceLoader{
@Override
public ResourceBundle loadBundle(String bundleName) {
if (bundleName != null && PortalStringConstants.REPOSITORY_RESOURCE_BUNDLE_NAME.equals(bundleName)){
return RepositoryResourceBundle.instance();
}
return super.loadBundle(bundleName);
}
}
|
gpl-3.0
|
ferdavid1/Tequila-Mockingbird
|
fft_notes.py
|
1326
|
import numpy as np
import scipy.io.wavfile as wave
import matplotlib.pyplot as plt
from wave import Wave_read
from math import log2, pow
from scipy.signal import find_peaks_cwt as peaks
from scipy.optimize import leastsq
import numpy as np
A4 = 440
C0 = A4*pow(2, -4.75)
name = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
def pitch(freq):
h = round(12*log2(freq/C0))
octave = h // 12
n = h % 12
return name[n] + str(octave)
def extract(filename):
sample_rate, wav_file = wave.read(filename, 'r')
N = len(wav_file)
x = np.array(wav_file)
w = np.fft.rfft(x)
w = np.abs(w)
w = [(x[0]) for x in w]
cutoff_idx = np.where(w < (np.max(w)/5)) [0]
cutoff_idx = list(cutoff_idx)
w2 = np.array(w.copy())
w2[cutoff_idx] = 0
ax = plt.subplot(2,1,1)
ax.set_title('Original melody')
plt.plot(w)
ax2 = plt.subplot(2,1,2)
plt.plot(w2)
ax2.set_title('Cleaned up')
plt.show()
freqs = np.fft.fftfreq(len(w2))
fpeaks = peaks(w, np.arange(9000,24000,1000), noise_perc=0.1)
id_freq = [freqs[x] for x in fpeaks]
id_hz = [abs(x * sample_rate) for x in id_freq]
notes = list(map(pitch, id_hz))
print('Notes identified: ', notes)
return notes
def Q():
pass
|
gpl-3.0
|
eljost/pysisyphus
|
pysisyphus/irc/LQA.py
|
1841
|
# [1] https://aip.scitation.org/doi/pdf/10.1063/1.459634?class=pdf
# Page, 1990, Eq. 19 is missing a **2 after g'_0,i
# [2] https://aip.scitation.org/doi/10.1063/1.1724823
# Hratchian, 2004
import numpy as np
from pysisyphus.optimizers.hessian_updates import bfgs_update
from pysisyphus.irc.IRC import IRC
class LQA(IRC):
def __init__(self, geometry, N_euler=5000, **kwargs):
super().__init__(geometry, **kwargs)
self.N_euler = N_euler
def step(self):
mw_gradient = self.mw_gradient
if len(self.irc_mw_gradients) > 1:
dg = self.irc_mw_gradients[-1] - self.irc_mw_gradients[-2]
dx = self.irc_mw_coords[-1] - self.irc_mw_coords[-2]
dH, _ = bfgs_update(self.mw_hessian, dx, dg)
self.mw_hessian += dH
eigenvalues, eigenvectors = np.linalg.eigh(self.mw_hessian)
# Drop small eigenvalues and corresponding eigenvectors
small_vals = np.abs(eigenvalues) < 1e-8
eigenvalues = eigenvalues[~small_vals]
eigenvectors = eigenvectors[:,~small_vals]
# t step for numerical integration
dt = 1 / self.N_euler * self.step_length / np.linalg.norm(mw_gradient)
# Transform gradient to eigensystem of the hessian
mw_gradient_trans = eigenvectors.T @ mw_gradient
t = dt
cur_length = 0
for i in range(self.N_euler):
dsdt = np.sqrt(np.sum(mw_gradient_trans**2 * np.exp(-2*eigenvalues*t)))
cur_length += dsdt * dt
if cur_length > self.step_length:
break
t += dt
alphas = (np.exp(-eigenvalues*t) - 1) / eigenvalues
A = eigenvectors @ np.diag(alphas) @ eigenvectors.T
step = A @ mw_gradient
mw_coords = self.mw_coords.copy()
self.mw_coords = mw_coords + step
|
gpl-3.0
|
marcelohama/mp-ofertas
|
MPOfertas/app/src/main/java/com/mercadopago/mpofertas/utils/SimpleCrypto.java
|
2784
|
package com.mercadopago.mpofertas.utils;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* Usage:
*
* <pre>
* String crypto = SimpleCrypto.encrypt(masterpassword, cleartext)
* ...
* String cleartext = SimpleCrypto.decrypt(masterpassword, crypto)
* </pre>
*
* @author ferenc.hechler
*/
public class SimpleCrypto {
public static String encrypt(String seed, String cleartext) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(String seed, String encrypted) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
}
|
gpl-3.0
|
beone/JRUN
|
RunJS/src/net/oschina/runjs/action/ProjectAction.java
|
23707
|
package net.oschina.runjs.action;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import net.oschina.common.servlet.Annotation.JSONOutputEnabled;
import net.oschina.common.servlet.Annotation.PostMethod;
import net.oschina.common.servlet.Annotation.UserRoleRequired;
import net.oschina.common.servlet.RequestContext;
import net.oschina.common.utils.FormatTool;
import net.oschina.common.utils.ImageCaptchaService;
import net.oschina.common.utils.ResourceUtils;
import net.oschina.runjs.beans.Code;
import net.oschina.runjs.beans.Comment;
import net.oschina.runjs.beans.Dynamic;
import net.oschina.runjs.beans.Favor;
import net.oschina.runjs.beans.Msg;
import net.oschina.runjs.beans.Plugin;
import net.oschina.runjs.beans.Project;
import net.oschina.runjs.beans.SquareCode;
import net.oschina.runjs.beans.User;
import net.oschina.runjs.beans.Vote;
import org.apache.commons.lang.StringUtils;
import com.google.gson.Gson;
/**
* 项目管理,包括新建、删除、更新、fork等操作
*
* @author jack
*
*/
public class ProjectAction {
private Gson gson = new Gson();
/**
* 新增一个项目
*
* @param ctx
* @throws IOException
*/
@PostMethod
@UserRoleRequired
@JSONOutputEnabled
public void add(RequestContext ctx) throws IOException {
User user = (User) ctx.user();
String verify_code = ctx.param("v_code", "");
if (!user.IsCurrentUser(verify_code))
throw ctx.error("operation_forbidden");
String pro_name = ctx.param("pro_name", "").trim();
String html = ctx.param("html", "");
String css = ctx.param("css", "");
String js = ctx.param("js", "");
if (pro_name.length() < 1 || pro_name.length() > 20)
throw ctx.error("pro_name_invalid");
// 判断该用户是否已经存在该项目,项目名不能重名。
if (Project.isProjectExist(pro_name, user.getId()))
throw ctx.error("pro_exist");
Project p = new Project();
Timestamp time = new Timestamp(new Date().getTime());
p.setName(pro_name);
p.setUser(user.getId());
p.setVersion(Project.INIT_VERSION);
p.setCreate_time(time);
p.setUpdate_time(time);
// 保存代码
Code code = new Code();
code.setUser(user.getId());
code.setProject(p.Save());
code.setName(p.getName());
code.setCss(css);
code.setHtml(html);
code.setJs(js);
code.setNum(Project.INIT_VERSION);
code.setCreate_time(time);
code.setUpdate_time(time);
code.setCode_type(Code.DEFAULT_TYPE);
if (0 < code.Save()) {
ctx.print(gson.toJson(code));
// 清除用户项目列表的缓存
Project.evictCache(p.CacheRegion(),
Project.USER_PRO_LIST + user.getId());
} else {
p.Delete();
throw ctx.error("operation_failed");
}
}
/**
* 删除项目,将会删除该项目的所有代码以及代码的所有评论
*
* @param ctx
* @throws IOException
*/
@PostMethod
@UserRoleRequired
@JSONOutputEnabled
public void delete_project(RequestContext ctx) throws IOException {
if (!ImageCaptchaService.validate(ctx.request())) {
throw ctx.error("captcha_error");
}
long id = ctx.id();
User user = (User) ctx.user();
String verify_code = ctx.param("v_code", "");
if (!user.IsCurrentUser(verify_code))
throw ctx.error("operation_forbidden");
// 权限检查
Project project = Project.INSTANCE.Get(id);
if (null == project)
throw ctx.error("project_not_exist");
if (null == user || (!user.IsAdmin(project)))
throw ctx.error("operation_forbidden");
// 循环删除代码
List<Code> code_list = Code.INSTANCE.getAllCodeByProject(id);
if (null != code_list)
for (Code code : code_list) {
// 循环删除评论
List<Comment> comment_list = Comment.INSTANCE
.getAllCommentByCode(code.getId());
if (null != comment_list) {
for (Comment comment : comment_list) {
comment.Delete();
}
}
if (code.Delete()) {
SquareCode sc = SquareCode.INSTANCE
.GetSquareCodeByCode(code.getId());
if (sc != null)
sc.Delete();
Plugin plugin = Plugin.INSTANCE.GetPluginByCode(code
.getId());
if (plugin != null)
plugin.Delete();
}
}
if (project.Delete()) {
// 清除用户项目列表的缓存
Project.evictCache(project.CacheRegion(), Project.USER_PRO_LIST
+ user.getId());
ctx.print(gson.toJson(project));
ImageCaptchaService.clear(ctx.request());
} else
throw ctx.error("operation_failed");
}
/**
* 删除指定的代码
*
* @param ctx
* @throws IOException
*/
@PostMethod
@UserRoleRequired
@JSONOutputEnabled
public void delete_version(RequestContext ctx) throws IOException {
if (!ImageCaptchaService.validate(ctx.request())) {
throw ctx.error("captcha_error");
}
User user = (User) ctx.user();
String verify_code = ctx.param("v_code", "");
if (!user.IsCurrentUser(verify_code))
throw ctx.error("operation_forbidden");
long pro_id = ctx.param("pro_id", 0l);
int version = ctx.param("ver", 0);
String sign = ctx.param("sign", "");
// 是否强制保存 0为不强制删除,1为强制删除
int force = ctx.param("force", 0);
Project pro = Project.INSTANCE.Get(pro_id);
if (null == pro)
throw ctx.error("project_not_exist");
// 权限检查
if (null == user || (!user.IsAdmin(pro)))
throw ctx.error("operation_forbidden");
Code code = Code.INSTANCE.getCodeByVersion(pro.getId(), version);
if (null == code)
throw ctx.error("code_not_exist");
// 验证签名
if (0 == force && !code.verifySign(sign))
throw ctx.error("code_is_old");
// 循环删除评论
List<Comment> comment_list = Comment.INSTANCE.getAllCommentByCode(code
.getId());
if (null != comment_list) {
for (Comment comment : comment_list) {
comment.Delete();
}
}
if (code.Delete()) {
ctx.print(gson.toJson(code));
ImageCaptchaService.clear(ctx.request());
} else
throw ctx.error("operation_failed");
}
/**
* 更新最新的版本的代码
*
* @param ctx
* @throws IOException
*/
@PostMethod
@UserRoleRequired
@JSONOutputEnabled
public void update(RequestContext ctx) throws IOException {
User user = (User) ctx.user();
String verify_code = ctx.param("v_code", "");
if (!user.IsCurrentUser(verify_code))
throw ctx.error("operation_forbidden");
Timestamp time = new Timestamp(new Date().getTime());
String sign = ctx.param("sign", "");
// 是否强制保存 0为不强制保存,1为强制保存
int force = ctx.param("force", 0);
long id = ctx.id();
String css = ctx.param("css");
String js = ctx.param("js");
String html = ctx.param("html");
Code code = Code.INSTANCE.Get(id);
if (code == null)
throw ctx.error("code_not_exist");
// 验证上次更新时间,如果是2秒以内,拒绝掉
if (Code.MIN_UPDATE_TIME >= (time.getTime() - code.getUpdate_time()
.getTime()))
throw ctx.error("update_too_fast");
// 验证签名
// 如果签名不对范围错误码为2的错误提示
if (0 == force && !code.verifySign(sign)) {
String[] keys = { "error", "msg" };
Object[] values = { 2,
ResourceUtils.getString("error", "code_is_old") };
ctx.output_json(keys, values);
return;
}
// 如果css、js、html不为null则更新,否则保留原来的版本
if (null != css)
code.setCss(css);
if (null != html)
code.setHtml(html);
if (null != js)
code.setJs(js);
// 更新时间
code.setUpdate_time(time);
if (code.update()) {
ctx.print(gson.toJson(code));
} else
throw ctx.error("operation_failed");
}
/**
* 项目重命名
*
* @param ctx
* @throws IOException
*/
@PostMethod
@UserRoleRequired
@JSONOutputEnabled
public void rename(RequestContext ctx) throws IOException {
User user = (User) ctx.user();
String verify_code = ctx.param("v_code", "");
if (!user.IsCurrentUser(verify_code))
throw ctx.error("operation_forbidden");
String pro_name = ctx.param("name", "").trim();
long pro_id = ctx.param("pro_id", 0l);
Timestamp time = new Timestamp(new Date().getTime());
if (StringUtils.isBlank(pro_name) || pro_name.length() > 30)
throw ctx.error("pro_name_invalid");
Project pro = Project.INSTANCE.Get(pro_id);
if (null == pro)
throw ctx.error("project_not_exist");
// 权限检查
if (null == user || (!user.IsAdmin(pro)))
throw ctx.error("operation_forbidden");
// 判断是否已经存在这样的项目名
if (!StringUtils.equalsIgnoreCase(pro_name, pro.getName())
&& Project.isProjectExist(pro_name, user.getId()))
throw ctx.error("pro_exist");
if (pro.UpdateField("name", pro_name)) {
pro.UpdateField("update_time", time);
ctx.print(gson.toJson(pro));
} else
throw ctx.error("operation_failed");
}
/**
* 代码重命名
*
* @param ctx
* @throws IOException
*/
@PostMethod
@UserRoleRequired
@JSONOutputEnabled
public void rename_code(RequestContext ctx) throws IOException {
User user = (User) ctx.user();
String verify_code = ctx.param("v_code", "");
if (!user.IsCurrentUser(verify_code))
throw ctx.error("operation_forbidden");
String code_name = ctx.param("name", "").trim();
if (StringUtils.isBlank(code_name) || code_name.length() > 20)
throw ctx.error("code_name_invalid");
long code_id = ctx.param("code_id", 0l);
Timestamp time = new Timestamp(new Date().getTime());
Code code = Code.INSTANCE.Get(code_id);
if (null == code)
throw ctx.error("code_not_exist");
if (null == user || (!user.IsAdmin(code)))
throw ctx.error("operation_forbidden");
if (code.UpdateField("name", code_name)) {
code.UpdateField("update_time", time);
Code.evictCache(code.CacheRegion(),
Code.CODE_IDENT + code.getIdent());
code.setName(code_name);
ctx.print(gson.toJson(code));
} else
throw ctx.error("operation_failed");
}
/**
* 修改代码信息
*
* @param ctx
* @throws IOException
*/
@PostMethod
@UserRoleRequired
@JSONOutputEnabled
public void update_info(RequestContext ctx) throws IOException {
User user = (User) ctx.user();
String verify_code = ctx.param("v_code", "");
if (!user.IsCurrentUser(verify_code))
throw ctx.error("operation_forbidden");
long id = ctx.param("id", 0l);
Code code = Code.INSTANCE.Get(id);
if (null == code)
throw ctx.error("code_not_exist");
// 权限检查
if (null == user || (!user.IsAdmin(code)))
throw ctx.error("operation_forbidden");
String code_name = ctx.param("name", "").trim();
String description = ctx.param("description", "").trim();
if (StringUtils.isBlank(code_name) || code_name.length() > 30)
throw ctx.error("code_name_invalid");
if (StringUtils.isBlank(description) || description.length() > 300)
throw ctx.error("description_error");
boolean su = false;
// 如果名称有改变
if (!code_name.equals(code.getName())) {
su = code.UpdateField("name", code_name);
code.setName(code_name);
// 清除ident的缓存
Code.evictCache(code.CacheRegion(),
Code.CODE_IDENT + code.getIdent());
}
// 如果描述有改变
if (!description.equals(code.getDescription())) {
su = code.UpdateField("description", description);
Timestamp time = new Timestamp(new Date().getTime());
code.UpdateField("update_time", time);
code.setDescription(description);
if (code.IsPosted())
Favor.INSTANCE.notifyAllFavors(id);
// 清除ident的缓存
Code.evictCache(code.CacheRegion(),
Code.CODE_IDENT + code.getIdent());
}
// 如果操作成功
if (su)
ctx.print(gson.toJson(code));
else
throw ctx.error("operation_failed");
}
/**
* 存为新版本
*
* @param ctx
* @throws IOException
*/
@PostMethod
@UserRoleRequired
@JSONOutputEnabled
public void new_version(RequestContext ctx) throws IOException {
User user = (User) ctx.user();
String verify_code = ctx.param("v_code", "");
if (!user.IsCurrentUser(verify_code))
throw ctx.error("operation_forbidden");
long id = ctx.id();
String css = ctx.param("css");
String js = ctx.param("js");
String html = ctx.param("html");
Code old_code = Code.INSTANCE.Get(id);
if (null == old_code)
throw ctx.error("code_not_exist");
Project pro = Project.INSTANCE.Get(old_code.getProject());
if (null == pro)
throw ctx.error("project_not_exist");
// 权限检查
if (null == user || (!user.IsAdmin(old_code)))
throw ctx.error("operation_forbidden");
Timestamp time = new Timestamp(new Date().getTime());
// 验证上次创建新版本时间
if (Code.MIN_NEW_VER_TIME >= (time.getTime() - old_code
.getAllCodeByProject(pro.getId()).get(0).getCreate_time()
.getTime()))
throw ctx.error("new_version_too_fast");
// 保存代码
Code code = new Code();
code.setUser(user.getId());
code.setProject(pro.getId());
// 判断是否有提交css、html、js,如果有则更新,否则保留原来的版本。
if (null != css)
code.setCss(css);
else
code.setCss(old_code.getCss());
if (null != html)
code.setHtml(html);
else
code.setHtml(old_code.getHtml());
if (null != js)
code.setJs(js);
else
code.setJs(old_code.getJs());
// 版本号加1
code.setNum(pro.getVersion() + 1);
code.setCreate_time(time);
code.setUpdate_time(time);
// 将其fork字段设置过来
code.setFork(old_code.getFork());
if (code.getFork() != 0) {
Code fork_code = Code.INSTANCE.Get(code.getFork());
Project fork_pro = Project.INSTANCE.Get(fork_code.getProject());
// Fork后默认为发布状态
code.setStatus(Code.STATUS_POST);
code.setPost_time(time);
code.setDescription(ResourceUtils.getString("description",
"fork_code_v", fork_pro.getName()));
}
if (0 != code.Save()) {
pro.UpdateField("version", pro.getVersion() + 1);
pro.UpdateField("update_time", time);
// 清除项目版本列表缓存
Code.evictCache(code.CacheRegion(),
Code.PRO_CODE_LIST + pro.getId());
// 清除fork列表缓存
Code.evictCache(code.CacheRegion(), Code.FORK_LIST + code.getFork());
ctx.print(gson.toJson(code));
return;
} else
throw ctx.error("operation_failed");
}
/**
* 从某一指定项目的指定版本fork
*
* @param ctx
* @throws IOException
*/
@PostMethod
@UserRoleRequired
@JSONOutputEnabled
public void fork(RequestContext ctx) throws IOException {
User user = (User) ctx.user();
String verify_code = ctx.param("v_code", "");
if (!user.IsCurrentUser(verify_code))
throw ctx.error("operation_forbidden");
long fork_pro_id = ctx.param("pro_id", 0l);
int fork_version = ctx.param("ver", 0);
String pro_name = ctx.param("pro_name", "").trim();
// 判断项目名是否合法
if (StringUtils.isBlank(pro_name))
throw ctx.error("pro_name_invalid");
// 判断该用户是否已经存在该项目
if (Project.isProjectExist(pro_name, user.getId()))
throw ctx.error("pro_exist");
Code fork_code = Code.INSTANCE.getCodeByVersion(fork_pro_id,
fork_version);
if (null == fork_code)
throw ctx.error("code_not_exist");
Project fork_pro = Project.INSTANCE.Get(fork_code.getProject());
Project p = new Project();
p.setName(pro_name);
p.setUser(user.getId());
p.setVersion(Project.INIT_VERSION);
Timestamp time = new Timestamp(new Date().getTime());
p.setCreate_time(time);
p.setUpdate_time(time);
// 克隆代码
Code code = new Code();
code.setFork(fork_code.getId());
code.setUser(user.getId());
if (0 != p.Save()) {
// 清除用户项目列表的缓存
Project.evictCache(p.CacheRegion(),
Project.USER_PRO_LIST + user.getId());
// 清除fork列表缓存
Code.evictCache(code.CacheRegion(), Code.FORK_LIST + code.getFork());
// Fork别人的代码默认是发布状态
// 自己的代码默认不发布,用户可以自行选择
if (code.getUser() != fork_code.getUser()) {
code.setStatus(Code.STATUS_POST);
code.setPost_time(time);
code.setDescription(ResourceUtils.getString("description",
"fork_code", fork_pro.getName()));
}
code.setProject(p.getId());
code.setCss(fork_code.getCss());
code.setHtml(fork_code.getHtml());
code.setJs(fork_code.getJs());
code.setNum(Project.INIT_VERSION);
code.setCreate_time(time);
code.setUpdate_time(time);
code.setCode_type(fork_code.getCode_type());
if (0 != code.Save()) {
// 添加动态
Dynamic.INSTANCE.add_fork_dy(code);
if (fork_code.getUser() != code.getUser()) {
// 添加通知
String notify = ResourceUtils.getString("description",
"fork_notify", user.getName(),
fork_code.getIdent(), fork_code.getName(),
code.getIdent());
Msg.INSTANCE.addMsg(code.getUser(), fork_code.getUser(),
Msg.TYPE_FORK, fork_code.getId(), notify);
}
// 清除被fork的代码的缓存列表
Project.evictCache(p.CacheRegion(), Project.FORK_PROJECTS
+ code.getFork());
Code.evictCache(code.CacheRegion(),
Code.FORK_COUNT + fork_code.getId());
ctx.print(gson.toJson(code));
return;
} else
throw ctx.error("operation_failed");
} else
throw ctx.error("operation_failed");
}
/**
* 添加评论
*
* @param ctx
*/
@PostMethod
@UserRoleRequired
@JSONOutputEnabled
public void add_comment(RequestContext ctx) throws IOException {
long id = ctx.id();
User user = (User) ctx.user();
String verify_code = ctx.param("v_code", "");
if (!user.IsCurrentUser(verify_code))
throw ctx.error("operation_forbidden");
String content = ctx.param("content", "").trim();
if (StringUtils.isBlank(content) || 200 < content.length())
throw ctx.error("comment_length", 200);
Code code = Code.INSTANCE.Get(id);
if (null == code)
throw ctx.error("code_not_exist");
// 如果代码未发布,提示操作失败
if (!code.IsPosted())
throw ctx.error("not_publish");
Comment comment = new Comment();
comment.setUser(user.getId());
comment.setCode(id);
comment.setContent(FormatTool.text(content));
comment.setCreate_time(new Timestamp(new Date().getTime()));
if (0 < comment.Save()) {
// 添加一条动态
Dynamic.INSTANCE.add_comment_dy(comment);
if (comment.getUser() != code.getUser()) {
// TODO 添加通知
String notify = ResourceUtils.getString("description",
"comment_notify", user.getName(), code.getIdent(),
code.getName(), code.getIdent());
Msg.INSTANCE.addMsg(comment.getUser(), code.getUser(),
Msg.TYPE_COMMENT, code.getId(), notify);
}
// 清除代码评论缓存列表
Comment.evictCache(comment.CacheRegion(), Comment.COMMENT_LIST
+ comment.getCode());
ctx.print(gson.toJson(comment));
return;
} else
throw ctx.error("operation_failed");
}
/**
* 删除评论
*
* @param ctx
* @throws IOException
*/
@PostMethod
@UserRoleRequired
@JSONOutputEnabled
public void delete_comment(RequestContext ctx) throws IOException {
long id = ctx.id();
User user = (User) ctx.user();
String verify_code = ctx.param("v_code", "");
if (!user.IsCurrentUser(verify_code))
throw ctx.error("operation_forbidden");
// 检查权限
Comment co = Comment.INSTANCE.Get(id);
if (null == co)
throw ctx.error("comment_not_exist");
// 权限检查
if (null == user || (!user.IsAdmin(co)))
throw ctx.error("operation_forbidden");
if (co.Delete()) {
// 清除代码评论缓存列表
Comment.evictCache(co.CacheRegion(),
Comment.COMMENT_LIST + co.getCode());
ctx.print(gson.toJson(co));
return;
} else
throw ctx.error("operation_failed");
}
/**
* 投票,type为投票类型,1顶,-1踩,以后可以有分值
*
* @param ctx
* @throws IOException
*/
@PostMethod
@UserRoleRequired
@JSONOutputEnabled
public void vote(RequestContext ctx) throws IOException {
User user = (User) ctx.user();
String verify_code = ctx.param("v_code", "");
if (!user.IsCurrentUser(verify_code))
throw ctx.error("operation_forbidden");
long id = ctx.id();
int value = ctx.param("type", Vote.VOTE_LOVE);
if (Vote.INSTANCE.isVoteExist(user.getId(), id))
throw ctx.error("cannot_repeat_vote");
Code code = Code.INSTANCE.Get(id);
if (null == code)
throw ctx.error("code_not_exist");
else if (code.getUser() == user.getId())
throw ctx.error("can_not_vote_self");
else {
Vote vote = new Vote();
vote.setCreate_time(new Timestamp(new Date().getTime()));
vote.setCode(id);
vote.setUser(user.getId());
vote.setValue(value);
if (0 < vote.Save()) {
if (vote.getValue() > 0) {
Dynamic.INSTANCE.add_up_dy(user, code);
// TODO 添加通知
String notify = ResourceUtils.getString("description",
"vote_notify", user.getName(), code.getIdent(),
code.getName(), code.getIdent());
Msg.INSTANCE.addMsg(vote.getUser(), code.getUser(),
Msg.TYPE_UP, code.getId(), notify);
}
Vote.evictCache(vote.CacheRegion(), Vote.VOTE_COUNT + id);
ctx.print(gson.toJson(vote));
} else
throw ctx.error("operation_failed");
}
}
/**
* 发布代码
*
* @param ctx
* @throws IOException
*/
@PostMethod
@UserRoleRequired
@JSONOutputEnabled
public void post(RequestContext ctx) throws IOException {
User user = (User) ctx.user();
String verify_code = ctx.param("v_code", "");
if (!user.IsCurrentUser(verify_code))
throw ctx.error("operation_forbidden");
long id = ctx.id();
Code code = Code.INSTANCE.Get(id);
if (null == code)
throw ctx.error("code_not_exist");
// 权限检查
if (null == user || (!user.IsAdmin(code)))
throw ctx.error("operation_forbidden");
String description = ctx.param("description", "").trim();
if (StringUtils.isBlank(description) || description.length() > 300)
throw ctx.error("description_error");
if (code.post(description)) {
ctx.print(gson.toJson(code));
} else
throw ctx.error("operation_failed");
}
/**
* 用户收藏
*
* @param ctx
* @throws IOException
*/
@PostMethod
@UserRoleRequired
@JSONOutputEnabled
public void favor(RequestContext ctx) throws IOException {
User user = (User) ctx.user();
String verify_code = ctx.param("v_code", "");
if (!user.IsCurrentUser(verify_code))
throw ctx.error("operation_forbidden");
long code_id = ctx.id();
Code code = Code.INSTANCE.Get(code_id);
if (null == code)
throw ctx.error("code_not_exist");
if (code.IsFavor(user.getId()))
throw ctx.error("favor_exist");
Favor favor = new Favor();
favor.setCode(code_id);
favor.setUser(user.getId());
favor.setStatus(Favor.NOTNEW);
favor.setCode_ident(code.getIdent());
favor.setCreate_time(new Timestamp(new Date().getTime()));
if (0 != favor.Save()) {
// 清除缓存
favor.evictCache(user, code_id);
ctx.print(gson.toJson(favor));
} else
throw ctx.error("operation_failed");
}
/**
* 取消收藏
*
* @param ctx
* @throws IOException
*/
@PostMethod
@UserRoleRequired
@JSONOutputEnabled
public void un_favor(RequestContext ctx) throws IOException {
User user = (User) ctx.user();
String verify_code = ctx.param("v_code", "");
if (!user.IsCurrentUser(verify_code))
throw ctx.error("operation_forbidden");
long code_id = ctx.id();
Code code = Code.INSTANCE.Get(code_id);
if (!code.IsFavor(user.getId()))
throw ctx.error("favor_not_exist");
Favor favor = Favor.INSTANCE.getFavorByCodeAndUser(user.getId(),
code_id);
if (null == favor)
throw ctx.error("favor_not_exist");
if (favor.Delete()) {
// 清除缓存
favor.evictCache(user, code_id);
ctx.print(gson.toJson(favor));
} else
throw ctx.error("operation_failed");
}
/**
* 验证码
*
* @param ctx
* @throws IOException
*/
public void captcha(RequestContext ctx) throws IOException {
ImageCaptchaService.get(ctx);
}
}
|
gpl-3.0
|
Tikaji/PowerPylons
|
src/main/java/com/tikaji/powerpylons/tileentity/base/GenericTileEntity.java
|
301
|
package com.tikaji.powerpylons.tileentity.base;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ITickable;
/**
* Created by Tikaji on 5/26/2016.
*/
public abstract class GenericTileEntity extends TileEntity implements ITickable
{
@Override
public abstract void update();
}
|
gpl-3.0
|
jdupl/iot-greenhouse-ctrl
|
gpio.py
|
616
|
class RPiGPIOWrapper():
# Implementation for Raspberry pi 1 to 3
# Pin ID are BCM numbering
def __init__(self, bcm_pin_id):
import RPi.GPIO as _GPIO
self.GPIO = _GPIO
self.pin_id = bcm_pin_id
def output(self, value):
self.__setup()
print('outputting %s to %d' % (value, self.pin_id))
self.GPIO.output(self.pin_id, value)
def cleanup(self):
self.GPIO.cleanup()
def __setup(self):
self.GPIO.setwarnings(False)
self.GPIO.setmode(self.GPIO.BCM)
self.GPIO.setup(self.pin_id, self.GPIO.OUT, initial=self.GPIO.HIGH)
|
gpl-3.0
|
jahuth/convis
|
convis/io.py
|
1018
|
import json
import numpy as np
from future.utils import iteritems as _iteritems
def _var_to_json_safe(v):
if hasattr(v,'get_value'):
v = v.get_value()
if type(v) is np.ndarray:
return v.tolist()
return v
def _json_safe_to_value(v):
if type(v) is list:
try:
return np.array(v)
except:
return v
return v
def save_dict_to_json(filename,d):
"""
Saves a (flat) dictionary that can also contain numpy
arrays to a json file.
"""
with open(filename,'w') as fp:
dat = [(p,_var_to_json_safe(param)) for (p,param) in _iteritems(d)]
json.dump(dict(dat), fp)
def load_dict_from_json(filename):
"""
Loads a (flat) dictionary from a json file and converts
lists back into numpy arrays.
"""
with open(filename,'r') as fp:
dat = json.load(fp)
assert(type(dat) == dict)
dat = dict([(p,_json_safe_to_value(param)) for (p,param) in _iteritems(dat)])
return dat
|
gpl-3.0
|
MaWiMa/hip
|
history/winkelfunction_pyramid.rb
|
1145
|
#!/usr/bin/ruby
# Norbert Reschke, 2015-06-18, s. Skizze
# Gerade Pyramide mit regelmäßiger Grundfläche
# a=Kantenlaengen, h=Hoehe
a = ARGV[0].to_f
h = ARGV[1].to_f
if (a == 0.0 or h == 0.0) and h != a # beide Werte 0, z.B. keine Parameterangabe, dann wird 1.0 gesetzt, s. b==a
puts "a und b müssen ein Wert größer 0 haben!"
exit
elsif h == 0 and a == 0 then
a,h = 1.0,1.0
end
ha = Math.sqrt( a**2/4 + h**2 )
g = Math.sqrt( a**2/4 + ha**2 )
hg = a*ha/g # hg = a * sin beta
# Schmiegen
alpha = Math.asin(h/ha)
beta = Math.asin(ha/g)
omega = Math.asin((Math.sqrt(2)*a/2)/hg) # asin(0.5d/hg)
# Bogenmass in Grad
alpha = alpha * 180.0 / Math::PI
beta = beta * 180.0 / Math::PI
omega = omega * 180.0 / Math::PI
puts "Gerade Pyramide mit regelmäßiger, #{n}-eckiger, Grundfläche"
puts "Seitenlänge, a: #{a}"
puts "Höhe der Pyramide, h: #{h}"
puts "Höhe auf a, ha #{ha}"
puts "Grat der Pyramide, g: #{g}"
puts "Grathöhe zum Eckpunkt, hg: #{hg}"
puts "Winkel alpha: #{alpha}"
puts "Winkel beta: #{beta}"
puts "Winkel omega: #{omega}"
|
gpl-3.0
|
sapphon/minecraftpython
|
src/main/java/org/sapphon/minecraft/modding/base/CombinedClientProxy.java
|
490
|
package org.sapphon.minecraft.modding.base;
import org.sapphon.minecraft.modding.minecraftpython.command.ClientTickHandler;
import org.sapphon.minecraft.modding.minecraftpython.command.ServerTickHandler;
import cpw.mods.fml.common.FMLCommonHandler;
public class CombinedClientProxy extends CommonProxy {
public CombinedClientProxy() {
FMLCommonHandler.instance().bus()
.register(new ClientTickHandler());
FMLCommonHandler.instance().bus().register(new ServerTickHandler());
}
}
|
gpl-3.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.